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

update chain33

parent 90375e0a
...@@ -9,7 +9,6 @@ import ( ...@@ -9,7 +9,6 @@ import (
"math/big" "math/big"
"sync" "sync"
"github.com/33cn/chain33/common"
"github.com/33cn/chain33/common/difficulty" "github.com/33cn/chain33/common/difficulty"
"github.com/33cn/chain33/types" "github.com/33cn/chain33/types"
) )
...@@ -67,12 +66,14 @@ func newBlockNodeByHeader(broadcast bool, header *types.Header, pid string, sequ ...@@ -67,12 +66,14 @@ func newBlockNodeByHeader(broadcast bool, header *types.Header, pid string, sequ
return node return node
} }
var sha256Len = 32
func newPreGenBlockNode() *blockNode { func newPreGenBlockNode() *blockNode {
node := &blockNode{ node := &blockNode{
hash: common.Hash{}.Bytes(), hash: make([]byte, sha256Len),
Difficulty: big.NewInt(-1), Difficulty: big.NewInt(-1),
height: -1, height: -1,
statehash: common.Hash{}.Bytes(), statehash: make([]byte, sha256Len),
broadcast: false, broadcast: false,
pid: "self", pid: "self",
} }
......
...@@ -37,7 +37,7 @@ var chainlog = log15.New("module", "chain_test") ...@@ -37,7 +37,7 @@ var chainlog = log15.New("module", "chain_test")
func addTx(priv crypto.PrivKey, api client.QueueProtocolAPI) ([]*types.Transaction, string, error) { func addTx(priv crypto.PrivKey, api client.QueueProtocolAPI) ([]*types.Transaction, string, error) {
txs := util.GenCoinsTxs(priv, 1) txs := util.GenCoinsTxs(priv, 1)
hash := common.Bytes2Hex(txs[0].Hash()) hash := common.ToHex(txs[0].Hash())
reply, err := api.SendTx(txs[0]) reply, err := api.SendTx(txs[0])
if err != nil { if err != nil {
return nil, hash, err return nil, hash, err
...@@ -50,7 +50,7 @@ func addTx(priv crypto.PrivKey, api client.QueueProtocolAPI) ([]*types.Transacti ...@@ -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) { func addTxTxHeigt(priv crypto.PrivKey, api client.QueueProtocolAPI, height int64) ([]*types.Transaction, string, error) {
txs := util.GenTxsTxHeigt(priv, 1, height+TxHeightOffset) 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]) reply, err := api.SendTx(txs[0])
if err != nil { if err != nil {
return nil, hash, err return nil, hash, err
......
...@@ -76,7 +76,7 @@ func (b *BlockChain) ProcessBlock(broadcast bool, block *types.BlockDetail, pid ...@@ -76,7 +76,7 @@ func (b *BlockChain) ProcessBlock(broadcast bool, block *types.BlockDetail, pid
prevHash := block.Block.GetParentHash() prevHash := block.Block.GetParentHash()
//创世块0需要做一些特殊的判断 //创世块0需要做一些特殊的判断
if 0 == block.Block.GetHeight() { if 0 == block.Block.GetHeight() {
if bytes.Equal(prevHash, common.Hash{}.Bytes()) { if bytes.Equal(prevHash, make([]byte, sha256Len)) {
prevHashExists = true prevHashExists = true
} }
} else { } else {
......
...@@ -107,12 +107,16 @@ func (api *paraChainAPI) IsErr() bool { ...@@ -107,12 +107,16 @@ func (api *paraChainAPI) IsErr() bool {
func (api *paraChainAPI) QueryTx(param *types.ReqHash) (*types.TransactionDetail, error) { func (api *paraChainAPI) QueryTx(param *types.ReqHash) (*types.TransactionDetail, error) {
data, err := api.grpcClient.QueryTransaction(context.Background(), param) data, err := api.grpcClient.QueryTransaction(context.Background(), param)
if err != nil {
err = ErrAPIEnv
}
return data, seterr(err, &api.errflag) return data, seterr(err, &api.errflag)
} }
func (api *paraChainAPI) GetRandNum(param *types.ReqRandHash) ([]byte, error) { func (api *paraChainAPI) GetRandNum(param *types.ReqRandHash) ([]byte, error) {
reply, err := api.grpcClient.QueryRandNum(context.Background(), param) reply, err := api.grpcClient.QueryRandNum(context.Background(), param)
if err != nil { if err != nil {
err = ErrAPIEnv
return nil, seterr(err, &api.errflag) return nil, seterr(err, &api.errflag)
} }
return reply.Hash, nil return reply.Hash, nil
...@@ -120,6 +124,9 @@ func (api *paraChainAPI) GetRandNum(param *types.ReqRandHash) ([]byte, error) { ...@@ -120,6 +124,9 @@ func (api *paraChainAPI) GetRandNum(param *types.ReqRandHash) ([]byte, error) {
func (api *paraChainAPI) GetBlockByHashes(param *types.ReqHashes) (*types.BlockDetails, error) { func (api *paraChainAPI) GetBlockByHashes(param *types.ReqHashes) (*types.BlockDetails, error) {
data, err := api.grpcClient.GetBlockByHashes(context.Background(), param) data, err := api.grpcClient.GetBlockByHashes(context.Background(), param)
if err != nil {
err = ErrAPIEnv
}
return data, seterr(err, &api.errflag) return data, seterr(err, &api.errflag)
} }
......
...@@ -107,7 +107,7 @@ func HashToAddress(version byte, in []byte) *Address { ...@@ -107,7 +107,7 @@ func HashToAddress(version byte, in []byte) *Address {
a.Pubkey = make([]byte, len(in)) a.Pubkey = make([]byte, len(in))
copy(a.Pubkey[:], in[:]) copy(a.Pubkey[:], in[:])
a.Version = version a.Version = version
a.Hash160 = common.Rimp160AfterSha256(in) a.Hash160 = common.Rimp160(in)
return a return a
} }
...@@ -191,7 +191,7 @@ func NewAddrFromString(hs string) (a *Address, e error) { ...@@ -191,7 +191,7 @@ func NewAddrFromString(hs string) (a *Address, e error) {
//Address 地址 //Address 地址
type Address struct { type Address struct {
Version byte 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 Checksum []byte // Unused for a stealth address
Pubkey []byte // Unused for a stealth address Pubkey []byte // Unused for a stealth address
Enc58str string Enc58str string
......
...@@ -31,3 +31,42 @@ func TestGetRandPrintString(t *testing.T) { ...@@ -31,3 +31,42 @@ func TestGetRandPrintString(t *testing.T) {
t.Error("rand str len") 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) ...@@ -242,7 +242,7 @@ func (c *SDBClient) Keys(keyStart, keyEnd string, limit int64) ([]string, error)
resp, err := c.Do("keys", keyStart, keyEnd, limit) resp, err := c.Do("keys", keyStart, keyEnd, limit)
if err != nil { 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 { if len(resp) > 0 && resp[0] == OK {
return resp[1:], nil return resp[1:], nil
...@@ -261,7 +261,7 @@ func (c *SDBClient) Rkeys(keyStart, keyEnd string, limit int64) ([]string, error ...@@ -261,7 +261,7 @@ func (c *SDBClient) Rkeys(keyStart, keyEnd string, limit int64) ([]string, error
resp, err := c.Do("rkeys", keyStart, keyEnd, limit) resp, err := c.Do("rkeys", keyStart, keyEnd, limit)
if err != nil { 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 { if len(resp) > 0 && resp[0] == OK {
return resp[1:], nil return resp[1:], nil
......
...@@ -5,104 +5,19 @@ ...@@ -5,104 +5,19 @@
package common package common
import ( import (
"crypto/rand"
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
"fmt"
"io"
"math/big"
"github.com/33cn/chain33/common/crypto/sha3" "github.com/33cn/chain33/common/crypto/sha3"
"golang.org/x/crypto/ripemd160" "golang.org/x/crypto/ripemd160"
) )
const ( //Sha256Len sha256 bytes len
hashLength = 32 const Sha256Len = 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)
}
//ToHex []byte -> hex //ToHex []byte -> hex
func ToHex(b []byte) string { func ToHex(b []byte) string {
hex := Bytes2Hex(b) hex := hex.EncodeToString(b)
// Prefer output of "0x0" instead of "0x" // Prefer output of "0x0" instead of "0x"
if len(hex) == 0 { if len(hex) == 0 {
return "" return ""
...@@ -112,7 +27,7 @@ func ToHex(b []byte) string { ...@@ -112,7 +27,7 @@ func ToHex(b []byte) string {
//HashHex []byte -> hex //HashHex []byte -> hex
func HashHex(d []byte) string { func HashHex(d []byte) string {
var buf [64]byte var buf [Sha256Len * 2]byte
hex.Encode(buf[:], d) hex.Encode(buf[:], d)
return string(buf[:]) return string(buf[:])
} }
...@@ -126,7 +41,7 @@ func FromHex(s string) ([]byte, error) { ...@@ -126,7 +41,7 @@ func FromHex(s string) ([]byte, error) {
if len(s)%2 == 1 { if len(s)%2 == 1 {
s = "0" + s s = "0" + s
} }
return Hex2Bytes(s) return hex.DecodeString(s)
} }
return []byte{}, nil return []byte{}, nil
} }
...@@ -142,40 +57,24 @@ func CopyBytes(b []byte) (copiedBytes []byte) { ...@@ -142,40 +57,24 @@ func CopyBytes(b []byte) (copiedBytes []byte) {
return return
} }
//HasHexPrefix 是否包含0x前缀
func HasHexPrefix(str string) bool {
l := len(str)
return l >= 2 && str[0:2] == "0x"
}
//IsHex 是否是hex字符串 //IsHex 是否是hex字符串
func IsHex(str string) bool { func IsHex(str string) bool {
l := len(str) l := len(str)
return l >= 4 && l%2 == 0 && str[0:2] == "0x" return l >= 4 && l%2 == 0 && str[0:2] == "0x"
} }
//Bytes2Hex []byte -> hex
func Bytes2Hex(d []byte) string {
return hex.EncodeToString(d)
}
//Sha256 加密 //Sha256 加密
func Sha256(b []byte) []byte { func Sha256(b []byte) []byte {
data := sha256.Sum256(b) data := sha256.Sum256(b)
return data[:] return data[:]
} }
//ShaKeccak256 加密 //Sha3 加密
func ShaKeccak256(b []byte) []byte { func Sha3(b []byte) []byte {
data := sha3.KeccakSum256(b) data := sha3.KeccakSum256(b)
return data[:] return data[:]
} }
//Hex2Bytes hex -> []byte
func Hex2Bytes(str string) ([]byte, error) {
return hex.DecodeString(str)
}
func sha2Hash(b []byte, out []byte) { func sha2Hash(b []byte, out []byte) {
s := sha256.New() s := sha256.New()
s.Write(b[:]) s.Write(b[:])
...@@ -187,9 +86,10 @@ func sha2Hash(b []byte, out []byte) { ...@@ -187,9 +86,10 @@ func sha2Hash(b []byte, out []byte) {
// Sha2Sum Returns hash: SHA256( SHA256( data ) ) // Sha2Sum Returns hash: SHA256( SHA256( data ) )
// Where possible, using ShaHash() should be a bit faster // 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[:]) sha2Hash(b, out[:])
return return out[:]
} }
func rimpHash(in []byte, out []byte) { func rimpHash(in []byte, out []byte) {
...@@ -200,18 +100,10 @@ func rimpHash(in []byte, out []byte) { ...@@ -200,18 +100,10 @@ func rimpHash(in []byte, out []byte) {
copy(out, rim.Sum(nil)) 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 // 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[:]) rimpHash(b, out[:])
return return out[:]
}
//RandKey 随机key
func RandKey() (ret [32]byte) {
_, err := io.ReadFull(rand.Reader, ret[:])
if err != nil {
panic(err)
}
return
} }
...@@ -137,17 +137,18 @@ func GetNtpTime(host string) (time.Time, error) { ...@@ -137,17 +137,18 @@ func GetNtpTime(host string) (time.Time, error) {
type durationSlice []time.Duration type durationSlice []time.Duration
func (s durationSlice) Len() int { return len(s) } 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] } func (s durationSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
//GetRealTime 获取实际时间 //GetRealTime 获取实际时间
func GetRealTime(hosts []string) time.Time { func GetRealTime(hosts []string) time.Time {
q := len(hosts)/2 + 1 q := len(hosts)/2 + 1
//q := 5
ch := make(chan time.Duration, len(hosts)) ch := make(chan time.Duration, len(hosts))
for i := 0; i < len(hosts); i++ { for i := 0; i < len(hosts); i++ {
go func(host string) { go func(host string) {
ntptime, _ := getTimeRetry(host, 10) ntptime, err := getTimeRetry(host, 10)
if ntptime.IsZero() { if ntptime.IsZero() || err != nil {
ch <- time.Duration(math.MaxInt64) ch <- time.Duration(math.MaxInt64)
} else { } else {
dt := time.Until(ntptime) dt := time.Until(ntptime)
...@@ -163,7 +164,6 @@ func GetRealTime(hosts []string) time.Time { ...@@ -163,7 +164,6 @@ func GetRealTime(hosts []string) time.Time {
continue continue
} }
dtlist = append(dtlist, t) dtlist = append(dtlist, t)
fmt.Println(dtlist)
if len(dtlist) >= q { if len(dtlist) >= q {
calclist := make([]time.Duration, len(dtlist)) calclist := make([]time.Duration, len(dtlist))
copy(calclist, dtlist) copy(calclist, dtlist)
...@@ -203,20 +203,16 @@ func maxSubList(list []time.Duration) (sub []time.Duration) { ...@@ -203,20 +203,16 @@ func maxSubList(list []time.Duration) (sub []time.Duration) {
var start int var start int
var end int var end int
if abs(nextheight-list[i]) > time.Millisecond*100 { if abs(nextheight-list[i]) > time.Millisecond*100 {
end = i + 1 end = i
if len(sub) < (end - start) { if len(sub) < (end - start) {
sub = list[start:end] sub = list[start:end]
} }
start = i + 1 start = i
end = i + 1 end = i
} else { } else {
end = i + 1 end = i + 1
} }
} }
//只有一个节点,那么取差最小的节点
if len(sub) <= 1 {
return list[0:1]
}
return sub return sub
} }
......
...@@ -4,21 +4,33 @@ ...@@ -4,21 +4,33 @@
package common package common
//var NtpHosts = []string{ import (
// "time.windows.com:123", "testing"
// "tw.pool.ntp.org:123", "time"
// "pool.ntp.org:123",
// "cn.pool.ntp.org:123", "github.com/stretchr/testify/assert"
// "time.apple.com:123", )
//}
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秒从而让测试用例运行失败 // 本测试用例有概率导致误差大于1秒从而让测试用例运行失败
//func TestGetRealTime(t *testing.T) { func TestGetRealTime(t *testing.T) {
// hosts := NtpHosts hosts := NtpHosts
// nettime := GetRealTimeRetry(hosts, 10) nettime := GetRealTimeRetry(hosts, 10)
// local := time.Now() //get nettime error, ignore
// t.Log(nettime.Sub(local)) if nettime.IsZero() {
// assert.Equal(t, int(local.Sub(nettime)/time.Second), 0) 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 { ...@@ -1007,15 +1007,12 @@ func (c *Chain33) GetTimeStatus(in *types.ReqNil, result *interface{}) error {
if err != nil { if err != nil {
return err return err
} }
timeStatus := &rpctypes.TimeStatus{ timeStatus := &rpctypes.TimeStatus{
NtpTime: reply.NtpTime, NtpTime: reply.NtpTime,
LocalTime: reply.LocalTime, LocalTime: reply.LocalTime,
Diff: reply.Diff, Diff: reply.Diff,
} }
*result = timeStatus *result = timeStatus
return nil return nil
} }
......
...@@ -86,8 +86,8 @@ func parseListAccountRes(arg interface{}) (interface{}, error) { ...@@ -86,8 +86,8 @@ func parseListAccountRes(arg interface{}) (interface{}, error) {
res := arg.(*rpctypes.WalletAccounts) res := arg.(*rpctypes.WalletAccounts)
var result commandtypes.AccountsResult var result commandtypes.AccountsResult
for _, r := range res.Wallets { for _, r := range res.Wallets {
balanceResult := strconv.FormatFloat(float64(r.Acc.Balance)/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)/float64(types.Coin), 'f', 4, 64) frozenResult := strconv.FormatFloat(float64(r.Acc.Frozen/types.Int1E4)/types.Float1E4, 'f', 4, 64)
accResult := &commandtypes.AccountResult{ accResult := &commandtypes.AccountResult{
Currency: r.Acc.Currency, Currency: r.Acc.Currency,
Addr: r.Acc.Addr, Addr: r.Acc.Addr,
...@@ -188,8 +188,8 @@ func balance(cmd *cobra.Command, args []string) { ...@@ -188,8 +188,8 @@ func balance(cmd *cobra.Command, args []string) {
func parseGetBalanceRes(arg interface{}) (interface{}, error) { func parseGetBalanceRes(arg interface{}) (interface{}, error) {
res := *arg.(*[]*rpctypes.Account) res := *arg.(*[]*rpctypes.Account)
balanceResult := strconv.FormatFloat(float64(res[0].Balance)/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)/float64(types.Coin), 'f', 4, 64) frozenResult := strconv.FormatFloat(float64(res[0].Frozen/types.Int1E4)/types.Float1E4, 'f', 4, 64)
result := &commandtypes.AccountResult{ result := &commandtypes.AccountResult{
Addr: res[0].Addr, Addr: res[0].Addr,
Currency: res[0].Currency, Currency: res[0].Currency,
...@@ -204,8 +204,8 @@ func parseGetAllBalanceRes(arg interface{}) (interface{}, error) { ...@@ -204,8 +204,8 @@ func parseGetAllBalanceRes(arg interface{}) (interface{}, error) {
accs := res.ExecAccount accs := res.ExecAccount
result := commandtypes.AllExecBalance{Addr: res.Addr} result := commandtypes.AllExecBalance{Addr: res.Addr}
for _, acc := range accs { for _, acc := range accs {
balanceResult := strconv.FormatFloat(float64(acc.Account.Balance)/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)/float64(types.Coin), 'f', 4, 64) frozenResult := strconv.FormatFloat(float64(acc.Account.Frozen/types.Int1E4)/types.Float1E4, 'f', 4, 64)
ar := &commandtypes.AccountResult{ ar := &commandtypes.AccountResult{
Currency: acc.Account.Currency, Currency: acc.Account.Currency,
Balance: balanceResult, Balance: balanceResult,
......
...@@ -745,7 +745,7 @@ func execBalance(cmd *cobra.Command, args []string) { ...@@ -745,7 +745,7 @@ func execBalance(cmd *cobra.Command, args []string) {
return return
} }
data, err := common.Hex2Bytes(str) data, err := common.FromHex(str)
if err != nil { if err != nil {
fmt.Fprintln(os.Stderr, err) fmt.Fprintln(os.Stderr, err)
return return
......
...@@ -51,7 +51,7 @@ func LoadDriver(name string, height int64) (driver Driver, err error) { ...@@ -51,7 +51,7 @@ func LoadDriver(name string, height int64) (driver Driver, err error) {
name = string(types.GetRealExecName([]byte(name))) name = string(types.GetRealExecName([]byte(name)))
c, ok := registedExecDriver[name] c, ok := registedExecDriver[name]
if !ok { if !ok {
elog.Error("LoadDriver", "driver", name) elog.Debug("LoadDriver", "driver", name)
return nil, types.ErrUnRegistedDriver return nil, types.ErrUnRegistedDriver
} }
if height >= c.height || height == -1 { if height >= c.height || height == -1 {
......
...@@ -7,7 +7,6 @@ package mavl ...@@ -7,7 +7,6 @@ package mavl
import ( import (
"bytes" "bytes"
"github.com/33cn/chain33/common"
"github.com/33cn/chain33/types" "github.com/33cn/chain33/types"
"github.com/golang/protobuf/proto" "github.com/golang/protobuf/proto"
) )
...@@ -21,6 +20,8 @@ type Proof struct { ...@@ -21,6 +20,8 @@ type Proof struct {
RootHash []byte RootHash []byte
} }
var sha256Len = 32
// Verify key:value 的proof确认 // Verify key:value 的proof确认
func (proof *Proof) Verify(key []byte, value []byte, root []byte) bool { func (proof *Proof) Verify(key []byte, value []byte, root []byte) bool {
if !bytes.Equal(proof.RootHash, root) { if !bytes.Equal(proof.RootHash, root) {
...@@ -29,7 +30,7 @@ func (proof *Proof) Verify(key []byte, value []byte, root []byte) bool { ...@@ -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} leafNode := types.LeafNode{Key: key, Value: value, Height: 0, Size: 1}
leafHash := leafNode.Hash() leafHash := leafNode.Hash()
hashLen := len(common.Hash{}) hashLen := sha256Len
if len(proof.LeafHash) > hashLen { if len(proof.LeafHash) > hashLen {
proof.LeafHash = proof.LeafHash[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 ...@@ -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) { 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 return nil, 0, nil, types.ErrSize
} }
if !bytes.Contains(hashkey, []byte(leafKeyCountPrefix)) { if !bytes.Contains(hashkey, []byte(leafKeyCountPrefix)) {
...@@ -111,7 +111,7 @@ func genOldLeafCountKey(key, hash []byte, height int64, hashLen int) (hashkey [] ...@@ -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) { 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 return nil, 0, nil, types.ErrSize
} }
if !bytes.Contains(hashkey, []byte(oldLeafKeyCountPrefix)) { if !bytes.Contains(hashkey, []byte(oldLeafKeyCountPrefix)) {
...@@ -460,7 +460,7 @@ func printSameLeafKeyDB(db dbm.DB, key string, isold bool) { ...@@ -460,7 +460,7 @@ func printSameLeafKeyDB(db dbm.DB, key string, isold bool) {
if len(hash) > 32 { if len(hash) > 32 {
pri = string(hash[:16]) 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) { ...@@ -479,7 +479,7 @@ func PrintLeafNodeParent(db dbm.DB, key, hash []byte, height int64) {
if len(hash) > 32 { if len(hash) > 32 {
pri = string(hash[:16]) 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 isHave = true
...@@ -497,7 +497,7 @@ func PrintLeafNodeParent(db dbm.DB, key, hash []byte, height int64) { ...@@ -497,7 +497,7 @@ func PrintLeafNodeParent(db dbm.DB, key, hash []byte, height int64) {
if len(hash) > 32 { if len(hash) > 32 {
pri = string(hash[:16]) 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 isHave = true
...@@ -521,7 +521,7 @@ func PrintNodeDb(db dbm.DB, hash []byte) { ...@@ -521,7 +521,7 @@ func PrintNodeDb(db dbm.DB, hash []byte) {
if len(node.hash) > 32 { if len(node.hash) > 32 {
pri = string(node.hash[:16]) 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) node.printNodeInfo(nDb)
} }
...@@ -531,7 +531,7 @@ func (node *Node) printNodeInfo(db *nodeDB) { ...@@ -531,7 +531,7 @@ func (node *Node) printNodeInfo(db *nodeDB) {
if len(node.hash) > 32 { if len(node.hash) > 32 {
pri = string(node.hash[:16]) 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 return
} }
if node.leftHash != nil { if node.leftHash != nil {
...@@ -543,7 +543,7 @@ func (node *Node) printNodeInfo(db *nodeDB) { ...@@ -543,7 +543,7 @@ func (node *Node) printNodeInfo(db *nodeDB) {
if len(left.hash) > 32 { if len(left.hash) > 32 {
pri = string(left.hash[:16]) 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) left.printNodeInfo(db)
} }
...@@ -556,7 +556,7 @@ func (node *Node) printNodeInfo(db *nodeDB) { ...@@ -556,7 +556,7 @@ func (node *Node) printNodeInfo(db *nodeDB) {
if len(right.hash) > 32 { if len(right.hash) > 32 {
pri = string(right.hash[:16]) 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) right.printNodeInfo(db)
} }
} }
......
...@@ -651,12 +651,12 @@ func genRootHashHeight(blockHeight int64, hash []byte) (key []byte) { ...@@ -651,12 +651,12 @@ func genRootHashHeight(blockHeight int64, hash []byte) (key []byte) {
} }
func getRootHash(hashKey []byte) (hash []byte, err error) { 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 return nil, types.ErrSize
} }
if !bytes.Contains(hashKey, []byte(rootHashHeightPrefix)) { if !bytes.Contains(hashKey, []byte(rootHashHeightPrefix)) {
return nil, types.ErrSize return nil, types.ErrSize
} }
hash = hashKey[len(hashKey)-len(common.Hash{}):] hash = hashKey[len(hashKey)-sha256Len:]
return hash, nil return hash, nil
} }
...@@ -10,12 +10,10 @@ import ( ...@@ -10,12 +10,10 @@ import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"math/rand" "math/rand"
"sort"
"testing"
"os" "os"
"sort"
"sync" "sync"
"testing"
. "github.com/33cn/chain33/common" . "github.com/33cn/chain33/common"
"github.com/33cn/chain33/common/db" "github.com/33cn/chain33/common/db"
...@@ -264,7 +262,7 @@ func TestHashSame2(t *testing.T) { ...@@ -264,7 +262,7 @@ func TestHashSame2(t *testing.T) {
for i := 0; i < 5; i++ { for i := 0; i < 5; i++ {
prevHash, err = saveBlock(db1, int64(i), prevHash, 1000, false) prevHash, err = saveBlock(db1, int64(i), prevHash, 1000, false)
assert.Nil(t, err) assert.Nil(t, err)
str := Bytes2Hex(prevHash) str := ToHex(prevHash)
fmt.Println("unable", str) fmt.Println("unable", str)
strs1[str] = true strs1[str] = true
} }
...@@ -278,7 +276,7 @@ func TestHashSame2(t *testing.T) { ...@@ -278,7 +276,7 @@ func TestHashSame2(t *testing.T) {
for i := 0; i < 5; i++ { for i := 0; i < 5; i++ {
prevHash, err = saveBlock(db2, int64(i), prevHash, 1000, false) prevHash, err = saveBlock(db2, int64(i), prevHash, 1000, false)
assert.Nil(t, err) assert.Nil(t, err)
str := Bytes2Hex(prevHash) str := ToHex(prevHash)
fmt.Println("enable", str) fmt.Println("enable", str)
if ok := strs1[str]; !ok { if ok := strs1[str]; !ok {
t.Error("enable Prefix have a different hash") t.Error("enable Prefix have a different hash")
......
...@@ -52,6 +52,8 @@ const ( ...@@ -52,6 +52,8 @@ const (
PrivacyMaturityDegree = 12 PrivacyMaturityDegree = 12
TxGroupMaxCount = 20 TxGroupMaxCount = 20
MinerAction = "miner" MinerAction = "miner"
Int1E4 int64 = 10000
Float1E4 float64 = 10000.0
) )
//全局账户私钥/公钥 //全局账户私钥/公钥
......
...@@ -223,11 +223,13 @@ func (leafnode *LeafNode) Hash() []byte { ...@@ -223,11 +223,13 @@ func (leafnode *LeafNode) Hash() []byte {
return common.Sha256(data) return common.Sha256(data)
} }
var sha256Len = 32
//Hash 计算中间节点的hash //Hash 计算中间节点的hash
func (innernode *InnerNode) Hash() []byte { func (innernode *InnerNode) Hash() []byte {
rightHash := innernode.RightHash rightHash := innernode.RightHash
leftHash := innernode.LeftHash leftHash := innernode.LeftHash
hashLen := len(common.Hash{}) hashLen := sha256Len
if len(innernode.RightHash) > hashLen { if len(innernode.RightHash) > hashLen {
innernode.RightHash = innernode.RightHash[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