github.com/klaytn/klaytn@v1.12.1/params/governance_paramset.go (about) 1 package params 2 3 import ( 4 "bytes" 5 "errors" 6 "math/big" 7 "reflect" 8 "strconv" 9 "strings" 10 11 "github.com/klaytn/klaytn/common" 12 "github.com/klaytn/klaytn/common/hexutil" 13 "github.com/klaytn/klaytn/log" 14 ) 15 16 var ( 17 errUnknownGovParamKey = errors.New("Unknown governance param key") 18 errUnknownGovParamName = errors.New("Unknown governance param name") 19 errBadGovParamValue = errors.New("Malformed governance param value") 20 ) 21 22 type govParamType struct { 23 // The canonical type 24 canonicalType reflect.Type 25 26 // Parse arbitrary typed value into canonical type 27 // Return false if not possible 28 // Used to parse or normalize database content. 29 parseValue func(v interface{}) (interface{}, bool) 30 31 // Parse byte array into canonical type 32 // Return false if not possible 33 // Used to parse solidity contract content. 34 parseBytes func(b []byte) (interface{}, bool) 35 36 // Application-specific checks. 37 // It is safe to assume that type of 'v' is canonicalType 38 validate func(v interface{}) bool 39 } 40 41 func (ty *govParamType) ParseValue(v interface{}) (interface{}, bool) { 42 if x, ok := ty.parseValue(v); ok { 43 return x, ty.Validate(x) 44 } else { 45 return nil, false 46 } 47 } 48 49 func (ty *govParamType) ParseBytes(b []byte) (interface{}, bool) { 50 if x, ok := ty.parseBytes(b); ok { 51 return x, ty.Validate(x) 52 } else { 53 return nil, false 54 } 55 } 56 57 func (ty *govParamType) Validate(v interface{}) bool { 58 // return ty.canonicalType == reflect.TypeOf(v) && ty.validate(v) 59 if ty.canonicalType != reflect.TypeOf(v) { 60 return false 61 } 62 if ty.validate != nil && !ty.validate(v) { 63 return false 64 } 65 return true 66 } 67 68 var ( 69 govModeNames = map[string]int{ 70 "none": GovernanceMode_None, 71 "single": GovernanceMode_Single, 72 "ballot": GovernanceMode_Ballot, 73 } 74 75 parseValueString = func(v interface{}) (interface{}, bool) { 76 s, ok := v.(string) 77 return s, ok 78 } 79 parseBytesString = func(b []byte) (interface{}, bool) { 80 return string(b), true 81 } 82 validatePass = func(v interface{}) bool { 83 return true 84 } 85 86 uint64ByteLen = int(reflect.TypeOf(uint64(0)).Size()) 87 88 govParamTypeGovMode = &govParamType{ 89 canonicalType: reflect.TypeOf("single"), 90 parseValue: parseValueString, 91 parseBytes: parseBytesString, 92 validate: func(v interface{}) bool { 93 _, ok := govModeNames[v.(string)] 94 return ok 95 }, 96 } 97 98 govParamTypeAddress = &govParamType{ 99 canonicalType: reflect.TypeOf(common.Address{}), 100 parseValue: func(v interface{}) (interface{}, bool) { 101 switch v.(type) { 102 case string: 103 s := v.(string) 104 return common.HexToAddress(s), common.IsHexAddress(s) 105 case common.Address: 106 return v, true 107 default: 108 return nil, false 109 } 110 }, 111 parseBytes: func(b []byte) (interface{}, bool) { 112 return common.BytesToAddress(b), len(b) == common.AddressLength 113 }, 114 validate: validatePass, 115 } 116 117 govParamTypeUint64 = &govParamType{ 118 canonicalType: reflect.TypeOf(uint64(0)), 119 parseValue: func(v interface{}) (interface{}, bool) { 120 switch v.(type) { 121 case int: 122 return uint64(v.(int)), v.(int) >= 0 123 case uint: 124 return uint64(v.(uint)), true 125 case uint64: 126 return v.(uint64), true 127 case float64: 128 return uint64(v.(float64)), v.(float64) >= 0 129 default: 130 return nil, false 131 } 132 }, 133 parseBytes: func(b []byte) (interface{}, bool) { 134 // Must not exceed uint64 range 135 return new(big.Int).SetBytes(b).Uint64(), len(b) <= uint64ByteLen 136 }, 137 validate: validatePass, 138 } 139 140 govParamTypeBigInt = &govParamType{ 141 canonicalType: reflect.TypeOf(""), 142 parseValue: func(v interface{}) (interface{}, bool) { 143 switch v.(type) { 144 case string: 145 return v.(string), true 146 case *big.Int: 147 return v.(*big.Int).String(), true 148 default: 149 return nil, false 150 } 151 }, 152 parseBytes: parseBytesString, 153 validate: func(v interface{}) bool { 154 if n, ok := new(big.Int).SetString(v.(string), 10); ok { 155 return n.Sign() >= 0 // must be non-negative. 156 } 157 return false 158 }, 159 } 160 161 govParamTypeRatio = &govParamType{ 162 canonicalType: reflect.TypeOf("12/34/54"), 163 parseValue: parseValueString, 164 parseBytes: parseBytesString, 165 validate: func(v interface{}) bool { 166 strs := strings.Split(v.(string), "/") 167 if len(strs) != RewardSliceCount { 168 return false 169 } 170 sum := 0 171 for _, s := range strs { 172 n, err := strconv.Atoi(s) 173 if err != nil || n < 0 { 174 return false 175 } 176 sum += n 177 } 178 return sum == 100 179 }, 180 } 181 182 govParamTypeKip82Ratio = &govParamType{ 183 canonicalType: reflect.TypeOf("20/80"), 184 parseValue: parseValueString, 185 parseBytes: parseBytesString, 186 validate: func(v interface{}) bool { 187 strs := strings.Split(v.(string), "/") 188 if len(strs) != RewardKip82SliceCount { 189 return false 190 } 191 sum := 0 192 for _, s := range strs { 193 n, err := strconv.Atoi(s) 194 if err != nil || n < 0 { 195 return false 196 } 197 sum += n 198 } 199 return sum == 100 200 }, 201 } 202 203 govParamTypeBool = &govParamType{ 204 canonicalType: reflect.TypeOf(true), 205 parseValue: func(v interface{}) (interface{}, bool) { 206 b, ok := v.(bool) 207 return b, ok 208 }, 209 parseBytes: func(b []byte) (interface{}, bool) { 210 if bytes.Compare(b, []byte{0x01}) == 0 { 211 return true, true 212 } else if bytes.Compare(b, []byte{0x00}) == 0 { 213 return false, true 214 } else { 215 return nil, false 216 } 217 }, 218 validate: validatePass, 219 } 220 ) 221 222 var govParamTypes = map[int]*govParamType{ 223 GovernanceMode: govParamTypeGovMode, 224 GoverningNode: govParamTypeAddress, 225 Epoch: govParamTypeUint64, 226 Policy: govParamTypeUint64, 227 CommitteeSize: govParamTypeUint64, 228 UnitPrice: govParamTypeUint64, 229 MintingAmount: govParamTypeBigInt, 230 Ratio: govParamTypeRatio, 231 Kip82Ratio: govParamTypeKip82Ratio, 232 UseGiniCoeff: govParamTypeBool, 233 DeferredTxFee: govParamTypeBool, 234 MinimumStake: govParamTypeBigInt, 235 StakeUpdateInterval: govParamTypeUint64, 236 ProposerRefreshInterval: govParamTypeUint64, 237 LowerBoundBaseFee: govParamTypeUint64, 238 UpperBoundBaseFee: govParamTypeUint64, 239 GasTarget: govParamTypeUint64, 240 MaxBlockGasUsedForBaseFee: govParamTypeUint64, 241 BaseFeeDenominator: govParamTypeUint64, 242 GovParamContract: govParamTypeAddress, 243 DeriveShaImpl: govParamTypeUint64, 244 } 245 246 var govParamNames = map[string]int{ 247 "governance.governancemode": GovernanceMode, 248 "governance.governingnode": GoverningNode, 249 "governance.govparamcontract": GovParamContract, 250 "istanbul.epoch": Epoch, 251 "istanbul.policy": Policy, 252 "istanbul.committeesize": CommitteeSize, 253 "governance.unitprice": UnitPrice, 254 "reward.mintingamount": MintingAmount, 255 "reward.ratio": Ratio, 256 "reward.kip82ratio": Kip82Ratio, 257 "reward.useginicoeff": UseGiniCoeff, 258 "reward.deferredtxfee": DeferredTxFee, 259 "reward.minimumstake": MinimumStake, 260 "reward.stakingupdateinterval": StakeUpdateInterval, 261 "reward.proposerupdateinterval": ProposerRefreshInterval, 262 "kip71.lowerboundbasefee": LowerBoundBaseFee, 263 "kip71.upperboundbasefee": UpperBoundBaseFee, 264 "kip71.gastarget": GasTarget, 265 "kip71.maxblockgasusedforbasefee": MaxBlockGasUsedForBaseFee, 266 "kip71.basefeedenominator": BaseFeeDenominator, 267 "governance.deriveshaimpl": DeriveShaImpl, 268 } 269 270 var govParamNamesReverse = map[int]string{} 271 272 func init() { 273 for name, key := range govParamNames { 274 govParamNamesReverse[key] = name 275 } 276 } 277 278 // GovParamSet is an immutable set of governance parameters 279 // with various convenience getters. 280 type GovParamSet struct { 281 // Items in canonical type. 282 // Only type checked and validated values will be stored. 283 items map[int]interface{} 284 } 285 286 func NewGovParamSet() *GovParamSet { 287 return &GovParamSet{ 288 items: make(map[int]interface{}), 289 } 290 } 291 292 // Return a new GovParamSet that contains keys from both input sets. 293 // If a key belongs to both sets, the value from `update` is used. 294 func NewGovParamSetMerged(base *GovParamSet, update *GovParamSet) *GovParamSet { 295 p := NewGovParamSet() 296 for key, value := range base.items { 297 p.items[key] = value 298 } 299 for key, value := range update.items { 300 p.items[key] = value 301 } 302 return p 303 } 304 305 func NewGovParamSetStrMap(items map[string]interface{}) (*GovParamSet, error) { 306 p := NewGovParamSet() 307 308 for name, value := range items { 309 key, ok := govParamNames[name] 310 if !ok { 311 return nil, errUnknownGovParamName 312 } 313 err := p.set(key, value) 314 if err != nil { 315 return nil, err 316 } 317 } 318 319 return p, nil 320 } 321 322 func NewGovParamSetIntMap(items map[int]interface{}) (*GovParamSet, error) { 323 p := NewGovParamSet() 324 325 for key, value := range items { 326 err := p.set(key, value) 327 if err != nil { 328 return nil, err 329 } 330 } 331 332 return p, nil 333 } 334 335 func NewGovParamSetBytesMap(items map[string][]byte) (*GovParamSet, error) { 336 p := NewGovParamSet() 337 338 for name, value := range items { 339 key, ok := govParamNames[name] 340 if !ok { 341 return nil, errUnknownGovParamName 342 } 343 err := p.setBytes(key, value) 344 if err != nil { 345 return nil, err 346 } 347 } 348 return p, nil 349 } 350 351 func NewGovParamSetBytesMapTolerant(items map[string][]byte) *GovParamSet { 352 p := NewGovParamSet() 353 354 for name, value := range items { 355 key, ok := govParamNames[name] 356 if !ok { 357 continue 358 } 359 p.setBytes(key, value) // this may fail but do not care 360 } 361 return p 362 } 363 364 func NewGovParamSetChainConfig(config *ChainConfig) (*GovParamSet, error) { 365 items := make(map[int]interface{}) 366 if config.Istanbul != nil { 367 items[Epoch] = config.Istanbul.Epoch 368 items[Policy] = config.Istanbul.ProposerPolicy 369 items[CommitteeSize] = config.Istanbul.SubGroupSize 370 } 371 items[UnitPrice] = config.UnitPrice 372 items[DeriveShaImpl] = config.DeriveShaImpl 373 if config.Governance != nil { 374 items[GoverningNode] = config.Governance.GoverningNode 375 items[GovernanceMode] = config.Governance.GovernanceMode 376 items[GovParamContract] = config.Governance.GovParamContract 377 if config.Governance.Reward != nil { 378 if config.Governance.Reward.MintingAmount != nil { 379 items[MintingAmount] = config.Governance.Reward.MintingAmount.String() 380 } 381 items[Ratio] = config.Governance.Reward.Ratio 382 // new parameters can be empty 383 if config.Governance.Reward.Kip82Ratio != "" { 384 items[Kip82Ratio] = config.Governance.Reward.Kip82Ratio 385 } 386 items[UseGiniCoeff] = config.Governance.Reward.UseGiniCoeff 387 items[DeferredTxFee] = config.Governance.Reward.DeferredTxFee 388 items[StakeUpdateInterval] = config.Governance.Reward.StakingUpdateInterval 389 items[ProposerRefreshInterval] = config.Governance.Reward.ProposerUpdateInterval 390 if config.Governance.Reward.MinimumStake != nil { 391 items[MinimumStake] = config.Governance.Reward.MinimumStake.String() 392 } 393 } 394 if config.Governance.KIP71 != nil { 395 items[LowerBoundBaseFee] = config.Governance.KIP71.LowerBoundBaseFee 396 items[UpperBoundBaseFee] = config.Governance.KIP71.UpperBoundBaseFee 397 items[GasTarget] = config.Governance.KIP71.GasTarget 398 items[MaxBlockGasUsedForBaseFee] = config.Governance.KIP71.MaxBlockGasUsedForBaseFee 399 items[BaseFeeDenominator] = config.Governance.KIP71.BaseFeeDenominator 400 } 401 } 402 403 return NewGovParamSetIntMap(items) 404 } 405 406 func (p *GovParamSet) set(key int, value interface{}) error { 407 ty, ok := govParamTypes[key] 408 if !ok { 409 return errUnknownGovParamKey 410 } 411 parsed, ok := ty.ParseValue(value) 412 if !ok { 413 logger.Error("Bad GovParam value", 414 "key", govParamNamesReverse[key], "value", value) 415 return errBadGovParamValue 416 } 417 p.items[key] = parsed 418 return nil 419 } 420 421 func (p *GovParamSet) setBytes(key int, bytes []byte) error { 422 ty, ok := govParamTypes[key] 423 if !ok { 424 return errUnknownGovParamKey 425 } 426 parsed, ok := ty.ParseBytes(bytes) 427 if !ok { 428 logger.Error("Bad GovParam value", 429 "key", govParamNamesReverse[key], "bytes", hexutil.Encode(bytes)) 430 return errBadGovParamValue 431 } 432 p.items[key] = parsed 433 return nil 434 } 435 436 func (p *GovParamSet) StrMap() map[string]interface{} { 437 m := map[string]interface{}{} 438 for key, value := range p.items { 439 m[govParamNamesReverse[key]] = value 440 } 441 return m 442 } 443 444 func (p *GovParamSet) IntMap() map[int]interface{} { 445 m := map[int]interface{}{} 446 for key, value := range p.items { 447 m[key] = value 448 } 449 return m 450 } 451 452 // Returns a parameter value and a boolean indicating success. 453 func (p *GovParamSet) Get(key int) (interface{}, bool) { 454 v, ok := p.items[key] 455 return v, ok 456 } 457 458 // Return a parameter value or return a nil if the key does not exist. 459 func (p *GovParamSet) MustGet(key int) interface{} { 460 if v, ok := p.Get(key); ok { 461 return v 462 } else { 463 logger := log.NewModuleLogger(log.Governance) 464 logger.Crit("Attempted to get missing GovParam item", "key", key, "name", govParamNamesReverse[key]) 465 return nil 466 } 467 } 468 469 func (p *GovParamSet) ToIstanbulConfig() *IstanbulConfig { 470 var ret IstanbulConfig 471 if _, ok := p.Get(Epoch); ok { 472 ret.Epoch = p.Epoch() 473 } 474 if _, ok := p.Get(Policy); ok { 475 ret.ProposerPolicy = p.Policy() 476 } 477 if _, ok := p.Get(CommitteeSize); ok { 478 ret.SubGroupSize = p.CommitteeSize() 479 } 480 481 return &ret 482 } 483 484 func (p *GovParamSet) ToRewardConfig() *RewardConfig { 485 var ret RewardConfig 486 if _, ok := p.Get(MintingAmount); ok { 487 ret.MintingAmount = p.MintingAmountBig() 488 } 489 if _, ok := p.Get(Ratio); ok { 490 ret.Ratio = p.Ratio() 491 } 492 if _, ok := p.Get(Kip82Ratio); ok { 493 ret.Kip82Ratio = p.Kip82Ratio() 494 } 495 if _, ok := p.Get(UseGiniCoeff); ok { 496 ret.UseGiniCoeff = p.UseGiniCoeff() 497 } 498 if _, ok := p.Get(DeferredTxFee); ok { 499 ret.DeferredTxFee = p.DeferredTxFee() 500 } 501 if _, ok := p.Get(StakeUpdateInterval); ok { 502 ret.StakingUpdateInterval = p.StakeUpdateInterval() 503 } 504 if _, ok := p.Get(ProposerRefreshInterval); ok { 505 ret.ProposerUpdateInterval = p.ProposerRefreshInterval() 506 } 507 if _, ok := p.Get(MinimumStake); ok { 508 ret.MinimumStake = p.MinimumStakeBig() 509 } 510 511 return &ret 512 } 513 514 func (p *GovParamSet) ToKIP71Config() *KIP71Config { 515 var ret KIP71Config 516 if _, ok := p.Get(LowerBoundBaseFee); ok { 517 ret.LowerBoundBaseFee = p.LowerBoundBaseFee() 518 } 519 if _, ok := p.Get(UpperBoundBaseFee); ok { 520 ret.UpperBoundBaseFee = p.UpperBoundBaseFee() 521 } 522 if _, ok := p.Get(GasTarget); ok { 523 ret.GasTarget = p.GasTarget() 524 } 525 if _, ok := p.Get(MaxBlockGasUsedForBaseFee); ok { 526 ret.MaxBlockGasUsedForBaseFee = p.MaxBlockGasUsedForBaseFee() 527 } 528 if _, ok := p.Get(BaseFeeDenominator); ok { 529 ret.BaseFeeDenominator = p.BaseFeeDenominator() 530 } 531 532 return &ret 533 } 534 535 func (p *GovParamSet) ToGovernanceConfig() *GovernanceConfig { 536 var ret GovernanceConfig 537 if _, ok := p.Get(GoverningNode); ok { 538 ret.GoverningNode = p.GoverningNode() 539 } 540 if _, ok := p.Get(GovernanceMode); ok { 541 ret.GovernanceMode = p.GovernanceModeStr() 542 } 543 if _, ok := p.Get(GovParamContract); ok { 544 ret.GovParamContract = p.GovParamContract() 545 } 546 ret.Reward = p.ToRewardConfig() 547 ret.KIP71 = p.ToKIP71Config() 548 549 return &ret 550 } 551 552 func (p *GovParamSet) ToChainConfig() *ChainConfig { 553 var ret ChainConfig 554 if _, ok := p.Get(UnitPrice); ok { 555 ret.UnitPrice = p.UnitPrice() 556 } 557 if _, ok := p.Get(DeriveShaImpl); ok { 558 ret.DeriveShaImpl = p.DeriveShaImpl() 559 } 560 ret.Istanbul = p.ToIstanbulConfig() 561 ret.Governance = p.ToGovernanceConfig() 562 563 return &ret 564 } 565 566 // Nominal getters. Shortcut for MustGet() + type assertion. 567 568 func (p *GovParamSet) GovernanceModeStr() string { 569 return p.MustGet(GovernanceMode).(string) 570 } 571 572 func (p *GovParamSet) GovernanceModeInt() int { 573 return govModeNames[p.GovernanceModeStr()] 574 } 575 576 func (p *GovParamSet) GoverningNode() common.Address { 577 return p.MustGet(GoverningNode).(common.Address) 578 } 579 580 func (p *GovParamSet) GovParamContract() common.Address { 581 return p.MustGet(GovParamContract).(common.Address) 582 } 583 584 func (p *GovParamSet) Epoch() uint64 { 585 return p.MustGet(Epoch).(uint64) 586 } 587 588 func (p *GovParamSet) Policy() uint64 { 589 return p.MustGet(Policy).(uint64) 590 } 591 592 func (p *GovParamSet) CommitteeSize() uint64 { 593 return p.MustGet(CommitteeSize).(uint64) 594 } 595 596 func (p *GovParamSet) UnitPrice() uint64 { 597 return p.MustGet(UnitPrice).(uint64) 598 } 599 600 func (p *GovParamSet) MintingAmountStr() string { 601 return p.MustGet(MintingAmount).(string) 602 } 603 604 func (p *GovParamSet) MintingAmountBig() *big.Int { 605 n, _ := new(big.Int).SetString(p.MintingAmountStr(), 10) 606 return n 607 } 608 609 func (p *GovParamSet) Ratio() string { 610 return p.MustGet(Ratio).(string) 611 } 612 613 func (p *GovParamSet) Kip82Ratio() string { 614 return p.MustGet(Kip82Ratio).(string) 615 } 616 617 func (p *GovParamSet) UseGiniCoeff() bool { 618 return p.MustGet(UseGiniCoeff).(bool) 619 } 620 621 func (p *GovParamSet) DeferredTxFee() bool { 622 return p.MustGet(DeferredTxFee).(bool) 623 } 624 625 func (p *GovParamSet) MinimumStakeStr() string { 626 return p.MustGet(MinimumStake).(string) 627 } 628 629 func (p *GovParamSet) MinimumStakeBig() *big.Int { 630 n, _ := new(big.Int).SetString(p.MinimumStakeStr(), 10) 631 return n 632 } 633 634 func (p *GovParamSet) StakeUpdateInterval() uint64 { 635 return p.MustGet(StakeUpdateInterval).(uint64) 636 } 637 638 func (p *GovParamSet) ProposerRefreshInterval() uint64 { 639 return p.MustGet(ProposerRefreshInterval).(uint64) 640 } 641 642 func (p *GovParamSet) Timeout() uint64 { 643 return p.MustGet(Timeout).(uint64) 644 } 645 646 func (p *GovParamSet) LowerBoundBaseFee() uint64 { 647 return p.MustGet(LowerBoundBaseFee).(uint64) 648 } 649 650 func (p *GovParamSet) UpperBoundBaseFee() uint64 { 651 return p.MustGet(UpperBoundBaseFee).(uint64) 652 } 653 654 func (p *GovParamSet) GasTarget() uint64 { 655 return p.MustGet(GasTarget).(uint64) 656 } 657 658 func (p *GovParamSet) MaxBlockGasUsedForBaseFee() uint64 { 659 return p.MustGet(MaxBlockGasUsedForBaseFee).(uint64) 660 } 661 662 func (p *GovParamSet) BaseFeeDenominator() uint64 { 663 return p.MustGet(BaseFeeDenominator).(uint64) 664 } 665 666 func (p *GovParamSet) DeriveShaImpl() int { 667 return int(p.MustGet(DeriveShaImpl).(uint64)) 668 }