Merge branch 'master' of github.com:harmony-one/harmony into rj_branch

pull/218/head
Rongjian Lan 6 years ago
commit 1cb417f9a9
  1. 107
      api/proto/node/node_test.go
  2. 95
      api/services/explorer/storage_test.go
  3. 27
      api/services/explorer/structs_test.go
  4. 3
      coverage.sh
  5. 47
      internal/utils/bytes.go
  6. 12
      internal/utils/bytes_test.go

@ -0,0 +1,107 @@
package node
import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/params"
"github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/core/types"
hdb "github.com/harmony-one/harmony/internal/db"
// "fmt"
"math/big"
"reflect"
"testing"
)
var (
senderPriKey, _ = crypto.GenerateKey()
receiverPriKey, _ = crypto.GenerateKey()
receiverAddress = crypto.PubkeyToAddress(receiverPriKey.PublicKey)
amountBigInt = big.NewInt(8000000000000000000)
)
func TestSerializeBlockchainSyncMessage(t *testing.T) {
h1 := common.HexToHash("123")
h2 := common.HexToHash("abc")
msg := BlockchainSyncMessage{
BlockHeight: 2,
BlockHashes: []common.Hash{
h1,
h2,
},
}
serializedByte := SerializeBlockchainSyncMessage(&msg)
dMsg, err := DeserializeBlockchainSyncMessage(serializedByte)
if err != nil || !reflect.DeepEqual(msg, *dMsg) {
t.Errorf("Failed to serialize/deserialize blockchain sync message\n")
}
}
func TestConstructTransactionListMessageAccount(t *testing.T) {
tx, _ := types.SignTx(types.NewTransaction(100, receiverAddress, uint32(0), amountBigInt, params.TxGas, nil, nil), types.HomesteadSigner{}, senderPriKey)
transactions := types.Transactions{tx}
buf := ConstructTransactionListMessageAccount(transactions)
if len(buf) == 0 {
t.Error("Failed to contruct transaction list message")
}
}
func TestConstructRequestTransactionsMessage(t *testing.T) {
txIDs := [][]byte{
[]byte{1, 2},
[]byte{3, 4},
}
buf := ConstructRequestTransactionsMessage(txIDs)
if len(buf) == 0 {
t.Error("Failed to contruct request transaction message")
}
}
func TestConstructStopMessage(t *testing.T) {
buf := ConstructStopMessage()
if len(buf) == 0 {
t.Error("Failed to contruct STOP message")
}
}
func TestConstructBlocksSyncMessage(t *testing.T) {
db := hdb.NewMemDatabase()
statedb, _ := state.New(common.Hash{}, state.NewDatabase(db))
root := statedb.IntermediateRoot(false)
head := &types.Header{
Number: new(big.Int).SetUint64(uint64(10000)),
Nonce: types.EncodeNonce(uint64(10000)),
ShardID: types.EncodeShardID(uint32(0)),
Time: new(big.Int).SetUint64(uint64(100000)),
Root: root,
}
head.GasLimit = 10000000000
head.Difficulty = params.GenesisDifficulty
statedb.Commit(false)
statedb.Database().TrieDB().Commit(root, true)
block1 := types.NewBlock(head, nil, nil)
blocks := []*types.Block{
block1,
}
buf := ConstructBlocksSyncMessage(blocks)
if len(buf) == 0 {
t.Error("Failed to contruct block sync message")
}
}

@ -0,0 +1,95 @@
package explorer
import (
"bytes"
"math/big"
"strconv"
"testing"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/rlp"
"github.com/harmony-one/harmony/core/types"
"github.com/stretchr/testify/assert"
)
// Test for GetBlockInfoKey
func TestGetBlockInfoKey(t *testing.T) {
assert.Equal(t, GetBlockInfoKey(3), "bi_3", "error")
}
// Test for GetAddressKey
func TestGetAddressKey(t *testing.T) {
assert.Equal(t, GetAddressKey("abcd"), "ad_abcd", "error")
}
// Test for GetBlockKey
func TestGetBlockKey(t *testing.T) {
assert.Equal(t, GetBlockKey(3), "b_3", "error")
}
// Test for GetTXKey
func TestGetTXKey(t *testing.T) {
assert.Equal(t, GetTXKey("abcd"), "tx_abcd", "error")
}
func TestInit(t *testing.T) {
ins := GetStorageInstance("1.1.1.1", "3333", true)
ins.GetDB().Put([]byte{1}, []byte{2})
value, err := ins.GetDB().Get([]byte{1})
assert.Equal(t, bytes.Compare(value, []byte{2}), 0, "value should be []byte{2}")
assert.Nil(t, err, "error should be nil")
}
func TestDump(t *testing.T) {
tx1 := types.NewTransaction(1, common.BytesToAddress([]byte{0x11}), 0, big.NewInt(111), 1111, big.NewInt(11111), []byte{0x11, 0x11, 0x11})
tx2 := types.NewTransaction(2, common.BytesToAddress([]byte{0x22}), 0, big.NewInt(222), 2222, big.NewInt(22222), []byte{0x22, 0x22, 0x22})
tx3 := types.NewTransaction(3, common.BytesToAddress([]byte{0x33}), 0, big.NewInt(333), 3333, big.NewInt(33333), []byte{0x33, 0x33, 0x33})
txs := []*types.Transaction{tx1, tx2, tx3}
block := types.NewBlock(&types.Header{Number: big.NewInt(314)}, txs, nil)
ins := GetStorageInstance("1.1.1.1", "3333", true)
ins.Dump(block, uint32(1))
db := ins.GetDB()
res, err := db.Get([]byte(BlockHeightKey))
if err == nil {
toInt, err := strconv.Atoi(string(res))
assert.Equal(t, toInt, 1, "error")
assert.Nil(t, err, "error")
} else {
t.Error("Error")
}
data, err := db.Get([]byte(GetBlockKey(1)))
assert.Nil(t, err, "should be nil")
blockData, err := rlp.EncodeToBytes(block)
assert.Nil(t, err, "should be nil")
assert.Equal(t, bytes.Compare(data, blockData), 0, "should be equal")
}
func TestUpdateAddressStorage(t *testing.T) {
tx1 := types.NewTransaction(1, common.BytesToAddress([]byte{0x11}), 0, big.NewInt(111), 1111, big.NewInt(11111), []byte{0x11, 0x11, 0x11})
tx2 := types.NewTransaction(2, common.BytesToAddress([]byte{0x22}), 0, big.NewInt(222), 2222, big.NewInt(22222), []byte{0x22, 0x22, 0x22})
tx3 := types.NewTransaction(3, common.BytesToAddress([]byte{0x33}), 0, big.NewInt(333), 3333, big.NewInt(33333), []byte{0x33, 0x33, 0x33})
txs := []*types.Transaction{tx1, tx2, tx3}
block := types.NewBlock(&types.Header{Number: big.NewInt(314)}, txs, nil)
ins := GetStorageInstance("1.1.1.1", "3333", true)
ins.Dump(block, uint32(1))
db := ins.GetDB()
res, err := db.Get([]byte(BlockHeightKey))
if err == nil {
toInt, err := strconv.Atoi(string(res))
assert.Equal(t, toInt, 1, "error")
assert.Nil(t, err, "error")
} else {
t.Error("Error")
}
data, err := db.Get([]byte(GetBlockKey(1)))
assert.Nil(t, err, "should be nil")
blockData, err := rlp.EncodeToBytes(block)
assert.Nil(t, err, "should be nil")
assert.Equal(t, bytes.Compare(data, blockData), 0, "should be equal")
}

