Commit 7957fb75 authored by vipwzw's avatar vipwzw Committed by 33cn

update chain33

parent 90375e0a
......@@ -9,7 +9,6 @@ import (
"math/big"
"sync"
"github.com/33cn/chain33/common"
"github.com/33cn/chain33/common/difficulty"
"github.com/33cn/chain33/types"
)
......@@ -67,12 +66,14 @@ func newBlockNodeByHeader(broadcast bool, header *types.Header, pid string, sequ
return node
}
var sha256Len = 32
func newPreGenBlockNode() *blockNode {
node := &blockNode{
hash: common.Hash{}.Bytes(),
hash: make([]byte, sha256Len),
Difficulty: big.NewInt(-1),
height: -1,
statehash: common.Hash{}.Bytes(),
statehash: make([]byte, sha256Len),
broadcast: false,
pid: "self",
}
......
......@@ -37,7 +37,7 @@ var chainlog = log15.New("module", "chain_test")
func addTx(priv crypto.PrivKey, api client.QueueProtocolAPI) ([]*types.Transaction, string, error) {
txs := util.GenCoinsTxs(priv, 1)
hash := common.Bytes2Hex(txs[0].Hash())
hash := common.ToHex(txs[0].Hash())
reply, err := api.SendTx(txs[0])
if err != nil {
return nil, hash, err
......@@ -50,7 +50,7 @@ func addTx(priv crypto.PrivKey, api client.QueueProtocolAPI) ([]*types.Transacti
func addTxTxHeigt(priv crypto.PrivKey, api client.QueueProtocolAPI, height int64) ([]*types.Transaction, string, error) {
txs := util.GenTxsTxHeigt(priv, 1, height+TxHeightOffset)
hash := common.Bytes2Hex(txs[0].Hash())
hash := common.ToHex(txs[0].Hash())
reply, err := api.SendTx(txs[0])
if err != nil {
return nil, hash, err
......
......@@ -76,7 +76,7 @@ func (b *BlockChain) ProcessBlock(broadcast bool, block *types.BlockDetail, pid
prevHash := block.Block.GetParentHash()
//创世块0需要做一些特殊的判断
if 0 == block.Block.GetHeight() {
if bytes.Equal(prevHash, common.Hash{}.Bytes()) {
if bytes.Equal(prevHash, make([]byte, sha256Len)) {
prevHashExists = true
}
} else {
......
......@@ -107,12 +107,16 @@ func (api *paraChainAPI) IsErr() bool {
func (api *paraChainAPI) QueryTx(param *types.ReqHash) (*types.TransactionDetail, error) {
data, err := api.grpcClient.QueryTransaction(context.Background(), param)
if err != nil {
err = ErrAPIEnv
}
return data, seterr(err, &api.errflag)
}
func (api *paraChainAPI) GetRandNum(param *types.ReqRandHash) ([]byte, error) {
reply, err := api.grpcClient.QueryRandNum(context.Background(), param)
if err != nil {
err = ErrAPIEnv
return nil, seterr(err, &api.errflag)
}
return reply.Hash, nil
......@@ -120,6 +124,9 @@ func (api *paraChainAPI) GetRandNum(param *types.ReqRandHash) ([]byte, error) {
func (api *paraChainAPI) GetBlockByHashes(param *types.ReqHashes) (*types.BlockDetails, error) {
data, err := api.grpcClient.GetBlockByHashes(context.Background(), param)
if err != nil {
err = ErrAPIEnv
}
return data, seterr(err, &api.errflag)
}
......
......@@ -107,7 +107,7 @@ func HashToAddress(version byte, in []byte) *Address {
a.Pubkey = make([]byte, len(in))
copy(a.Pubkey[:], in[:])
a.Version = version
a.Hash160 = common.Rimp160AfterSha256(in)
a.Hash160 = common.Rimp160(in)
return a
}
......@@ -191,7 +191,7 @@ func NewAddrFromString(hs string) (a *Address, e error) {
//Address 地址
type Address struct {
Version byte
Hash160 [20]byte // For a stealth address: it's HASH160
Hash160 []byte // For a stealth address: it's HASH160
Checksum []byte // Unused for a stealth address
Pubkey []byte // Unused for a stealth address
Enc58str string
......
......@@ -31,3 +31,42 @@ func TestGetRandPrintString(t *testing.T) {
t.Error("rand str len")
}
}
func TestMinMax(t *testing.T) {
assert.Equal(t, MinInt32(1, 2), int32(1))
assert.Equal(t, MaxInt32(1, 2), int32(2))
}
func TestHex(t *testing.T) {
var data [Sha256Len]byte
assert.Equal(t, "0000000000000000000000000000000000000000000000000000000000000000", HashHex(data[:]))
assert.Equal(t, 64, len(HashHex(data[:])))
assert.Equal(t, "0x0000000000000000000000000000000000000000000000000000000000000000", ToHex(data[:]))
bdata, err := FromHex("0x0000000000000000000000000000000000000000000000000000000000000000")
assert.Nil(t, err)
assert.Equal(t, bdata, data[:])
bdata, err = FromHex("0X0000000000000000000000000000000000000000000000000000000000000000")
assert.Nil(t, err)
assert.Equal(t, bdata, data[:])
bdata, err = FromHex("0000000000000000000000000000000000000000000000000000000000000000")
assert.Nil(t, err)
assert.Equal(t, bdata, data[:])
data2 := CopyBytes(data[:])
data[0] = 1
assert.Equal(t, data2[0], uint8(0))
assert.Equal(t, false, IsHex("0x"))
assert.Equal(t, false, IsHex("0x0"))
assert.Equal(t, true, IsHex("0x00"))
}
func TestHash(t *testing.T) {
var data [Sha256Len]byte
assert.Equal(t, "0x66687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f2925", ToHex(Sha256(data[:])))
assert.Equal(t, "0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563", ToHex(Sha3(data[:])))
assert.Equal(t, "0x2b32db6c2c0a6235fb1397e8225ea85e0f0e6e8c7b126d0016ccbde0e667151e", ToHex(Sha2Sum(data[:])))
assert.Equal(t, "0xb8bcb07f6344b42ab04250c86a6e8b75d3fdbbc6", ToHex(Rimp160(data[:])))
}
......@@ -242,7 +242,7 @@ func (c *SDBClient) Keys(keyStart, keyEnd string, limit int64) ([]string, error)
resp, err := c.Do("keys", keyStart, keyEnd, limit)
if err != nil {
return nil, newErrorf(err, "Keys %s error", keyStart, keyEnd, limit)
return nil, newErrorf(err, "Keys [%s,%s] %d error", keyStart, keyEnd, limit)
}
if len(resp) > 0 && resp[0] == OK {
return resp[1:], nil
......@@ -261,7 +261,7 @@ func (c *SDBClient) Rkeys(keyStart, keyEnd string, limit int64) ([]string, error
resp, err := c.Do("rkeys", keyStart, keyEnd, limit)
if err != nil {
return nil, newErrorf(err, "Rkeys %s error", keyStart, keyEnd, limit)
return nil, newErrorf(err, "Rkeys [%s,%s] %d error", keyStart, keyEnd, limit)
}
if len(resp) > 0 && resp[0] == OK {
return resp[1:], nil
......
......@@ -5,104 +5,19 @@
package common
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"math/big"
"github.com/33cn/chain33/common/crypto/sha3"
"golang.org/x/crypto/ripemd160"
)
const (
hashLength = 32
)
//Hash hash
type Hash [hashLength]byte
//BytesToHash []byte -> hash
func BytesToHash(b []byte) Hash {
var h Hash
h.SetBytes(b)
return h
}
//StringToHash string -> hash
func StringToHash(s string) Hash { return BytesToHash([]byte(s)) }
//BigToHash *big.Int -> hash
func BigToHash(b *big.Int) Hash { return BytesToHash(b.Bytes()) }
//HexToHash hex -> hash
func HexToHash(s string) Hash {
b, _ := FromHex(s)
return BytesToHash(b)
}
//Str Get the string representation of the underlying hash
func (h Hash) Str() string { return string(h[:]) }
//Bytes Get the []byte representation of the underlying hash
func (h Hash) Bytes() []byte { return h[:] }
//Hex Get the hex representation of the underlying hash
func (h Hash) Hex() string { return hexEncode(h[:]) }
// TerminalString implements log.TerminalStringer, formatting a string for console
// output during logging.
func (h Hash) TerminalString() string {
return fmt.Sprintf("%x…%x", h[:3], h[29:])
}
// String implements the stringer interface and is used also by the logger when
// doing full logging into a file.
func (h Hash) String() string {
return h.Hex()
}
// Format implements fmt.Formatter, forcing the byte slice to be formatted as is,
// without going through the stringer interface used for logging.
func (h Hash) Format(s fmt.State, c rune) {
fmt.Fprintf(s, "%"+string(c), h[:])
}
//SetBytes Sets the hash to the value of b. If b is larger than len(h), 'b' will be cropped (from the left).
func (h *Hash) SetBytes(b []byte) {
if len(b) > len(h) {
b = b[len(b)-hashLength:]
}
copy(h[hashLength-len(b):], b)
}
//SetString Set string `s` to h. If s is larger than len(h) s will be cropped (from left) to fit.
func (h *Hash) SetString(s string) { h.SetBytes([]byte(s)) }
//Set Sets h to other
func (h *Hash) Set(other Hash) {
for i, v := range other {
h[i] = v
}
}
//EmptyHash hash是否为空
func EmptyHash(h Hash) bool {
return h == Hash{}
}
func hexEncode(b []byte) string {
enc := make([]byte, len(b)*2+2)
copy(enc, "0x")
hex.Encode(enc[2:], b)
return string(enc)
}
//Sha256Len sha256 bytes len
const Sha256Len = 32
//ToHex []byte -> hex
func ToHex(b []byte) string {
hex := Bytes2Hex(b)
hex := hex.EncodeToString(b)
// Prefer output of "0x0" instead of "0x"
if len(hex) == 0 {
return ""
......@@ -112,7 +27,7 @@ func ToHex(b []byte) string {
//HashHex []byte -> hex
func HashHex(d []byte) string {
var buf [64]byte
var buf [Sha256Len * 2]byte
hex.Encode(buf[:], d)
return string(buf[:])
}
......@@ -126,7 +41,7 @@ func FromHex(s string) ([]byte, error) {
if len(s)%2 == 1 {
s = "0" + s
}
return Hex2Bytes(s)
return hex.DecodeString(s)
}
return []byte{}, nil
}
......@@ -142,40 +57,24 @@ func CopyBytes(b []byte) (copiedBytes []byte) {
return
}
//HasHexPrefix 是否包含0x前缀
func HasHexPrefix(str string) bool {
l := len(str)
return l >= 2 && str[0:2] == "0x"
}
//IsHex 是否是hex字符串
func IsHex(str string) bool {
l := len(str)
return l >= 4 && l%2 == 0 && str[0:2] == "0x"
}
//Bytes2Hex []byte -> hex
func Bytes2Hex(d []byte) string {
return hex.EncodeToString(d)
}
//Sha256 加密
func Sha256(b []byte) []byte {
data := sha256.Sum256(b)
return data[:]
}
//ShaKeccak256 加密
func ShaKeccak256(b []byte) []byte {
//Sha3 加密
func Sha3(b []byte) []byte {
data := sha3.KeccakSum256(b)
return data[:]
}
//Hex2Bytes hex -> []byte
func Hex2Bytes(str string) ([]byte, error) {
return hex.DecodeString(str)
}
func sha2Hash(b []byte, out []byte) {
s := sha256.New()
s.Write(b[:])
......@@ -187,9 +86,10 @@ func sha2Hash(b []byte, out []byte) {
// Sha2Sum Returns hash: SHA256( SHA256( data ) )
// Where possible, using ShaHash() should be a bit faster
func Sha2Sum(b []byte) (out [32]byte) {
func Sha2Sum(b []byte) []byte {
out := make([]byte, 32)
sha2Hash(b, out[:])
return
return out[:]
}
func rimpHash(in []byte, out []byte) {
......@@ -200,18 +100,10 @@ func rimpHash(in []byte, out []byte) {
copy(out, rim.Sum(nil))
}
// Rimp160AfterSha256 Returns hash: RIMP160( SHA256( data ) )
// Rimp160 Returns hash: RIMP160( SHA256( data ) )
// Where possible, using RimpHash() should be a bit faster
func Rimp160AfterSha256(b []byte) (out [20]byte) {
func Rimp160(b []byte) []byte {
out := make([]byte, 20)
rimpHash(b, out[:])
return
}
//RandKey 随机key
func RandKey() (ret [32]byte) {
_, err := io.ReadFull(rand.Reader, ret[:])
if err != nil {
panic(err)
}
return
return out[:]
}
......@@ -137,17 +137,18 @@ func GetNtpTime(host string) (time.Time, error) {
type durationSlice []time.Duration
func (s durationSlice) Len() int { return len(s) }
func (s durationSlice) Less(i, j int) bool { return s[i] < s[j] }
func (s durationSlice) Less(i, j int) bool { return abs(s[i]) < abs(s[j]) }
func (s durationSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
//GetRealTime 获取实际时间
func GetRealTime(hosts []string) time.Time {
q := len(hosts)/2 + 1
//q := 5
ch := make(chan time.Duration, len(hosts))
for i := 0; i < len(hosts); i++ {
go func(host string) {
ntptime, _ := getTimeRetry(host, 10)
if ntptime.IsZero() {
ntptime, err := getTimeRetry(host, 10)
if ntptime.IsZero() || err != nil {
ch <- time.Duration(math.MaxInt64)
} else {
dt := time.Until(ntptime)
......@@ -163,7 +164,6 @@ func GetRealTime(hosts []string) time.Time {
continue
}
dtlist = append(dtlist, t)
fmt.Println(dtlist)
if len(dtlist) >= q {
calclist := make([]time.Duration, len(dtlist))
copy(calclist, dtlist)
......@@ -203,20 +203,16 @@ func maxSubList(list []time.Duration) (sub []time.Duration) {
var start int
var end int
if abs(nextheight-list[i]) > time.Millisecond*100 {
end = i + 1
end = i
if len(sub) < (end - start) {
sub = list[start:end]
}
start = i + 1
end = i + 1
start = i
end = i
} else {
end = i + 1
}
}
//只有一个节点,那么取差最小的节点
if len(sub) <= 1 {
return list[0:1]
}
return sub
}
......
......@@ -4,21 +4,33 @@
package common
//var NtpHosts = []string{
// "time.windows.com:123",
// "tw.pool.ntp.org:123",
// "pool.ntp.org:123",
// "cn.pool.ntp.org:123",
// "time.apple.com:123",
//}
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
var NtpHosts = []string{
"time.windows.com:123",
"ntp.ubuntu.com:123",
"pool.ntp.org:123",
"cn.pool.ntp.org:123",
"time.apple.com:123",
}
// 在单元测试中对网络时间和本地时间进行单元测试的功能是没有意义的
// 只有在实际运行过程中,通过网络时间来纠正本地时间
// 本测试用例有概率导致误差大于1秒从而让测试用例运行失败
//func TestGetRealTime(t *testing.T) {
// hosts := NtpHosts
// nettime := GetRealTimeRetry(hosts, 10)
// local := time.Now()
// t.Log(nettime.Sub(local))
// assert.Equal(t, int(local.Sub(nettime)/time.Second), 0)
//}
func TestGetRealTime(t *testing.T) {
hosts := NtpHosts
nettime := GetRealTimeRetry(hosts, 10)
//get nettime error, ignore
if nettime.IsZero() {
return
}
//nettime 获取和本地时间应该
local := time.Now()
t.Log(nettime.Sub(local))
assert.Equal(t, int(local.Sub(nettime)/time.Second), 0)
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package common
import (
"crypto/sha256"
"encoding/hex"
)
//Revers String returns the Hash as the hexadecimal string of the byte-reversed hash.
func (h Hash) Revers() Hash {
for i := 0; i < hashLength/2; i++ {
h[i], h[hashLength-1-i] = h[hashLength-1-i], h[i]
}
return h
}
//ReversString String returns the Hash as the hexadecimal string of the byte-reversed hash.
func (h Hash) ReversString() string {
for i := 0; i < hashLength/2; i++ {
h[i], h[hashLength-1-i] = h[hashLength-1-i], h[i]
}
return hex.EncodeToString(h[:])
}
// HashB calculates hash(b) and returns the resulting bytes.
func HashB(b []byte) []byte {
hash := sha256.Sum256(b)
return hash[:]
}
// HashH calculates hash(b) and returns the resulting bytes as a Hash.
func HashH(b []byte) Hash {
return Hash(sha256.Sum256(b))
}
// DoubleHashB calculates hash(hash(b)) and returns the resulting bytes.
func DoubleHashB(b []byte) []byte {
first := sha256.Sum256(b)
second := sha256.Sum256(first[:])
return second[:]
}
// DoubleHashH calculates hash(hash(b)) and returns the resulting bytes as a
// Hash.
func DoubleHashH(b []byte) Hash {
first := sha256.Sum256(b)
return Hash(sha256.Sum256(first[:]))
}
......@@ -1007,15 +1007,12 @@ func (c *Chain33) GetTimeStatus(in *types.ReqNil, result *interface{}) error {
if err != nil {
return err
}
timeStatus := &rpctypes.TimeStatus{
NtpTime: reply.NtpTime,
LocalTime: reply.LocalTime,
Diff: reply.Diff,
}
*result = timeStatus
return nil
}
......
......@@ -86,8 +86,8 @@ func parseListAccountRes(arg interface{}) (interface{}, error) {
res := arg.(*rpctypes.WalletAccounts)
var result commandtypes.AccountsResult
for _, r := range res.Wallets {
balanceResult := strconv.FormatFloat(float64(r.Acc.Balance)/float64(types.Coin), 'f', 4, 64)
frozenResult := strconv.FormatFloat(float64(r.Acc.Frozen)/float64(types.Coin), 'f', 4, 64)
balanceResult := strconv.FormatFloat(float64(r.Acc.Balance/types.Int1E4)/types.Float1E4, 'f', 4, 64)
frozenResult := strconv.FormatFloat(float64(r.Acc.Frozen/types.Int1E4)/types.Float1E4, 'f', 4, 64)
accResult := &commandtypes.AccountResult{
Currency: r.Acc.Currency,
Addr: r.Acc.Addr,
......@@ -188,8 +188,8 @@ func balance(cmd *cobra.Command, args []string) {
func parseGetBalanceRes(arg interface{}) (interface{}, error) {
res := *arg.(*[]*rpctypes.Account)
balanceResult := strconv.FormatFloat(float64(res[0].Balance)/float64(types.Coin), 'f', 4, 64)
frozenResult := strconv.FormatFloat(float64(res[0].Frozen)/float64(types.Coin), 'f', 4, 64)
balanceResult := strconv.FormatFloat(float64(res[0].Balance/types.Int1E4)/types.Float1E4, 'f', 4, 64)
frozenResult := strconv.FormatFloat(float64(res[0].Frozen/types.Int1E4)/types.Float1E4, 'f', 4, 64)
result := &commandtypes.AccountResult{
Addr: res[0].Addr,
Currency: res[0].Currency,
......@@ -204,8 +204,8 @@ func parseGetAllBalanceRes(arg interface{}) (interface{}, error) {
accs := res.ExecAccount
result := commandtypes.AllExecBalance{Addr: res.Addr}
for _, acc := range accs {
balanceResult := strconv.FormatFloat(float64(acc.Account.Balance)/float64(types.Coin), 'f', 4, 64)
frozenResult := strconv.FormatFloat(float64(acc.Account.Frozen)/float64(types.Coin), 'f', 4, 64)
balanceResult := strconv.FormatFloat(float64(acc.Account.Balance/types.Int1E4)/types.Float1E4, 'f', 4, 64)
frozenResult := strconv.FormatFloat(float64(acc.Account.Frozen/types.Int1E4)/types.Float1E4, 'f', 4, 64)
ar := &commandtypes.AccountResult{
Currency: acc.Account.Currency,
Balance: balanceResult,
......
......@@ -745,7 +745,7 @@ func execBalance(cmd *cobra.Command, args []string) {
return
}
data, err := common.Hex2Bytes(str)
data, err := common.FromHex(str)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
......
......@@ -51,7 +51,7 @@ func LoadDriver(name string, height int64) (driver Driver, err error) {
name = string(types.GetRealExecName([]byte(name)))
c, ok := registedExecDriver[name]
if !ok {
elog.Error("LoadDriver", "driver", name)
elog.Debug("LoadDriver", "driver", name)
return nil, types.ErrUnRegistedDriver
}
if height >= c.height || height == -1 {
......
......@@ -7,7 +7,6 @@ package mavl
import (
"bytes"
"github.com/33cn/chain33/common"
"github.com/33cn/chain33/types"
"github.com/golang/protobuf/proto"
)
......@@ -21,6 +20,8 @@ type Proof struct {
RootHash []byte
}
var sha256Len = 32
// Verify key:value 的proof确认
func (proof *Proof) Verify(key []byte, value []byte, root []byte) bool {
if !bytes.Equal(proof.RootHash, root) {
......@@ -29,7 +30,7 @@ func (proof *Proof) Verify(key []byte, value []byte, root []byte) bool {
leafNode := types.LeafNode{Key: key, Value: value, Height: 0, Size: 1}
leafHash := leafNode.Hash()
hashLen := len(common.Hash{})
hashLen := sha256Len
if len(proof.LeafHash) > hashLen {
proof.LeafHash = proof.LeafHash[len(proof.LeafHash)-hashLen:]
}
......
......@@ -81,7 +81,7 @@ func genLeafCountKey(key, hash []byte, height int64, hashLen int) (hashkey []byt
}
func getKeyHeightFromLeafCountKey(hashkey []byte) (key []byte, height int, hash []byte, err error) {
if len(hashkey) < len(leafKeyCountPrefix)+blockHeightStrLen+len(common.Hash{})+hashLenStr {
if len(hashkey) < len(leafKeyCountPrefix)+blockHeightStrLen+sha256Len+hashLenStr {
return nil, 0, nil, types.ErrSize
}
if !bytes.Contains(hashkey, []byte(leafKeyCountPrefix)) {
......@@ -111,7 +111,7 @@ func genOldLeafCountKey(key, hash []byte, height int64, hashLen int) (hashkey []
}
func getKeyHeightFromOldLeafCountKey(hashkey []byte) (key []byte, height int, hash []byte, err error) {
if len(hashkey) < len(oldLeafKeyCountPrefix)+blockHeightStrLen+len(common.Hash{})+hashLenStr {
if len(hashkey) < len(oldLeafKeyCountPrefix)+blockHeightStrLen+sha256Len+hashLenStr {
return nil, 0, nil, types.ErrSize
}
if !bytes.Contains(hashkey, []byte(oldLeafKeyCountPrefix)) {
......@@ -460,7 +460,7 @@ func printSameLeafKeyDB(db dbm.DB, key string, isold bool) {
if len(hash) > 32 {
pri = string(hash[:16])
}
treelog.Info("leaf node", "height", height, "pri", pri, "hash", common.Bytes2Hex(hash), "key", string(key))
treelog.Info("leaf node", "height", height, "pri", pri, "hash", common.ToHex(hash), "key", string(key))
}
}
}
......@@ -479,7 +479,7 @@ func PrintLeafNodeParent(db dbm.DB, key, hash []byte, height int64) {
if len(hash) > 32 {
pri = string(hash[:16])
}
treelog.Info("hash node", "hash pri", pri, "hash", common.Bytes2Hex(hash))
treelog.Info("hash node", "hash pri", pri, "hash", common.ToHex(hash))
}
}
isHave = true
......@@ -497,7 +497,7 @@ func PrintLeafNodeParent(db dbm.DB, key, hash []byte, height int64) {
if len(hash) > 32 {
pri = string(hash[:16])
}
treelog.Info("hash node", "hash pri", pri, "hash", common.Bytes2Hex(hash))
treelog.Info("hash node", "hash pri", pri, "hash", common.ToHex(hash))
}
}
isHave = true
......@@ -521,7 +521,7 @@ func PrintNodeDb(db dbm.DB, hash []byte) {
if len(node.hash) > 32 {
pri = string(node.hash[:16])
}
treelog.Info("hash node", "hash pri", pri, "hash", common.Bytes2Hex(node.hash), "height", node.height)
treelog.Info("hash node", "hash pri", pri, "hash", common.ToHex(node.hash), "height", node.height)
node.printNodeInfo(nDb)
}
......@@ -531,7 +531,7 @@ func (node *Node) printNodeInfo(db *nodeDB) {
if len(node.hash) > 32 {
pri = string(node.hash[:16])
}
treelog.Info("leaf node", "hash pri", pri, "hash", common.Bytes2Hex(node.hash), "key", string(node.key))
treelog.Info("leaf node", "hash pri", pri, "hash", common.ToHex(node.hash), "key", string(node.key))
return
}
if node.leftHash != nil {
......@@ -543,7 +543,7 @@ func (node *Node) printNodeInfo(db *nodeDB) {
if len(left.hash) > 32 {
pri = string(left.hash[:16])
}
treelog.Debug("hash node", "hash pri", pri, "hash", common.Bytes2Hex(left.hash), "height", left.height)
treelog.Debug("hash node", "hash pri", pri, "hash", common.ToHex(left.hash), "height", left.height)
left.printNodeInfo(db)
}
......@@ -556,7 +556,7 @@ func (node *Node) printNodeInfo(db *nodeDB) {
if len(right.hash) > 32 {
pri = string(right.hash[:16])
}
treelog.Debug("hash node", "hash pri", pri, "hash", common.Bytes2Hex(right.hash), "height", right.height)
treelog.Debug("hash node", "hash pri", pri, "hash", common.ToHex(right.hash), "height", right.height)
right.printNodeInfo(db)
}
}
......
......@@ -651,12 +651,12 @@ func genRootHashHeight(blockHeight int64, hash []byte) (key []byte) {
}
func getRootHash(hashKey []byte) (hash []byte, err error) {
if len(hashKey) < len(rootHashHeightPrefix)+blockHeightStrLen+len(common.Hash{}) {
if len(hashKey) < len(rootHashHeightPrefix)+blockHeightStrLen+sha256Len {
return nil, types.ErrSize
}
if !bytes.Contains(hashKey, []byte(rootHashHeightPrefix)) {
return nil, types.ErrSize
}
hash = hashKey[len(hashKey)-len(common.Hash{}):]
hash = hashKey[len(hashKey)-sha256Len:]
return hash, nil
}
......@@ -10,12 +10,10 @@ import (
"fmt"
"io/ioutil"
"math/rand"
"sort"
"testing"
"os"
"sort"
"sync"
"testing"
. "github.com/33cn/chain33/common"
"github.com/33cn/chain33/common/db"
......@@ -264,7 +262,7 @@ func TestHashSame2(t *testing.T) {
for i := 0; i < 5; i++ {
prevHash, err = saveBlock(db1, int64(i), prevHash, 1000, false)
assert.Nil(t, err)
str := Bytes2Hex(prevHash)
str := ToHex(prevHash)
fmt.Println("unable", str)
strs1[str] = true
}
......@@ -278,7 +276,7 @@ func TestHashSame2(t *testing.T) {
for i := 0; i < 5; i++ {
prevHash, err = saveBlock(db2, int64(i), prevHash, 1000, false)
assert.Nil(t, err)
str := Bytes2Hex(prevHash)
str := ToHex(prevHash)
fmt.Println("enable", str)
if ok := strs1[str]; !ok {
t.Error("enable Prefix have a different hash")
......
......@@ -52,6 +52,8 @@ const (
PrivacyMaturityDegree = 12
TxGroupMaxCount = 20
MinerAction = "miner"
Int1E4 int64 = 10000
Float1E4 float64 = 10000.0
)
//全局账户私钥/公钥
......
......@@ -223,11 +223,13 @@ func (leafnode *LeafNode) Hash() []byte {
return common.Sha256(data)
}
var sha256Len = 32
//Hash 计算中间节点的hash
func (innernode *InnerNode) Hash() []byte {
rightHash := innernode.RightHash
leftHash := innernode.LeftHash
hashLen := len(common.Hash{})
hashLen := sha256Len
if len(innernode.RightHash) > hashLen {
innernode.RightHash = innernode.RightHash[len(innernode.RightHash)-hashLen:]
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment