Skip to content

Commit

Permalink
Merge pull request #2469 from nspcc-dev/hardfork
Browse files Browse the repository at this point in the history
core: add ability to create hard-forks
  • Loading branch information
roman-khimov authored May 12, 2022
2 parents b7d3dd1 + 4d4f616 commit 7fd0eb1
Show file tree
Hide file tree
Showing 12 changed files with 172 additions and 3 deletions.
2 changes: 2 additions & 0 deletions config/protocol.unit_testnet.single.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions config/protocol.unit_testnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions docs/node-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
31 changes: 31 additions & 0 deletions pkg/config/hardfork.go
Original file line number Diff line number Diff line change
@@ -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
}
24 changes: 24 additions & 0 deletions pkg/config/hardfork_string.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions pkg/config/protocol_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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")
}
Expand Down
6 changes: 6 additions & 0 deletions pkg/config/protocol_config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
4 changes: 4 additions & 0 deletions pkg/core/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
14 changes: 13 additions & 1 deletion pkg/core/interop/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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.
}
22 changes: 22 additions & 0 deletions pkg/core/interop_system.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand All @@ -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
}
Expand Down
57 changes: 57 additions & 0 deletions pkg/core/interop_system_neotest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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"
Expand Down Expand Up @@ -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)
}
4 changes: 2 additions & 2 deletions pkg/core/interops.go
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down

0 comments on commit 7fd0eb1

Please sign in to comment.