@ -0,0 +1,27 @@
package explorer
import (
"math/big"
"strconv"
"testing"
"github.com/stretchr/testify/assert"
"github.com/ethereum/go-ethereum/common"
"github.com/harmony-one/harmony/core/types"
)
// Test for GetBlockInfoKey
func TestGetTransaction(t *testing.T) {
tx1 := types.NewTransaction(1, common.BytesToAddress([]byte{0x11}), 0, big.NewInt(111), 1111, big.NewInt(11111), []byte{0x11, 0x11, 0x11})
tx2 := types.NewTransaction(2, common.BytesToAddress([]byte{0x22}), 0, big.NewInt(222), 2222, big.NewInt(22222), []byte{0x22, 0x22, 0x22})
tx3 := types.NewTransaction(3, common.BytesToAddress([]byte{0x33}), 0, big.NewInt(333), 3333, big.NewInt(33333), []byte{0x33, 0x33, 0x33})
txs := []*types.Transaction{tx1, tx2, tx3}
block := types.NewBlock(&types.Header{Number: big.NewInt(314)}, txs, nil)
tx := GetTransaction(tx1, block)
assert.Equal(t, tx.ID, tx1.Hash().Hex(), "should be equal tx1.Hash()")
assert.Equal(t, tx.To, tx1.To().Hex(), "should be equal tx1.To()")
assert.Equal(t, tx.Bytes, strconv.Itoa(int(tx1.Size())), "should be equal tx1.Size()")
}

@ -0,0 +1,3 @@
go test ./... -coverprofile=/tmp/coverage.out;
grep -v "harmony-one/harmony/core" /tmp/coverage.out | grep -v "harmony-one/harmony/internal/trie" | grep -v "harmony-one/harmony/internal/db" | grep -v "harmony-one/harmony/log" > /tmp/coverage1.out
go tool cover -func=/tmp/coverage1.out

@ -2,18 +2,6 @@ package utils
import "encoding/hex"
// ToHex returns the hex representation of b, prefixed with '0x'.
// For empty slices, the return value is "0x0".
//
// Deprecated: use hexutil.Encode instead.
func ToHex(b []byte) string {
hex := Bytes2Hex(b)
if len(hex) == 0 {
hex = "0"
}
return "0x" + hex
}
// FromHex returns the bytes represented by the hexadecimal string s.
// s may be prefixed with "0x".
func FromHex(s string) []byte {
@ -39,11 +27,6 @@ func CopyBytes(b []byte) (copiedBytes []byte) {
return
}
// hasHexPrefix validates str begins with '0x' or '0X'.
func hasHexPrefix(str string) bool {
return len(str) >= 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X')
}
// isHexCharacter returns bool of c being a valid hexadecimal.
func isHexCharacter(c byte) bool {
return ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F')
@ -62,31 +45,12 @@ func isHex(str string) bool {
return true
}
// Bytes2Hex returns the hexadecimal encoding of d.
func Bytes2Hex(d []byte) string {
return hex.EncodeToString(d)
}
// Hex2Bytes returns the bytes represented by the hexadecimal string str.
func Hex2Bytes(str string) []byte {
h, _ := hex.DecodeString(str)
return h
}
// Hex2BytesFixed returns bytes of a specified fixed length flen.
func Hex2BytesFixed(str string, flen int) []byte {
h, _ := hex.DecodeString(str)
if len(h) == flen {
return h
}
if len(h) > flen {
return h[len(h)-flen:]
}
hh := make([]byte, flen)
copy(hh[flen-len(h):flen], h[:])
return hh
}
// RightPadBytes zero-pads slice to the right up to length l.
func RightPadBytes(slice []byte, l int) []byte {
if l <= len(slice) {
@ -110,14 +74,3 @@ func LeftPadBytes(slice []byte, l int) []byte {
return padded
}
// Get32BytesFromString parses the string representation of hex into 32 byte array
func Get32BytesFromString(hashString string) ([32]byte, error) {
bytes, err := hex.DecodeString(hashString)
if err != nil {
return [32]byte{}, err
}
bytesArray := [32]byte{}
copy(bytesArray[:], bytes)
return bytesArray, nil
}

@ -87,3 +87,15 @@ func TestNoPrefixShortHexOddLength(t *testing.T) {
t.Errorf("Expected %x got %x", expected, result)
}
}
func TestCopyBytes(t *testing.T) {
expected := []byte{1, 2, 3}
result := CopyBytes(expected)
if !bytes.Equal(expected, result) {
t.Errorf("Expected %x got %x", expected, result)
}
expected[0] = 0
if result[0] == 0 {
t.Errorf("should not be 0")
}
}

Loading…
Cancel
Save