Merge pull request #703 from nspcc-dev/fix/tests

core: verify headers in AddHeaders()
This commit is contained in:
Roman Khimov 2020-03-02 17:28:41 +03:00 committed by GitHub
commit 3fc0df7d88
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
16 changed files with 150 additions and 209 deletions

View file

@ -12,6 +12,7 @@ import (
"github.com/CityOfZion/neo-go/pkg/encoding/address" "github.com/CityOfZion/neo-go/pkg/encoding/address"
"github.com/CityOfZion/neo-go/pkg/network" "github.com/CityOfZion/neo-go/pkg/network"
"github.com/CityOfZion/neo-go/pkg/rpc/request" "github.com/CityOfZion/neo-go/pkg/rpc/request"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"go.uber.org/zap/zaptest" "go.uber.org/zap/zaptest"
) )
@ -38,12 +39,8 @@ func BenchmarkTXPerformanceTest(t *testing.B) {
t.ResetTimer() t.ResetTimer()
for n := 0; n < t.N; n++ { for n := 0; n < t.N; n++ {
if server.RelayTxn(data[n]) != network.RelaySucceed { assert.Equal(t, network.RelaySucceed, server.RelayTxn(data[n]))
t.Fail() assert.Equal(t, network.RelayAlreadyExists, server.RelayTxn(data[n]))
}
if server.RelayTxn(data[n]) != network.RelayAlreadyExists {
t.Fail()
}
} }
chain.Close() chain.Close()
} }

View file

@ -16,42 +16,37 @@ const exampleSavePath = exampleCompilePath + "/save"
type compilerTestCase struct { type compilerTestCase struct {
name string name string
function func() function func(*testing.T)
} }
func TestCompiler(t *testing.T) { func TestCompiler(t *testing.T) {
testCases := []compilerTestCase{ testCases := []compilerTestCase{
{ {
name: "TestCompile", name: "TestCompile",
function: func() { function: func(t *testing.T) {
infos, err := ioutil.ReadDir(examplePath) infos, err := ioutil.ReadDir(examplePath)
require.NoError(t, err) require.NoError(t, err)
for _, info := range infos { for _, info := range infos {
infos, err := ioutil.ReadDir(path.Join(examplePath, info.Name())) infos, err := ioutil.ReadDir(path.Join(examplePath, info.Name()))
require.NoError(t, err) require.NoError(t, err)
if len(infos) == 0 { require.False(t, len(infos) == 0, "detected smart contract folder with no contract in it")
t.Fatal("detected smart contract folder with no contract in it")
}
filename := filterFilename(infos) filename := filterFilename(infos)
targetPath := path.Join(examplePath, info.Name(), filename) targetPath := path.Join(examplePath, info.Name(), filename)
if err := compileFile(targetPath); err != nil { require.NoError(t, compileFile(targetPath))
t.Fatal(err)
}
} }
}, },
}, },
{ {
name: "TestCompileAndSave", name: "TestCompileAndSave",
function: func() { function: func(t *testing.T) {
infos, err := ioutil.ReadDir(exampleCompilePath) infos, err := ioutil.ReadDir(exampleCompilePath)
require.NoError(t, err) require.NoError(t, err)
err = os.MkdirAll(exampleSavePath, os.ModePerm) err = os.MkdirAll(exampleSavePath, os.ModePerm)
require.NoError(t, err) require.NoError(t, err)
outfile := exampleSavePath + "/test.avm" outfile := exampleSavePath + "/test.avm"
if _, err := compiler.CompileAndSave(exampleCompilePath+"/"+infos[0].Name(), &compiler.Options{Outfile: outfile}); err != nil { _, err = compiler.CompileAndSave(exampleCompilePath+"/"+infos[0].Name(), &compiler.Options{Outfile: outfile})
t.Fatal(err) require.NoError(t, err)
}
defer func() { defer func() {
err := os.RemoveAll(exampleSavePath) err := os.RemoveAll(exampleSavePath)
require.NoError(t, err) require.NoError(t, err)
@ -61,9 +56,7 @@ func TestCompiler(t *testing.T) {
} }
for _, tcase := range testCases { for _, tcase := range testCases {
t.Run(tcase.name, func(t *testing.T) { t.Run(tcase.name, tcase.function)
tcase.function()
})
} }
} }

View file

@ -51,9 +51,7 @@ func vmAndCompile(t *testing.T, src string) *vm.VM {
vm.RegisterInteropGetter(storePlugin.getInterop) vm.RegisterInteropGetter(storePlugin.getInterop)
b, err := compiler.Compile(strings.NewReader(src)) b, err := compiler.Compile(strings.NewReader(src))
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
vm.Load(b) vm.Load(b)
return vm return vm
} }

View file

@ -301,11 +301,16 @@ func (bc *Blockchain) AddBlock(block *block.Block) error {
if expectedHeight != block.Index { if expectedHeight != block.Index {
return fmt.Errorf("expected block %d, but passed block %d", expectedHeight, block.Index) return fmt.Errorf("expected block %d, but passed block %d", expectedHeight, block.Index)
} }
headerLen := bc.headerListLen()
if int(block.Index) == headerLen {
err := bc.addHeaders(bc.config.VerifyBlocks, block.Header())
if err != nil {
return err
}
}
if bc.config.VerifyBlocks { if bc.config.VerifyBlocks {
err := block.Verify() err := block.Verify()
if err == nil {
err = bc.VerifyBlock(block)
}
if err != nil { if err != nil {
return fmt.Errorf("block %s is invalid: %s", block.Hash().StringLE(), err) return fmt.Errorf("block %s is invalid: %s", block.Hash().StringLE(), err)
} }
@ -318,24 +323,37 @@ func (bc *Blockchain) AddBlock(block *block.Block) error {
} }
} }
} }
headerLen := bc.headerListLen()
if int(block.Index) == headerLen {
err := bc.AddHeaders(block.Header())
if err != nil {
return err
}
}
return bc.storeBlock(block) return bc.storeBlock(block)
} }
// AddHeaders processes the given headers and add them to the // AddHeaders processes the given headers and add them to the
// HeaderHashList. // HeaderHashList.
func (bc *Blockchain) AddHeaders(headers ...*block.Header) (err error) { func (bc *Blockchain) AddHeaders(headers ...*block.Header) error {
return bc.addHeaders(bc.config.VerifyBlocks, headers...)
}
func (bc *Blockchain) addHeaders(verify bool, headers ...*block.Header) (err error) {
var ( var (
start = time.Now() start = time.Now()
batch = bc.dao.store.Batch() batch = bc.dao.store.Batch()
) )
if len(headers) == 0 {
return nil
} else if verify {
// Verify that the chain of the headers is consistent.
var lastHeader *block.Header
if lastHeader, err = bc.GetHeader(headers[0].PrevHash); err != nil {
return fmt.Errorf("previous header was not found: %v", err)
}
for _, h := range headers {
if err = bc.verifyHeader(h, lastHeader); err != nil {
return
}
lastHeader = h
}
}
bc.headersOp <- func(headerList *HeaderHashList) { bc.headersOp <- func(headerList *HeaderHashList) {
oldlen := headerList.Len() oldlen := headerList.Len()
for _, h := range headers { for _, h := range headers {
@ -1101,19 +1119,17 @@ func (bc *Blockchain) ApplyPolicyToTxSet(txes []mempool.TxWithFee) []mempool.TxW
return txes return txes
} }
// VerifyBlock verifies block against its current state. func (bc *Blockchain) verifyHeader(currHeader, prevHeader *block.Header) error {
func (bc *Blockchain) VerifyBlock(block *block.Block) error { if prevHeader.Hash() != currHeader.PrevHash {
prevHeader, err := bc.GetHeader(block.PrevHash) return errors.New("previous header hash doesn't match")
if err != nil {
return errors.Wrap(err, "unable to get previous header")
} }
if prevHeader.Index+1 != block.Index { if prevHeader.Index+1 != currHeader.Index {
return errors.New("previous header index doesn't match") return errors.New("previous header index doesn't match")
} }
if prevHeader.Timestamp >= block.Timestamp { if prevHeader.Timestamp >= currHeader.Timestamp {
return errors.New("block is not newer than the previous one") return errors.New("block is not newer than the previous one")
} }
return bc.verifyBlockWitnesses(block, prevHeader) return bc.verifyHeaderWitnesses(currHeader, prevHeader)
} }
// verifyTx verifies whether a transaction is bonafide or not. // verifyTx verifies whether a transaction is bonafide or not.
@ -1678,16 +1694,16 @@ func (bc *Blockchain) verifyTxWitnesses(t *transaction.Transaction, block *block
return nil return nil
} }
// verifyBlockWitnesses is a block-specific implementation of VerifyWitnesses logic. // verifyHeaderWitnesses is a block-specific implementation of VerifyWitnesses logic.
func (bc *Blockchain) verifyBlockWitnesses(block *block.Block, prevHeader *block.Header) error { func (bc *Blockchain) verifyHeaderWitnesses(currHeader, prevHeader *block.Header) error {
var hash util.Uint160 var hash util.Uint160
if prevHeader == nil && block.PrevHash.Equals(util.Uint256{}) { if prevHeader == nil && currHeader.PrevHash.Equals(util.Uint256{}) {
hash = block.Script.ScriptHash() hash = currHeader.Script.ScriptHash()
} else { } else {
hash = prevHeader.NextConsensus hash = prevHeader.NextConsensus
} }
interopCtx := bc.newInteropContext(trigger.Verification, bc.dao.store, nil, nil) interopCtx := bc.newInteropContext(trigger.Verification, bc.dao.store, nil, nil)
return bc.verifyHashAgainstScript(hash, &block.Script, block.VerificationHash(), interopCtx, true) return bc.verifyHashAgainstScript(hash, &currHeader.Script, currHeader.VerificationHash(), interopCtx, true)
} }
func hashAndIndexToBytes(h util.Uint256, index uint32) []byte { func hashAndIndexToBytes(h util.Uint256, index uint32) []byte {

View file

@ -15,41 +15,48 @@ import (
func TestAddHeaders(t *testing.T) { func TestAddHeaders(t *testing.T) {
bc := newTestChain(t) bc := newTestChain(t)
h1 := newBlock(1).Header() defer bc.Close()
h2 := newBlock(2).Header() lastBlock := bc.topBlock.Load().(*block.Block)
h3 := newBlock(3).Header() h1 := newBlock(bc.config, 1, lastBlock.Hash()).Header()
h2 := newBlock(bc.config, 2, h1.Hash()).Header()
h3 := newBlock(bc.config, 3, h2.Hash()).Header()
if err := bc.AddHeaders(h1, h2, h3); err != nil { require.NoError(t, bc.AddHeaders())
t.Fatal(err) require.NoError(t, bc.AddHeaders(h1, h2))
} require.NoError(t, bc.AddHeaders(h2, h3))
assert.Equal(t, h3.Index, bc.HeaderHeight()) assert.Equal(t, h3.Index, bc.HeaderHeight())
assert.Equal(t, uint32(0), bc.BlockHeight()) assert.Equal(t, uint32(0), bc.BlockHeight())
assert.Equal(t, h3.Hash(), bc.CurrentHeaderHash()) assert.Equal(t, h3.Hash(), bc.CurrentHeaderHash())
// Add them again, they should not be added. // Add them again, they should not be added.
if err := bc.AddHeaders(h3, h2, h1); err != nil { require.Error(t, bc.AddHeaders(h3, h2, h1))
t.Fatal(err)
}
assert.Equal(t, h3.Index, bc.HeaderHeight()) assert.Equal(t, h3.Index, bc.HeaderHeight())
assert.Equal(t, uint32(0), bc.BlockHeight()) assert.Equal(t, uint32(0), bc.BlockHeight())
assert.Equal(t, h3.Hash(), bc.CurrentHeaderHash()) assert.Equal(t, h3.Hash(), bc.CurrentHeaderHash())
h4 := newBlock(bc.config, 4, h3.Hash().Reverse()).Header()
h5 := newBlock(bc.config, 5, h4.Hash()).Header()
assert.Error(t, bc.AddHeaders(h4, h5))
assert.Equal(t, h3.Index, bc.HeaderHeight())
assert.Equal(t, uint32(0), bc.BlockHeight())
assert.Equal(t, h3.Hash(), bc.CurrentHeaderHash())
h6 := newBlock(bc.config, 4, h3.Hash()).Header()
h6.Script.InvocationScript = nil
assert.Error(t, bc.AddHeaders(h6))
assert.Equal(t, h3.Index, bc.HeaderHeight())
assert.Equal(t, uint32(0), bc.BlockHeight())
assert.Equal(t, h3.Hash(), bc.CurrentHeaderHash())
} }
func TestAddBlock(t *testing.T) { func TestAddBlock(t *testing.T) {
const size = 3
bc := newTestChain(t) bc := newTestChain(t)
blocks := []*block.Block{ blocks, err := bc.genBlocks(size)
newBlock(1, newMinerTX()), require.NoError(t, err)
newBlock(2, newMinerTX()),
newBlock(3, newMinerTX()),
}
for i := 0; i < len(blocks); i++ {
if err := bc.AddBlock(blocks[i]); err != nil {
t.Fatal(err)
}
}
lastBlock := blocks[len(blocks)-1] lastBlock := blocks[len(blocks)-1]
assert.Equal(t, lastBlock.Index, bc.HeaderHeight()) assert.Equal(t, lastBlock.Index, bc.HeaderHeight())
@ -60,9 +67,8 @@ func TestAddBlock(t *testing.T) {
for _, block := range blocks { for _, block := range blocks {
key := storage.AppendPrefix(storage.DataBlock, block.Hash().BytesLE()) key := storage.AppendPrefix(storage.DataBlock, block.Hash().BytesLE())
if _, err := bc.dao.store.Get(key); err != nil { _, err := bc.dao.store.Get(key)
t.Fatalf("block %s not persisted", block.Hash()) require.NoErrorf(t, err, "block %s not persisted", block.Hash())
}
} }
assert.Equal(t, lastBlock.Index, bc.BlockHeight()) assert.Equal(t, lastBlock.Index, bc.BlockHeight())
@ -92,7 +98,7 @@ func TestScriptFromWitness(t *testing.T) {
func TestGetHeader(t *testing.T) { func TestGetHeader(t *testing.T) {
bc := newTestChain(t) bc := newTestChain(t)
block := newBlock(1, newMinerTX()) block := bc.newBlock(newMinerTX())
err := bc.AddBlock(block) err := bc.AddBlock(block)
assert.Nil(t, err) assert.Nil(t, err)
@ -103,7 +109,7 @@ func TestGetHeader(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, block.Header(), header) assert.Equal(t, block.Header(), header)
b2 := newBlock(2) b2 := bc.newBlock()
_, err = bc.GetHeader(b2.Hash()) _, err = bc.GetHeader(b2.Hash())
assert.Error(t, err) assert.Error(t, err)
assert.NoError(t, bc.persist()) assert.NoError(t, bc.persist())
@ -112,21 +118,14 @@ func TestGetHeader(t *testing.T) {
func TestGetBlock(t *testing.T) { func TestGetBlock(t *testing.T) {
bc := newTestChain(t) bc := newTestChain(t)
blocks := makeBlocks(100) blocks, err := bc.genBlocks(100)
require.NoError(t, err)
for i := 0; i < len(blocks); i++ {
if err := bc.AddBlock(blocks[i]); err != nil {
t.Fatal(err)
}
}
// Test unpersisted and persisted access // Test unpersisted and persisted access
for j := 0; j < 2; j++ { for j := 0; j < 2; j++ {
for i := 0; i < len(blocks); i++ { for i := 0; i < len(blocks); i++ {
block, err := bc.GetBlock(blocks[i].Hash()) block, err := bc.GetBlock(blocks[i].Hash())
if err != nil { require.NoErrorf(t, err, "can't get block %d: %s, attempt %d", i, err, j)
t.Fatalf("can't get block %d: %s, attempt %d", i, err, j)
}
assert.Equal(t, blocks[i].Index, block.Index) assert.Equal(t, blocks[i].Index, block.Index)
assert.Equal(t, blocks[i].Hash(), block.Hash()) assert.Equal(t, blocks[i].Hash(), block.Hash())
} }
@ -136,20 +135,15 @@ func TestGetBlock(t *testing.T) {
func TestHasBlock(t *testing.T) { func TestHasBlock(t *testing.T) {
bc := newTestChain(t) bc := newTestChain(t)
blocks := makeBlocks(50) blocks, err := bc.genBlocks(50)
require.NoError(t, err)
for i := 0; i < len(blocks); i++ {
if err := bc.AddBlock(blocks[i]); err != nil {
t.Fatal(err)
}
}
// Test unpersisted and persisted access // Test unpersisted and persisted access
for j := 0; j < 2; j++ { for j := 0; j < 2; j++ {
for i := 0; i < len(blocks); i++ { for i := 0; i < len(blocks); i++ {
assert.True(t, bc.HasBlock(blocks[i].Hash())) assert.True(t, bc.HasBlock(blocks[i].Hash()))
} }
newBlock := newBlock(51) newBlock := bc.newBlock()
assert.False(t, bc.HasBlock(newBlock.Hash())) assert.False(t, bc.HasBlock(newBlock.Hash()))
assert.NoError(t, bc.persist()) assert.NoError(t, bc.persist())
} }
@ -187,10 +181,8 @@ func TestClose(t *testing.T) {
assert.NotNil(t, r) assert.NotNil(t, r)
}() }()
bc := newTestChain(t) bc := newTestChain(t)
blocks := makeBlocks(10) _, err := bc.genBlocks(10)
for i := 0; i < len(blocks); i++ { require.NoError(t, err)
require.NoError(t, bc.AddBlock(blocks[i]))
}
bc.Close() bc.Close()
// It's a hack, but we use internal knowledge of MemoryStore // It's a hack, but we use internal knowledge of MemoryStore
// implementation which makes it completely unusable (up to panicing) // implementation which makes it completely unusable (up to panicing)

View file

@ -14,6 +14,7 @@ import (
// https://github.com/neo-project/neo/blob/master-2.x/neo.UnitTests/UT_InteropPrices.cs#L245 // https://github.com/neo-project/neo/blob/master-2.x/neo.UnitTests/UT_InteropPrices.cs#L245
func TestGetPrice(t *testing.T) { func TestGetPrice(t *testing.T) {
bc := newTestChain(t) bc := newTestChain(t)
defer bc.Close()
systemInterop := bc.newInteropContext(trigger.Application, storage.NewMemoryStore(), nil, nil) systemInterop := bc.newInteropContext(trigger.Application, storage.NewMemoryStore(), nil, nil)
v := bc.spawnVMWithInterops(systemInterop) v := bc.spawnVMWithInterops(systemInterop)

View file

@ -24,9 +24,6 @@ import (
"go.uber.org/zap/zaptest" "go.uber.org/zap/zaptest"
) )
var newBlockPrevHash util.Uint256
var unitTestNetCfg config.Config
var privNetKeys = []string{ var privNetKeys = []string{
"KxyjQ8eUa4FHt3Gvioyt1Wz29cTUrE4eTqX3yFSk1YFCsPL8uNsY", "KxyjQ8eUa4FHt3Gvioyt1Wz29cTUrE4eTqX3yFSk1YFCsPL8uNsY",
"KzfPUYDC9n2yf4fK5ro4C8KMcdeXtFuEnStycbZgX3GomiUsvX6W", "KzfPUYDC9n2yf4fK5ro4C8KMcdeXtFuEnStycbZgX3GomiUsvX6W",
@ -37,24 +34,21 @@ var privNetKeys = []string{
// newTestChain should be called before newBlock invocation to properly setup // newTestChain should be called before newBlock invocation to properly setup
// global state. // global state.
func newTestChain(t *testing.T) *Blockchain { func newTestChain(t *testing.T) *Blockchain {
var err error unitTestNetCfg, err := config.Load("../../config", config.ModeUnitTestNet)
unitTestNetCfg, err = config.Load("../../config", config.ModeUnitTestNet) require.NoError(t, err)
if err != nil {
t.Fatal(err)
}
chain, err := NewBlockchain(storage.NewMemoryStore(), unitTestNetCfg.ProtocolConfiguration, zaptest.NewLogger(t)) chain, err := NewBlockchain(storage.NewMemoryStore(), unitTestNetCfg.ProtocolConfiguration, zaptest.NewLogger(t))
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
go chain.Run() go chain.Run()
zeroHash, err := chain.GetHeader(chain.GetHeaderHash(0))
require.Nil(t, err)
newBlockPrevHash = zeroHash.Hash()
return chain return chain
} }
func newBlock(index uint32, txs ...*transaction.Transaction) *block.Block { func (bc *Blockchain) newBlock(txs ...*transaction.Transaction) *block.Block {
validators, _ := getValidators(unitTestNetCfg.ProtocolConfiguration) lastBlock := bc.topBlock.Load().(*block.Block)
return newBlock(bc.config, lastBlock.Index+1, lastBlock.Hash(), txs...)
}
func newBlock(cfg config.ProtocolConfiguration, index uint32, prev util.Uint256, txs ...*transaction.Transaction) *block.Block {
validators, _ := getValidators(cfg)
vlen := len(validators) vlen := len(validators)
valScript, _ := smartcontract.CreateMultiSigRedeemScript( valScript, _ := smartcontract.CreateMultiSigRedeemScript(
vlen-(vlen-1)/3, vlen-(vlen-1)/3,
@ -66,7 +60,7 @@ func newBlock(index uint32, txs ...*transaction.Transaction) *block.Block {
b := &block.Block{ b := &block.Block{
Base: block.Base{ Base: block.Base{
Version: 0, Version: 0,
PrevHash: newBlockPrevHash, PrevHash: prev,
Timestamp: uint32(time.Now().UTC().Unix()) + index, Timestamp: uint32(time.Now().UTC().Unix()) + index,
Index: index, Index: index,
ConsensusData: 1111, ConsensusData: 1111,
@ -76,7 +70,6 @@ func newBlock(index uint32, txs ...*transaction.Transaction) *block.Block {
Transactions: txs, Transactions: txs,
} }
_ = b.RebuildMerkleRoot() _ = b.RebuildMerkleRoot()
newBlockPrevHash = b.Hash()
invScript := make([]byte, 0) invScript := make([]byte, 0)
for _, wif := range privNetKeys { for _, wif := range privNetKeys {
@ -96,12 +89,17 @@ func newBlock(index uint32, txs ...*transaction.Transaction) *block.Block {
return b return b
} }
func makeBlocks(n int) []*block.Block { func (bc *Blockchain) genBlocks(n int) ([]*block.Block, error) {
blocks := make([]*block.Block, n) blocks := make([]*block.Block, n)
lastHash := bc.topBlock.Load().(*block.Block).Hash()
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
blocks[i] = newBlock(uint32(i+1), newMinerTX()) blocks[i] = newBlock(bc.config, uint32(i)+1, lastHash, newMinerTX())
if err := bc.AddBlock(blocks[i]); err != nil {
return blocks, err
}
lastHash = blocks[i].Hash()
} }
return blocks return blocks, nil
} }
func newMinerTX() *transaction.Transaction { func newMinerTX() *transaction.Transaction {
@ -113,21 +111,15 @@ func newMinerTX() *transaction.Transaction {
func getDecodedBlock(t *testing.T, i int) *block.Block { func getDecodedBlock(t *testing.T, i int) *block.Block {
data, err := getBlockData(i) data, err := getBlockData(i)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
b, err := hex.DecodeString(data["raw"].(string)) b, err := hex.DecodeString(data["raw"].(string))
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
block := &block.Block{} block := &block.Block{}
r := io.NewBinReaderFromBuf(b) r := io.NewBinReaderFromBuf(b)
block.DecodeBinary(r) block.DecodeBinary(r)
if r.Err != nil { require.NoError(t, r.Err)
t.Fatal(r.Err)
}
return block return block
} }
@ -175,20 +167,13 @@ func newDumbBlock() *block.Block {
func _(t *testing.T) { func _(t *testing.T) {
bc := newTestChain(t) bc := newTestChain(t)
n := 50 n := 50
blocks := makeBlocks(n) _, err := bc.genBlocks(n)
require.NoError(t, err)
for i := 0; i < len(blocks); i++ {
if err := bc.AddBlock(blocks[i]); err != nil {
t.Fatal(err)
}
}
tx1 := newMinerTX() tx1 := newMinerTX()
avm, err := ioutil.ReadFile("../rpc/testdata/test_contract.avm") avm, err := ioutil.ReadFile("../rpc/testdata/test_contract.avm")
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
var props smartcontract.PropertyState var props smartcontract.PropertyState
script := io.NewBufBinWriter() script := io.NewBufBinWriter()
@ -209,10 +194,8 @@ func _(t *testing.T) {
tx2 := transaction.NewInvocationTX(txScript, util.Fixed8FromFloat(100)) tx2 := transaction.NewInvocationTX(txScript, util.Fixed8FromFloat(100))
block := newBlock(uint32(n+1), tx1, tx2) block := bc.newBlock(tx1, tx2)
if err := bc.AddBlock(block); err != nil { require.NoError(t, bc.AddBlock(block))
t.Fatal(err)
}
script = io.NewBufBinWriter() script = io.NewBufBinWriter()
emit.String(script.BinWriter, "testvalue") emit.String(script.BinWriter, "testvalue")
@ -223,13 +206,11 @@ func _(t *testing.T) {
emit.AppCall(script.BinWriter, hash.Hash160(avm), false) emit.AppCall(script.BinWriter, hash.Hash160(avm), false)
tx3 := transaction.NewInvocationTX(script.Bytes(), util.Fixed8FromFloat(100)) tx3 := transaction.NewInvocationTX(script.Bytes(), util.Fixed8FromFloat(100))
b := newBlock(uint32(n+2), newMinerTX(), tx3) b := bc.newBlock(newMinerTX(), tx3)
require.NoError(t, bc.AddBlock(b)) require.NoError(t, bc.AddBlock(b))
outStream, err := os.Create("../rpc/testdata/testblocks.acc") outStream, err := os.Create("../rpc/testdata/testblocks.acc")
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
defer outStream.Close() defer outStream.Close()
writer := io.NewBinWriterFromIO(outStream) writer := io.NewBinWriterFromIO(outStream)
@ -240,15 +221,11 @@ func _(t *testing.T) {
for i := 1; i < int(count); i++ { for i := 1; i < int(count); i++ {
bh := bc.GetHeaderHash(i) bh := bc.GetHeaderHash(i)
b, err := bc.GetBlock(bh) b, err := bc.GetBlock(bh)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
buf := io.NewBufBinWriter() buf := io.NewBufBinWriter()
b.EncodeBinary(buf.BinWriter) b.EncodeBinary(buf.BinWriter)
bytes := buf.Bytes() bytes := buf.Bytes()
writer.WriteBytes(bytes) writer.WriteBytes(bytes)
if writer.Err != nil { require.NoError(t, writer.Err)
t.Fatal(err)
}
} }
} }

View file

@ -9,6 +9,7 @@ import (
"github.com/CityOfZion/neo-go/pkg/io" "github.com/CityOfZion/neo-go/pkg/io"
"github.com/CityOfZion/neo-go/pkg/util" "github.com/CityOfZion/neo-go/pkg/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestRegisterTX(t *testing.T) { func TestRegisterTX(t *testing.T) {
@ -43,9 +44,7 @@ func TestRegisterTX(t *testing.T) {
func TestDecodeRegisterTXFromRawString(t *testing.T) { func TestDecodeRegisterTXFromRawString(t *testing.T) {
rawTX := "400000455b7b226c616e67223a227a682d434e222c226e616d65223a22e5b08fe89a81e882a1227d2c7b226c616e67223a22656e222c226e616d65223a22416e745368617265227d5d0000c16ff28623000000da1745e9b549bd0bfa1a569971c77eba30cd5a4b00000000" rawTX := "400000455b7b226c616e67223a227a682d434e222c226e616d65223a22e5b08fe89a81e882a1227d2c7b226c616e67223a22656e222c226e616d65223a22416e745368617265227d5d0000c16ff28623000000da1745e9b549bd0bfa1a569971c77eba30cd5a4b00000000"
b, err := hex.DecodeString(rawTX) b, err := hex.DecodeString(rawTX)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
tx := &Transaction{} tx := &Transaction{}
r := io.NewBinReaderFromBuf(b) r := io.NewBinReaderFromBuf(b)

View file

@ -6,18 +6,15 @@ import (
"github.com/CityOfZion/neo-go/config" "github.com/CityOfZion/neo-go/config"
"github.com/CityOfZion/neo-go/pkg/encoding/address" "github.com/CityOfZion/neo-go/pkg/encoding/address"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestGenesisBlockMainNet(t *testing.T) { func TestGenesisBlockMainNet(t *testing.T) {
cfg, err := config.Load("../../config", config.ModeMainNet) cfg, err := config.Load("../../config", config.ModeMainNet)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
block, err := createGenesisBlock(cfg.ProtocolConfiguration) block, err := createGenesisBlock(cfg.ProtocolConfiguration)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
expect := "d42561e3d30e15be6400b6df2f328e02d2bf6354c41dce433bc57687c82144bf" expect := "d42561e3d30e15be6400b6df2f328e02d2bf6354c41dce433bc57687c82144bf"
assert.Equal(t, expect, block.Hash().StringLE()) assert.Equal(t, expect, block.Hash().StringLE())
@ -30,19 +27,13 @@ func TestGetConsensusAddressMainNet(t *testing.T) {
) )
cfg, err := config.Load("../../config", config.ModeMainNet) cfg, err := config.Load("../../config", config.ModeMainNet)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
validators, err := getValidators(cfg.ProtocolConfiguration) validators, err := getValidators(cfg.ProtocolConfiguration)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
script, err := getNextConsensusAddress(validators) script, err := getNextConsensusAddress(validators)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
assert.Equal(t, consensusScript, script.String()) assert.Equal(t, consensusScript, script.String())
assert.Equal(t, consensusAddr, address.Uint160ToString(script)) assert.Equal(t, consensusAddr, address.Uint160ToString(script))

View file

@ -17,9 +17,7 @@ func testComputeMerkleTree(t *testing.T, hexHashes []string, result string) {
} }
merkle, err := NewMerkleTree(hashes) merkle, err := NewMerkleTree(hashes)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
assert.Equal(t, result, merkle.Root().StringLE()) assert.Equal(t, result, merkle.Root().StringLE())
assert.Equal(t, true, merkle.root.IsRoot()) assert.Equal(t, true, merkle.root.IsRoot())
assert.Equal(t, false, merkle.root.IsLeaf()) assert.Equal(t, false, merkle.root.IsLeaf())

View file

@ -15,9 +15,7 @@ func TestUint160DecodeEncodeAddress(t *testing.T) {
} }
for _, addr := range addrs { for _, addr := range addrs {
val, err := StringToUint160(addr) val, err := StringToUint160(addr)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
assert.Equal(t, addr, Uint160ToString(val)) assert.Equal(t, addr, Uint160ToString(val))
} }
} }
@ -26,9 +24,7 @@ func TestUint160DecodeKnownAddress(t *testing.T) {
address := "AJeAEsmeD6t279Dx4n2HWdUvUmmXQ4iJvP" address := "AJeAEsmeD6t279Dx4n2HWdUvUmmXQ4iJvP"
val, err := StringToUint160(address) val, err := StringToUint160(address)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
assert.Equal(t, "b28427088a3729b2536d10122960394e8be6721f", val.StringLE()) assert.Equal(t, "b28427088a3729b2536d10122960394e8be6721f", val.StringLE())
assert.Equal(t, "1f72e68b4e39602912106d53b229378a082784b2", val.String()) assert.Equal(t, "1f72e68b4e39602912106d53b229378a082784b2", val.String())

View file

@ -29,9 +29,7 @@ func TestSendVersion(t *testing.T) {
assert.Equal(t, uint32(0), version.StartHeight) assert.Equal(t, uint32(0), version.StartHeight)
} }
if err := p.SendVersion(); err != nil { require.NoError(t, p.SendVersion())
t.Fatal(err)
}
} }
// Server should reply with a verack after receiving a valid version. // Server should reply with a verack after receiving a valid version.
@ -49,9 +47,7 @@ func TestVerackAfterHandleVersionCmd(t *testing.T) {
} }
version := payload.NewVersion(1337, 3000, "/NEO-GO/", 0, true) version := payload.NewVersion(1337, 3000, "/NEO-GO/", 0, true)
if err := s.handleVersionCmd(p, version); err != nil { require.NoError(t, s.handleVersionCmd(p, version))
t.Fatal(err)
}
} }
// Server should not reply with a verack after receiving a // Server should not reply with a verack after receiving a

View file

@ -7,6 +7,7 @@ import (
"github.com/CityOfZion/neo-go/pkg/io" "github.com/CityOfZion/neo-go/pkg/io"
"github.com/CityOfZion/neo-go/pkg/vm/opcode" "github.com/CityOfZion/neo-go/pkg/vm/opcode"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestCreateMultiSigRedeemScript(t *testing.T) { func TestCreateMultiSigRedeemScript(t *testing.T) {
@ -17,18 +18,14 @@ func TestCreateMultiSigRedeemScript(t *testing.T) {
validators := []*keys.PublicKey{val1, val2, val3} validators := []*keys.PublicKey{val1, val2, val3}
out, err := CreateMultiSigRedeemScript(3, validators) out, err := CreateMultiSigRedeemScript(3, validators)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
br := io.NewBinReaderFromBuf(out) br := io.NewBinReaderFromBuf(out)
assert.Equal(t, opcode.PUSH3, opcode.Opcode(br.ReadB())) assert.Equal(t, opcode.PUSH3, opcode.Opcode(br.ReadB()))
for i := 0; i < len(validators); i++ { for i := 0; i < len(validators); i++ {
bb := br.ReadVarBytes() bb := br.ReadVarBytes()
if br.Err != nil { require.NoError(t, br.Err)
t.Fatal(err)
}
assert.Equal(t, validators[i].Bytes(), bb) assert.Equal(t, validators[i].Bytes(), bb)
} }

View file

@ -124,9 +124,7 @@ func getTestingInterop(id uint32) *InteropFuncPrice {
func testFile(t *testing.T, filename string) { func testFile(t *testing.T, filename string) {
data, err := ioutil.ReadFile(filename) data, err := ioutil.ReadFile(filename)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
// FIXME remove when NEO 3.0 https://github.com/nspcc-dev/neo-go/issues/477 // FIXME remove when NEO 3.0 https://github.com/nspcc-dev/neo-go/issues/477
if len(data) > 2 && data[0] == 0xef && data[1] == 0xbb && data[2] == 0xbf { if len(data) > 2 && data[0] == 0xef && data[1] == 0xbb && data[2] == 0xbf {
@ -134,9 +132,7 @@ func testFile(t *testing.T, filename string) {
} }
ut := new(vmUT) ut := new(vmUT)
if err = json.Unmarshal(data, ut); err != nil { require.NoError(t, json.Unmarshal(data, ut))
t.Fatal(err)
}
t.Run(ut.Category+":"+ut.Name, func(t *testing.T) { t.Run(ut.Category+":"+ut.Name, func(t *testing.T) {
for i := range ut.Tests { for i := range ut.Tests {

View file

@ -1694,9 +1694,7 @@ func TestSimpleCall(t *testing.T) {
result := 12 result := 12
prog, err := hex.DecodeString(progStr) prog, err := hex.DecodeString(progStr)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
vm := load(prog) vm := load(prog)
runVM(t, vm) runVM(t, vm)
assert.Equal(t, result, int(vm.estack.Pop().BigInt().Int64())) assert.Equal(t, result, int(vm.estack.Pop().BigInt().Int64()))

View file

@ -134,16 +134,12 @@ func convertPubs(t *testing.T, hexKeys []string) []*keys.PublicKey {
} }
func compareFields(t *testing.T, tk keytestcases.Ktype, acc *Account) { func compareFields(t *testing.T, tk keytestcases.Ktype, acc *Account) {
if want, have := tk.Address, acc.Address; want != have { want, have := tk.Address, acc.Address
t.Fatalf("expected %s got %s", want, have) require.Equalf(t, want, have, "expected %s got %s", want, have)
} want, have = tk.Wif, acc.wif
if want, have := tk.Wif, acc.wif; want != have { require.Equalf(t, want, have, "expected %s got %s", want, have)
t.Fatalf("expected %s got %s", want, have) want, have = tk.PublicKey, hex.EncodeToString(acc.publicKey)
} require.Equalf(t, want, have, "expected %s got %s", want, have)
if want, have := tk.PublicKey, hex.EncodeToString(acc.publicKey); want != have { want, have = tk.PrivateKey, acc.privateKey.String()
t.Fatalf("expected %s got %s", want, have) require.Equalf(t, want, have, "expected %s got %s", want, have)
}
if want, have := tk.PrivateKey, acc.privateKey.String(); want != have {
t.Fatalf("expected %s got %s", want, have)
}
} }