Merge pull request #2469 from nspcc-dev/hardfork

core: add ability to create hard-forks
This commit is contained in:
Roman Khimov 2022-05-12 14:05:48 +03:00 committed by GitHub
commit 7fd0eb14b5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 172 additions and 3 deletions

View file

@ -20,6 +20,8 @@ ProtocolConfiguration:
RoleManagement: [0]
OracleContract: [0]
Notary: [0]
Hardforks:
HF_2712_FixSyscallFees: 25
ApplicationConfiguration:
# LogPath could be set up in case you need stdout logs to some proper file.

View file

@ -29,6 +29,8 @@ ProtocolConfiguration:
RoleManagement: [0]
OracleContract: [0]
Notary: [0]
Hardforks:
HF_2712_FixSyscallFees: 25
ApplicationConfiguration:
# LogPath could be set up in case you need stdout logs to some proper file.

View file

@ -204,6 +204,7 @@ protocol-related settings described in the table below.
| --- | --- | --- | --- | --- |
| CommitteeHistory | map[uint32]int | none | Number of committee members after the given height, for example `{0: 1, 20: 4}` sets up a chain with one committee member since the genesis and then changes the setting to 4 committee members at the height of 20. `StandbyCommittee` committee setting must have the number of keys equal or exceeding the highest value in this option. Blocks numbers where the change happens must be divisible by the old and by the new values simultaneously. If not set, committee size is derived from the `StandbyCommittee` setting and never changes. |
| GarbageCollectionPeriod | `uint32` | 10000 | Controls MPT garbage collection interval (in blocks) for configurations with `RemoveUntraceableBlocks` enabled and `KeepOnlyLatestState` disabled. In this mode the node stores a number of MPT trees (corresponding to `MaxTraceableBlocks` and `StateSyncInterval`), but the DB needs to be clean from old entries from time to time. Doing it too often will cause too much processing overhead, doing it too rarely will leave more useless data in the DB. |
| Hardforks | `map[string]uint32` | [] | The set of incompatible changes that affect node behaviour starting from the specified height. The default value is an empty set which should be interpreted as "each known hard-fork is applied from the zero blockchain height". The list of valid hard-fork names:<br>`HF_2712_FixSyscallFees` represents hard-fork introduced in [#2469](https://github.com/nspcc-dev/neo-go/pull/2469) (ported from the [reference](https://github.com/neo-project/neo/pull/2712)). It adjusts the prices of `System.Contract.CreateStandardAccount` and `System.Contract.CreateMultisigAccount` interops so that the resulting prices are in accordance with `sha256` method of native `CryptoLib` contract. |
| KeepOnlyLatestState | `bool` | `false` | Specifies if MPT should only store latest state. If true, DB size will be smaller, but older roots won't be accessible. This value should remain th
e same for the same database. | Conflicts with `P2PStateExchangeExtensions`. |
| Magic | `uint32` | `0` | Magic number which uniquely identifies NEO network. |

31
pkg/config/hardfork.go Normal file
View file

@ -0,0 +1,31 @@
package config
//go:generate stringer -type=Hardfork -linecomment
// Hardfork represents the application hard-fork identifier.
type Hardfork byte
const (
// HF2712FixSyscallFees represents hard-fork introduced in #2469 (ported from
// https://github.com/neo-project/neo/pull/2712) changing the prices of
// System.Contract.CreateStandardAccount and
// System.Contract.CreateMultisigAccount interops.
HF2712FixSyscallFees Hardfork = 1 << iota // HF_2712_FixSyscallFees
)
// hardforks holds a map of Hardfork string representation to its type.
var hardforks map[string]Hardfork
func init() {
hardforks = make(map[string]Hardfork)
for _, hf := range []Hardfork{HF2712FixSyscallFees} {
hardforks[hf.String()] = hf
}
}
// IsHardforkValid denotes whether the provided string represents a valid
// Hardfork name.
func IsHardforkValid(s string) bool {
_, ok := hardforks[s]
return ok
}

View file

@ -0,0 +1,24 @@
// Code generated by "stringer -type Hardfork -linecomment ./pkg/config/hardfork.go"; DO NOT EDIT.
package config
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[HF2712FixSyscallFees-1]
}
const _Hardfork_name = "HF_2712_FixSyscallFees"
var _Hardfork_index = [...]uint8{0, 22}
func (i Hardfork) String() string {
i -= 1
if i >= Hardfork(len(_Hardfork_index)-1) {
return "Hardfork(" + strconv.FormatInt(int64(i+1), 10) + ")"
}
return _Hardfork_name[_Hardfork_index[i]:_Hardfork_index[i+1]]
}

View file

@ -23,6 +23,9 @@ type (
Magic netmode.Magic `yaml:"Magic"`
MemPoolSize int `yaml:"MemPoolSize"`
// Hardforks is a map of hardfork names that enables version-specific application
// logic dependent on the specified height.
Hardforks map[string]uint32 `yaml:"Hardforks"`
// InitialGASSupply is the amount of GAS generated in the genesis block.
InitialGASSupply fixedn.Fixed8 `yaml:"InitialGASSupply"`
// P2PNotaryRequestPayloadPoolSize specifies the memory pool size for P2PNotaryRequestPayloads.
@ -94,6 +97,11 @@ func (p *ProtocolConfiguration) Validate() error {
return fmt.Errorf("NativeActivations configuration section contains unexpected native contract name: %s", name)
}
}
for name := range p.Hardforks {
if !IsHardforkValid(name) {
return fmt.Errorf("Hardforks configuration section contains unexpected hardfork: %s", name)
}
}
if p.ValidatorsCount != 0 && len(p.ValidatorsHistory) != 0 {
return errors.New("configuration should either have ValidatorsCount or ValidatorsHistory, not both")
}

View file

@ -100,6 +100,12 @@ func TestProtocolConfigurationValidation(t *testing.T) {
ValidatorsHistory: map[uint32]int{0: 4, 100: 4},
}
require.Error(t, p.Validate())
p = &ProtocolConfiguration{
Hardforks: map[string]uint32{
"HF_Unknown": 123, // Unknown hard-fork.
},
}
require.Error(t, p.Validate())
p = &ProtocolConfiguration{
StandbyCommittee: []string{
"02b3622bf4017bdfe317c58aed5f4c753f206b7db896046fa7d774bbc4bf7f8dc2",

View file

@ -259,6 +259,10 @@ func NewBlockchain(s storage.Store, cfg config.ProtocolConfiguration, log *zap.L
cfg.NativeUpdateHistories = map[string][]uint32{}
log.Info("NativeActivations are not set, using default values")
}
if cfg.Hardforks == nil {
cfg.Hardforks = map[string]uint32{}
log.Info("Hardforks are not set, using default value")
}
bc := &Blockchain{
config: cfg,
dao: dao.NewSimple(s, cfg.StateRootInHeader, cfg.P2PSigExtensions),

View file

@ -48,6 +48,7 @@ type Context struct {
Chain Ledger
Container hash.Hashable
Network uint32
Hardforks map[string]uint32
Natives []Contract
Trigger trigger.Type
Block *block.Block
@ -71,9 +72,11 @@ func NewContext(trigger trigger.Type, bc Ledger, d *dao.Simple, baseExecFee, bas
getContract func(*dao.Simple, util.Uint160) (*state.Contract, error), natives []Contract,
block *block.Block, tx *transaction.Transaction, log *zap.Logger) *Context {
dao := d.GetPrivate()
cfg := bc.GetConfig()
return &Context{
Chain: bc,
Network: uint32(bc.GetConfig().Magic),
Network: uint32(cfg.Magic),
Hardforks: cfg.Hardforks,
Natives: natives,
Trigger: trigger,
Block: block,
@ -368,3 +371,12 @@ func (ic *Context) GetBlock(hash util.Uint256) (*block.Block, error) {
}
return block, nil
}
// IsHardforkEnabled tells whether specified hard-fork enabled at the current context height.
func (ic *Context) IsHardforkEnabled(hf config.Hardfork) bool {
height, ok := ic.Hardforks[hf.String()]
if ok {
return ic.BlockHeight() >= height
}
return len(ic.Hardforks) == 0 // Enable each hard-fork by default.
}

View file

@ -8,7 +8,9 @@ import (
"math"
"math/big"
"github.com/nspcc-dev/neo-go/pkg/config"
"github.com/nspcc-dev/neo-go/pkg/core/block"
"github.com/nspcc-dev/neo-go/pkg/core/fee"
"github.com/nspcc-dev/neo-go/pkg/core/interop"
istorage "github.com/nspcc-dev/neo-go/pkg/core/interop/storage"
"github.com/nspcc-dev/neo-go/pkg/core/native"
@ -215,6 +217,16 @@ func contractCreateMultisigAccount(ic *interop.Context) error {
}
pubs[i] = p
}
var invokeFee int64
if ic.IsHardforkEnabled(config.HF2712FixSyscallFees) {
invokeFee = fee.ECDSAVerifyPrice * int64(len(pubs))
} else {
invokeFee = 1 << 8
}
invokeFee *= ic.BaseExecFee()
if !ic.VM.AddGas(invokeFee) {
return errors.New("gas limit exceeded")
}
script, err := smartcontract.CreateMultiSigRedeemScript(int(mu64), pubs)
if err != nil {
return err
@ -230,6 +242,16 @@ func contractCreateStandardAccount(ic *interop.Context) error {
if err != nil {
return err
}
var invokeFee int64
if ic.IsHardforkEnabled(config.HF2712FixSyscallFees) {
invokeFee = fee.ECDSAVerifyPrice
} else {
invokeFee = 1 << 8
}
invokeFee *= ic.BaseExecFee()
if !ic.VM.AddGas(invokeFee) {
return errors.New("gas limit exceeded")
}
ic.VM.Estack().PushItem(stackitem.NewByteArray(p.GetScriptHash().BytesBE()))
return nil
}

View file

@ -7,6 +7,7 @@ import (
"testing"
"github.com/nspcc-dev/neo-go/internal/contracts"
"github.com/nspcc-dev/neo-go/pkg/config"
"github.com/nspcc-dev/neo-go/pkg/core/interop"
"github.com/nspcc-dev/neo-go/pkg/core/interop/interopnames"
"github.com/nspcc-dev/neo-go/pkg/core/native/nativenames"
@ -19,6 +20,7 @@ import (
"github.com/nspcc-dev/neo-go/pkg/neotest/chain"
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
"github.com/nspcc-dev/neo-go/pkg/vm/emit"
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
"github.com/stretchr/testify/require"
@ -254,3 +256,58 @@ func TestSystemRuntimeBurnGas(t *testing.T) {
cInvoker.InvokeFail(t, "GAS must be positive", "burnGas", int64(0))
})
}
func TestSystemContractCreateAccount_Hardfork(t *testing.T) {
bc, acc := chain.NewSingleWithCustomConfig(t, func(c *config.ProtocolConfiguration) {
c.P2PSigExtensions = true // `initBasicChain` requires Notary enabled
c.Hardforks = map[string]uint32{
config.HF2712FixSyscallFees.String(): 2,
}
})
e := neotest.NewExecutor(t, bc, acc, acc)
priv, err := keys.NewPrivateKey()
require.NoError(t, err)
pub := priv.PublicKey()
w := io.NewBufBinWriter()
emit.Array(w.BinWriter, []interface{}{pub.Bytes(), pub.Bytes(), pub.Bytes()}...)
emit.Int(w.BinWriter, int64(2))
emit.Syscall(w.BinWriter, interopnames.SystemContractCreateMultisigAccount)
require.NoError(t, w.Err)
multisigScript := slice.Copy(w.Bytes())
w.Reset()
emit.Bytes(w.BinWriter, pub.Bytes())
emit.Syscall(w.BinWriter, interopnames.SystemContractCreateStandardAccount)
require.NoError(t, w.Err)
standardScript := slice.Copy(w.Bytes())
createAccTx := func(t *testing.T, script []byte) *transaction.Transaction {
tx := e.PrepareInvocation(t, script, []neotest.Signer{e.Committee}, bc.BlockHeight()+1)
return tx
}
// blocks #1, #2: old prices
tx1Standard := createAccTx(t, standardScript)
tx1Multisig := createAccTx(t, multisigScript)
e.AddNewBlock(t, tx1Standard, tx1Multisig)
e.CheckHalt(t, tx1Standard.Hash())
e.CheckHalt(t, tx1Multisig.Hash())
tx2Standard := createAccTx(t, standardScript)
tx2Multisig := createAccTx(t, multisigScript)
e.AddNewBlock(t, tx2Standard, tx2Multisig)
e.CheckHalt(t, tx2Standard.Hash())
e.CheckHalt(t, tx2Multisig.Hash())
// block #3: updated prices (larger than the previous ones)
tx3Standard := createAccTx(t, standardScript)
tx3Multisig := createAccTx(t, multisigScript)
e.AddNewBlock(t, tx3Standard, tx3Multisig)
e.CheckHalt(t, tx3Standard.Hash())
e.CheckHalt(t, tx3Multisig.Hash())
require.True(t, tx1Standard.SystemFee == tx2Standard.SystemFee)
require.True(t, tx1Multisig.SystemFee == tx2Multisig.SystemFee)
require.True(t, tx2Standard.SystemFee < tx3Standard.SystemFee)
require.True(t, tx2Multisig.SystemFee < tx3Multisig.SystemFee)
}

View file

@ -33,8 +33,8 @@ var systemInterops = []interop.Function{
{Name: interopnames.SystemContractCall, Func: contract.Call, Price: 1 << 15,
RequiredFlags: callflag.ReadStates | callflag.AllowCall, ParamCount: 4},
{Name: interopnames.SystemContractCallNative, Func: native.Call, Price: 0, ParamCount: 1},
{Name: interopnames.SystemContractCreateMultisigAccount, Func: contractCreateMultisigAccount, Price: 1 << 8, ParamCount: 2},
{Name: interopnames.SystemContractCreateStandardAccount, Func: contractCreateStandardAccount, Price: 1 << 8, ParamCount: 1},
{Name: interopnames.SystemContractCreateMultisigAccount, Func: contractCreateMultisigAccount, Price: 0, ParamCount: 2},
{Name: interopnames.SystemContractCreateStandardAccount, Func: contractCreateStandardAccount, Price: 0, ParamCount: 1},
{Name: interopnames.SystemContractGetCallFlags, Func: contractGetCallFlags, Price: 1 << 10},
{Name: interopnames.SystemContractNativeOnPersist, Func: native.OnPersist, Price: 0, RequiredFlags: callflag.States},
{Name: interopnames.SystemContractNativePostPersist, Func: native.PostPersist, Price: 0, RequiredFlags: callflag.States},