Commit 44cfc785 authored by kingwang's avatar kingwang Committed by vipwzw

update chain33 05/17

parent 5fd58c21
...@@ -437,10 +437,16 @@ func (bs *BlockStore) LoadBlockByHeight(height int64) (*types.BlockDetail, error ...@@ -437,10 +437,16 @@ func (bs *BlockStore) LoadBlockByHeight(height int64) (*types.BlockDetail, error
//LoadBlockByHash 通过hash获取BlockDetail信息 //LoadBlockByHash 通过hash获取BlockDetail信息
func (bs *BlockStore) LoadBlockByHash(hash []byte) (*types.BlockDetail, error) { func (bs *BlockStore) LoadBlockByHash(hash []byte) (*types.BlockDetail, error) {
block, _, err := bs.loadBlockByHash(hash)
return block, err
}
func (bs *BlockStore) loadBlockByHash(hash []byte) (*types.BlockDetail, int, error) {
var blockdetail types.BlockDetail var blockdetail types.BlockDetail
var blockheader types.Header var blockheader types.Header
var blockbody types.BlockBody var blockbody types.BlockBody
var block types.Block var block types.Block
var blockSize int
//通过hash获取blockheader //通过hash获取blockheader
header, err := bs.db.Get(calcHashToBlockHeaderKey(hash)) header, err := bs.db.Get(calcHashToBlockHeaderKey(hash))
...@@ -448,26 +454,30 @@ func (bs *BlockStore) LoadBlockByHash(hash []byte) (*types.BlockDetail, error) { ...@@ -448,26 +454,30 @@ func (bs *BlockStore) LoadBlockByHash(hash []byte) (*types.BlockDetail, error) {
if err != dbm.ErrNotFoundInDb { if err != dbm.ErrNotFoundInDb {
storeLog.Error("LoadBlockByHash calcHashToBlockHeaderKey", "hash", common.ToHex(hash), "err", err) storeLog.Error("LoadBlockByHash calcHashToBlockHeaderKey", "hash", common.ToHex(hash), "err", err)
} }
return nil, types.ErrHashNotExist return nil, blockSize, types.ErrHashNotExist
} }
err = proto.Unmarshal(header, &blockheader) err = proto.Unmarshal(header, &blockheader)
if err != nil { if err != nil {
storeLog.Error("LoadBlockByHash", "err", err) storeLog.Error("LoadBlockByHash", "err", err)
return nil, err return nil, blockSize, err
} }
blockSize += len(header)
//通过hash获取blockbody //通过hash获取blockbody
body, err := bs.db.Get(calcHashToBlockBodyKey(hash)) body, err := bs.db.Get(calcHashToBlockBodyKey(hash))
if body == nil || err != nil { if body == nil || err != nil {
if err != dbm.ErrNotFoundInDb { if err != dbm.ErrNotFoundInDb {
storeLog.Error("LoadBlockByHash calcHashToBlockBodyKey ", "err", err) storeLog.Error("LoadBlockByHash calcHashToBlockBodyKey ", "err", err)
} }
return nil, types.ErrHashNotExist return nil, blockSize, types.ErrHashNotExist
} }
err = proto.Unmarshal(body, &blockbody) err = proto.Unmarshal(body, &blockbody)
if err != nil { if err != nil {
storeLog.Error("LoadBlockByHash", "err", err) storeLog.Error("LoadBlockByHash", "err", err)
return nil, err return nil, blockSize, err
} }
blockSize += len(body)
block.Version = blockheader.Version block.Version = blockheader.Version
block.ParentHash = blockheader.ParentHash block.ParentHash = blockheader.ParentHash
block.TxHash = blockheader.TxHash block.TxHash = blockheader.TxHash
...@@ -485,7 +495,7 @@ func (bs *BlockStore) LoadBlockByHash(hash []byte) (*types.BlockDetail, error) { ...@@ -485,7 +495,7 @@ func (bs *BlockStore) LoadBlockByHash(hash []byte) (*types.BlockDetail, error) {
//storeLog.Info("LoadBlockByHash", "Height", block.Height, "Difficulty", blockdetail.Block.Difficulty) //storeLog.Info("LoadBlockByHash", "Height", block.Height, "Difficulty", blockdetail.Block.Difficulty)
return &blockdetail, nil return &blockdetail, blockSize, nil
} }
//SaveBlock 批量保存blocks信息到db数据库中,并返回最新的sequence值 //SaveBlock 批量保存blocks信息到db数据库中,并返回最新的sequence值
...@@ -989,13 +999,13 @@ func (bs *BlockStore) saveBlockSequence(storeBatch dbm.Batch, hash []byte, heigh ...@@ -989,13 +999,13 @@ func (bs *BlockStore) saveBlockSequence(storeBatch dbm.Batch, hash []byte, heigh
} }
//LoadBlockBySequence 通过seq高度获取BlockDetail信息 //LoadBlockBySequence 通过seq高度获取BlockDetail信息
func (bs *BlockStore) LoadBlockBySequence(Sequence int64) (*types.BlockDetail, error) { func (bs *BlockStore) LoadBlockBySequence(Sequence int64) (*types.BlockDetail, int, error) {
//首先通过Sequence序列号获取对应的blockhash和操作类型从db中 //首先通过Sequence序列号获取对应的blockhash和操作类型从db中
BlockSequence, err := bs.GetBlockSequence(Sequence) BlockSequence, err := bs.GetBlockSequence(Sequence)
if err != nil { if err != nil {
return nil, err return nil, 0, err
} }
return bs.LoadBlockByHash(BlockSequence.Hash) return bs.loadBlockByHash(BlockSequence.Hash)
} }
//GetBlockSequence 从db数据库中获取指定Sequence对应的block序列操作信息 //GetBlockSequence 从db数据库中获取指定Sequence对应的block序列操作信息
......
...@@ -854,7 +854,7 @@ func testLoadBlockBySequence(t *testing.T, blockchain *blockchain.BlockChain) { ...@@ -854,7 +854,7 @@ func testLoadBlockBySequence(t *testing.T, blockchain *blockchain.BlockChain) {
curheight := blockchain.GetBlockHeight() curheight := blockchain.GetBlockHeight()
lastseq, _ := blockchain.GetStore().LoadBlockLastSequence() lastseq, _ := blockchain.GetStore().LoadBlockLastSequence()
block, err := blockchain.GetStore().LoadBlockBySequence(lastseq) block, _, err := blockchain.GetStore().LoadBlockBySequence(lastseq)
require.NoError(t, err) require.NoError(t, err)
if block.Block.Height != curheight { if block.Block.Height != curheight {
......
...@@ -11,6 +11,11 @@ import ( ...@@ -11,6 +11,11 @@ import (
"github.com/33cn/chain33/types" "github.com/33cn/chain33/types"
) )
const (
pushMaxSeq = 100
pushMaxSize = 100 * 1024 * 1024
)
//pushNotify push Notify //pushNotify push Notify
type pushNotify struct { type pushNotify struct {
cb chan *types.BlockSeqCB cb chan *types.BlockSeqCB
...@@ -94,10 +99,10 @@ func (p *pushseq) updateSeq(seq int64) { ...@@ -94,10 +99,10 @@ func (p *pushseq) updateSeq(seq int64) {
} }
func (p *pushseq) trigeRun(run chan struct{}, sleep time.Duration) { func (p *pushseq) trigeRun(run chan struct{}, sleep time.Duration) {
if sleep > 0 {
time.Sleep(sleep)
}
go func() { go func() {
if sleep > 0 {
time.Sleep(sleep)
}
select { select {
case run <- struct{}{}: case run <- struct{}{}:
default: default:
...@@ -132,9 +137,13 @@ func (p *pushseq) runTask(input pushNotify) { ...@@ -132,9 +137,13 @@ func (p *pushseq) runTask(input pushNotify) {
p.trigeRun(run, 100*time.Millisecond) p.trigeRun(run, 100*time.Millisecond)
continue continue
} }
data, err := p.getDataBySeq(lastseq + 1) seqCount := pushMaxSeq
if lastseq+int64(seqCount) > maxseq {
seqCount = 1
}
data, err := p.getSeqs(lastseq+1, seqCount, pushMaxSize)
if err != nil { if err != nil {
chainlog.Error("getDataBySeq", "err", err) chainlog.Error("getDataBySeq", "err", err, "seq", lastseq+1, "maxSeq", seqCount)
p.trigeRun(run, 1000*time.Millisecond) p.trigeRun(run, 1000*time.Millisecond)
continue continue
} }
...@@ -146,14 +155,14 @@ func (p *pushseq) runTask(input pushNotify) { ...@@ -146,14 +155,14 @@ func (p *pushseq) runTask(input pushNotify) {
continue continue
} }
//update seqid //update seqid
lastseq = lastseq + 1 lastseq = lastseq + int64(seqCount)
p.trigeRun(run, 0) p.trigeRun(run, 0)
} }
} }
}(input) }(input)
} }
func (p *pushseq) postData(cb *types.BlockSeqCB, data *types.BlockSeq) (err error) { func (p *pushseq) postData(cb *types.BlockSeqCB, data *types.BlockSeqs) (err error) {
var postdata []byte var postdata []byte
if cb.Encode == "json" { if cb.Encode == "json" {
...@@ -195,18 +204,36 @@ func (p *pushseq) postData(cb *types.BlockSeqCB, data *types.BlockSeq) (err erro ...@@ -195,18 +204,36 @@ func (p *pushseq) postData(cb *types.BlockSeqCB, data *types.BlockSeq) (err erro
chainlog.Error("postData fail", "cb.name", cb.Name, "body", string(body)) chainlog.Error("postData fail", "cb.name", cb.Name, "body", string(body))
return types.ErrPushSeqPostData return types.ErrPushSeqPostData
} }
chainlog.Debug("postData success", "cb.name", cb.Name, "SeqNum", data.Num) chainlog.Debug("postData success", "cb.name", cb.Name, "SeqNum", data.Seqs[0].Num, "seqCount", len(data.Seqs))
return p.store.setSeqCBLastNum([]byte(cb.Name), data.Num) return p.store.setSeqCBLastNum([]byte(cb.Name), data.Seqs[0].Num+int64(len(data.Seqs))-1)
} }
func (p *pushseq) getDataBySeq(seq int64) (*types.BlockSeq, error) { func (p *pushseq) getDataBySeq(seq int64) (*types.BlockSeq, int, error) {
seqdata, err := p.store.GetBlockSequence(seq) seqdata, err := p.store.GetBlockSequence(seq)
if err != nil { if err != nil {
return nil, err return nil, 0, err
} }
detail, err := p.store.LoadBlockBySequence(seq) detail, blockSize, err := p.store.LoadBlockBySequence(seq)
if err != nil { if err != nil {
return nil, err return nil, 0, err
}
return &types.BlockSeq{Num: seq, Seq: seqdata, Detail: detail}, blockSize, nil
}
func (p *pushseq) getSeqs(seq int64, seqCount, maxSize int) (*types.BlockSeqs, error) {
seqs := &types.BlockSeqs{}
totalSize := 0
for i := 0; i < seqCount; i++ {
seq, size, err := p.getDataBySeq(seq + int64(i))
if err != nil {
return nil, err
}
if totalSize == 0 || totalSize+size < maxSize {
seqs.Seqs = append(seqs.Seqs, seq)
totalSize += size
} else {
break
}
} }
return &types.BlockSeq{Num: seq, Seq: seqdata, Detail: detail}, nil return seqs, nil
} }
...@@ -351,7 +351,9 @@ function base_test() { ...@@ -351,7 +351,9 @@ function base_test() {
if [ "$DAPP" == "" ]; then if [ "$DAPP" == "" ]; then
system_test_rpc "https://${1}:8801" system_test_rpc "https://${1}:8801"
fi fi
if [ "$DAPP" == "paracross" ]; then
system_test_rpc "https://${1}:8901"
fi
} }
function dapp_run() { function dapp_run() {
if [ -e "$DAPP_TEST_FILE" ]; then if [ -e "$DAPP_TEST_FILE" ]; then
......
...@@ -1229,29 +1229,6 @@ func (_m *QueueProtocolAPI) Version() (*types.VersionInfo, error) { ...@@ -1229,29 +1229,6 @@ func (_m *QueueProtocolAPI) Version() (*types.VersionInfo, error) {
return r0, r1 return r0, r1
} }
// WalletCreateTx provides a mock function with given fields: param
func (_m *QueueProtocolAPI) WalletCreateTx(param *types.ReqCreateTransaction) (*types.Transaction, error) {
ret := _m.Called(param)
var r0 *types.Transaction
if rf, ok := ret.Get(0).(func(*types.ReqCreateTransaction) *types.Transaction); ok {
r0 = rf(param)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*types.Transaction)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*types.ReqCreateTransaction) error); ok {
r1 = rf(param)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// WalletGetAccountList provides a mock function with given fields: req // WalletGetAccountList provides a mock function with given fields: req
func (_m *QueueProtocolAPI) WalletGetAccountList(req *types.ReqAccountList) (*types.WalletAccounts, error) { func (_m *QueueProtocolAPI) WalletGetAccountList(req *types.ReqAccountList) (*types.WalletAccounts, error) {
ret := _m.Called(req) ret := _m.Called(req)
......
...@@ -1007,19 +1007,6 @@ func (q *QueueProtocol) GetSequenceByHash(param *types.ReqHash) (*types.Int64, e ...@@ -1007,19 +1007,6 @@ func (q *QueueProtocol) GetSequenceByHash(param *types.ReqHash) (*types.Int64, e
return nil, types.ErrTypeAsset return nil, types.ErrTypeAsset
} }
// WalletCreateTx create transaction
func (q *QueueProtocol) WalletCreateTx(param *types.ReqCreateTransaction) (*types.Transaction, error) {
msg, err := q.query(walletKey, types.EventWalletCreateTx, param)
if err != nil {
log.Error("CreateTrasaction", "Error", err.Error())
return nil, err
}
if reply, ok := msg.GetData().(*types.Transaction); ok {
return reply, nil
}
return nil, types.ErrTypeAsset
}
// GetBlockByHashes get block detail list by hash list // GetBlockByHashes get block detail list by hash list
func (q *QueueProtocol) GetBlockByHashes(param *types.ReqHashes) (*types.BlockDetails, error) { func (q *QueueProtocol) GetBlockByHashes(param *types.ReqHashes) (*types.BlockDetails, error) {
if param == nil { if param == nil {
......
...@@ -94,8 +94,6 @@ type QueueProtocolAPI interface { ...@@ -94,8 +94,6 @@ type QueueProtocolAPI interface {
// types.EventSignRawTx // types.EventSignRawTx
SignRawTx(param *types.ReqSignRawTx) (*types.ReplySignRawTx, error) SignRawTx(param *types.ReqSignRawTx) (*types.ReplySignRawTx, error)
GetFatalFailure() (*types.Int32, error) GetFatalFailure() (*types.Int32, error)
// types.EventCreateTransaction 由服务器协助创建一个交易
WalletCreateTx(param *types.ReqCreateTransaction) (*types.Transaction, error)
// types.EventGetBlocks // types.EventGetBlocks
GetBlocks(param *types.ReqBlocks) (*types.BlockDetails, error) GetBlocks(param *types.ReqBlocks) (*types.BlockDetails, error)
// types.EventQueryTx // types.EventQueryTx
......
// 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 p256
import (
"crypto/ecdsa"
"crypto/elliptic"
"errors"
"math/big"
"github.com/33cn/chain33/common/crypto"
"github.com/33cn/chain33/common/vrf"
)
// GenVrfKey returns vrf private and public key
func GenVrfKey(key crypto.PrivKey) (vrf.PrivateKey, vrf.PublicKey, []byte) {
priv, pub := PrivKeyFromBytes(elliptic.P256(), key.Bytes())
return &PrivateKey{PrivateKey: priv}, &PublicKey{PublicKey: pub}, SerializePublicKey(pub)
}
// PrivKeyFromBytes return ecdsa private and public key
func PrivKeyFromBytes(curve elliptic.Curve, pk []byte) (*ecdsa.PrivateKey, *ecdsa.PublicKey) {
x, y := curve.ScalarBaseMult(pk)
priv := &ecdsa.PrivateKey{
PublicKey: ecdsa.PublicKey{
Curve: curve,
X: x,
Y: y,
},
D: new(big.Int).SetBytes(pk),
}
return priv, &priv.PublicKey
}
// SerializePublicKey serialize public key
func SerializePublicKey(p *ecdsa.PublicKey) []byte {
b := make([]byte, 0, 65)
b = append(b, 0x4)
b = paddedAppend(32, b, p.X.Bytes())
return paddedAppend(32, b, p.Y.Bytes())
}
func paddedAppend(size uint, dst, src []byte) []byte {
for i := 0; i < int(size)-len(src); i++ {
dst = append(dst, 0)
}
return append(dst, src...)
}
// ParseVrfPubKey parse public key
func ParseVrfPubKey(pubKeyStr []byte) (vrf.PublicKey, error) {
pubkey := &ecdsa.PublicKey{}
pubkey.Curve = elliptic.P256()
if len(pubKeyStr) == 0 {
return nil, errors.New("pubkey string is empty")
}
pubkey.X = new(big.Int).SetBytes(pubKeyStr[1:33])
pubkey.Y = new(big.Int).SetBytes(pubKeyStr[33:])
if pubkey.X.Cmp(pubkey.Curve.Params().P) >= 0 {
return nil, errors.New("pubkey X parameter is >= to P")
}
if pubkey.Y.Cmp(pubkey.Curve.Params().P) >= 0 {
return nil, errors.New("pubkey Y parameter is >= to P")
}
if !pubkey.Curve.IsOnCurve(pubkey.X, pubkey.Y) {
return nil, errors.New("pubkey isn't on secp256k1 curve")
}
return &PublicKey{PublicKey: pubkey}, nil
}
// 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 p256
import (
"testing"
"github.com/33cn/chain33/common/crypto"
"github.com/33cn/chain33/common/vrf"
"github.com/33cn/chain33/types"
"github.com/stretchr/testify/assert"
)
func Test_GenerateKey(t *testing.T) {
k, pk := GenerateKey()
testVRF(t, k, pk)
}
func Test_GenVrfKey(t *testing.T) {
c, err := crypto.New(types.GetSignName("", types.SECP256K1))
assert.NoError(t, err)
priv, err := c.GenKey()
assert.NoError(t, err)
vpriv, _, pubKey := GenVrfKey(priv)
vpub, err := ParseVrfPubKey(pubKey)
assert.NoError(t, err)
testVRF(t, vpriv, vpub)
}
func testVRF(t *testing.T, priv vrf.PrivateKey, pub vrf.PublicKey) {
m1 := []byte("data1")
m2 := []byte("data2")
m3 := []byte("data2")
hash1, proof1 := priv.Evaluate(m1)
hash2, proof2 := priv.Evaluate(m2)
hash3, proof3 := priv.Evaluate(m3)
for _, tc := range []struct {
m []byte
hash [32]byte
proof []byte
err error
}{
{m1, hash1, proof1, nil},
{m2, hash2, proof2, nil},
{m3, hash3, proof3, nil},
{m3, hash3, proof2, nil},
{m3, hash3, proof1, ErrInvalidVRF},
} {
hash, err := pub.ProofToHash(tc.m, tc.proof)
if got, want := err, tc.err; got != want {
t.Errorf("ProofToHash(%s, %x): %v, want %v", tc.m, tc.proof, got, want)
}
if err != nil {
continue
}
if got, want := hash, tc.hash; got != want {
t.Errorf("ProofToHash(%s, %x): %x, want %x", tc.m, tc.proof, got, want)
}
}
}
...@@ -2,8 +2,22 @@ ...@@ -2,8 +2,22 @@
// Use of this source code is governed by a BSD-style // Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
// Package p256 implements a verifiable random function using curve p256. // Copyright 2016 Google Inc. All Rights Reserved.
package p256 //
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package secp256k1 implements a verifiable random function using curve secp256k1.
package secp256k1
import ( import (
"bytes" "bytes"
...@@ -19,11 +33,11 @@ import ( ...@@ -19,11 +33,11 @@ import (
"math/big" "math/big"
vrfp "github.com/33cn/chain33/common/vrf" vrfp "github.com/33cn/chain33/common/vrf"
"github.com/btcsuite/btcd/btcec"
) )
var ( var (
curve = elliptic.P256() curve = btcec.S256()
params = curve.Params()
// ErrInvalidVRF err // ErrInvalidVRF err
ErrInvalidVRF = errors.New("invalid VRF proof") ErrInvalidVRF = errors.New("invalid VRF proof")
) )
...@@ -52,7 +66,7 @@ func GenerateKey() (vrfp.PrivateKey, vrfp.PublicKey) { ...@@ -52,7 +66,7 @@ func GenerateKey() (vrfp.PrivateKey, vrfp.PublicKey) {
func H1(m []byte) (x, y *big.Int) { func H1(m []byte) (x, y *big.Int) {
h := sha512.New() h := sha512.New()
var i uint32 var i uint32
byteLen := (params.BitSize + 7) >> 3 byteLen := (curve.BitSize + 7) >> 3
for x == nil && i < 100 { for x == nil && i < 100 {
// TODO: Use a NIST specified DRBG. // TODO: Use a NIST specified DRBG.
h.Reset() h.Reset()
...@@ -75,7 +89,7 @@ var one = big.NewInt(1) ...@@ -75,7 +89,7 @@ var one = big.NewInt(1)
// H2 hashes to an integer [1,N-1] // H2 hashes to an integer [1,N-1]
func H2(m []byte) *big.Int { func H2(m []byte) *big.Int {
// NIST SP 800-90A § A.5.1: Simple discard method. // NIST SP 800-90A § A.5.1: Simple discard method.
byteLen := (params.BitSize + 7) >> 3 byteLen := (curve.BitSize + 7) >> 3
h := sha512.New() h := sha512.New()
for i := uint32(0); ; i++ { for i := uint32(0); ; i++ {
// TODO: Use a NIST specified DRBG. // TODO: Use a NIST specified DRBG.
...@@ -88,7 +102,7 @@ func H2(m []byte) *big.Int { ...@@ -88,7 +102,7 @@ func H2(m []byte) *big.Int {
} }
b := h.Sum(nil) b := h.Sum(nil)
k := new(big.Int).SetBytes(b[:byteLen]) k := new(big.Int).SetBytes(b[:byteLen])
if k.Cmp(new(big.Int).Sub(params.N, one)) == -1 { if k.Cmp(new(big.Int).Sub(curve.N, one)) == -1 {
return k.Add(k, one) return k.Add(k, one)
} }
} }
...@@ -108,15 +122,15 @@ func (k PrivateKey) Evaluate(m []byte) (index [32]byte, proof []byte) { ...@@ -108,15 +122,15 @@ func (k PrivateKey) Evaluate(m []byte) (index [32]byte, proof []byte) {
Hx, Hy := H1(m) Hx, Hy := H1(m)
// VRF_k(m) = [k]H // VRF_k(m) = [k]H
sHx, sHy := params.ScalarMult(Hx, Hy, k.D.Bytes()) sHx, sHy := curve.ScalarMult(Hx, Hy, k.D.Bytes())
vrf := elliptic.Marshal(curve, sHx, sHy) // 65 bytes. vrf := elliptic.Marshal(curve, sHx, sHy) // 65 bytes.
// G is the base point // G is the base point
// s = H2(G, H, [k]G, VRF, [r]G, [r]H) // s = H2(G, H, [k]G, VRF, [r]G, [r]H)
rGx, rGy := params.ScalarBaseMult(r) rGx, rGy := curve.ScalarBaseMult(r)
rHx, rHy := params.ScalarMult(Hx, Hy, r) rHx, rHy := curve.ScalarMult(Hx, Hy, r)
var b bytes.Buffer var b bytes.Buffer
if _, err := b.Write(elliptic.Marshal(curve, params.Gx, params.Gy)); err != nil { if _, err := b.Write(elliptic.Marshal(curve, curve.Gx, curve.Gy)); err != nil {
panic(err) panic(err)
} }
if _, err := b.Write(elliptic.Marshal(curve, Hx, Hy)); err != nil { if _, err := b.Write(elliptic.Marshal(curve, Hx, Hy)); err != nil {
...@@ -138,7 +152,7 @@ func (k PrivateKey) Evaluate(m []byte) (index [32]byte, proof []byte) { ...@@ -138,7 +152,7 @@ func (k PrivateKey) Evaluate(m []byte) (index [32]byte, proof []byte) {
// t = r−s*k mod N // t = r−s*k mod N
t := new(big.Int).Sub(ri, new(big.Int).Mul(s, k.D)) t := new(big.Int).Sub(ri, new(big.Int).Mul(s, k.D))
t.Mod(t, params.N) t.Mod(t, curve.N)
// Index = H(vrf) // Index = H(vrf)
index = sha256.Sum256(vrf) index = sha256.Sum256(vrf)
...@@ -184,22 +198,22 @@ func (pk *PublicKey) ProofToHash(m, proof []byte) (index [32]byte, err error) { ...@@ -184,22 +198,22 @@ func (pk *PublicKey) ProofToHash(m, proof []byte) (index [32]byte, err error) {
} }
// [t]G + [s]([k]G) = [t+ks]G // [t]G + [s]([k]G) = [t+ks]G
tGx, tGy := params.ScalarBaseMult(t) tGx, tGy := curve.ScalarBaseMult(t)
ksGx, ksGy := params.ScalarMult(pk.X, pk.Y, s) ksGx, ksGy := curve.ScalarMult(pk.X, pk.Y, s)
tksGx, tksGy := params.Add(tGx, tGy, ksGx, ksGy) tksGx, tksGy := curve.Add(tGx, tGy, ksGx, ksGy)
// H = H1(m) // H = H1(m)
// [t]H + [s]VRF = [t+ks]H // [t]H + [s]VRF = [t+ks]H
Hx, Hy := H1(m) Hx, Hy := H1(m)
tHx, tHy := params.ScalarMult(Hx, Hy, t) tHx, tHy := curve.ScalarMult(Hx, Hy, t)
sHx, sHy := params.ScalarMult(uHx, uHy, s) sHx, sHy := curve.ScalarMult(uHx, uHy, s)
tksHx, tksHy := params.Add(tHx, tHy, sHx, sHy) tksHx, tksHy := curve.Add(tHx, tHy, sHx, sHy)
// H2(G, H, [k]G, VRF, [t]G + [s]([k]G), [t]H + [s]VRF) // H2(G, H, [k]G, VRF, [t]G + [s]([k]G), [t]H + [s]VRF)
// = H2(G, H, [k]G, VRF, [t+ks]G, [t+ks]H) // = H2(G, H, [k]G, VRF, [t+ks]G, [t+ks]H)
// = H2(G, H, [k]G, VRF, [r]G, [r]H) // = H2(G, H, [k]G, VRF, [r]G, [r]H)
var b bytes.Buffer var b bytes.Buffer
if _, err := b.Write(elliptic.Marshal(curve, params.Gx, params.Gy)); err != nil { if _, err := b.Write(elliptic.Marshal(curve, curve.Gx, curve.Gy)); err != nil {
panic(err) panic(err)
} }
if _, err := b.Write(elliptic.Marshal(curve, Hx, Hy)); err != nil { if _, err := b.Write(elliptic.Marshal(curve, Hx, Hy)); err != nil {
......
...@@ -2,7 +2,21 @@ ...@@ -2,7 +2,21 @@
// Use of this source code is governed by a BSD-style // Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package p256 // Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package secp256k1
import ( import (
"bytes" "bytes"
...@@ -21,7 +35,7 @@ func TestH1(t *testing.T) { ...@@ -21,7 +35,7 @@ func TestH1(t *testing.T) {
if x == nil { if x == nil {
t.Errorf("H1(%v)=%v, want curve point", m, x) t.Errorf("H1(%v)=%v, want curve point", m, x)
} }
if got := curve.Params().IsOnCurve(x, y); !got { if got := curve.IsOnCurve(x, y); !got {
t.Errorf("H1(%v)=[%v, %v], is not on curve", m, x, y) t.Errorf("H1(%v)=[%v, %v], is not on curve", m, x, y)
} }
} }
......
...@@ -2,7 +2,21 @@ ...@@ -2,7 +2,21 @@
// Use of this source code is governed by a BSD-style // Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package p256 // Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package secp256k1
import ( import (
"crypto/elliptic" "crypto/elliptic"
...@@ -42,17 +56,17 @@ func Unmarshal(curve elliptic.Curve, data []byte) (x, y *big.Int) { ...@@ -42,17 +56,17 @@ func Unmarshal(curve elliptic.Curve, data []byte) (x, y *big.Int) {
} }
// Use the curve equation to calculate y² given x. // Use the curve equation to calculate y² given x.
// only applies to curves of the form y² = x³ - 3x + b. // only applies to curves of the form y² = x³ + b.
func y2(curve *elliptic.CurveParams, x *big.Int) *big.Int { func y2(curve *elliptic.CurveParams, x *big.Int) *big.Int {
// y² = x³ - 3x + b // y² = x³ + b
x3 := new(big.Int).Mul(x, x) x3 := new(big.Int).Mul(x, x)
x3.Mul(x3, x) x3.Mul(x3, x)
threeX := new(big.Int).Lsh(x, 1) //threeX := new(big.Int).Lsh(x, 1)
threeX.Add(threeX, x) //threeX.Add(threeX, x)
//
x3.Sub(x3, threeX) //x3.Sub(x3, threeX)
x3.Add(x3, curve.B) x3.Add(x3, curve.B)
x3.Mod(x3, curve.P) x3.Mod(x3, curve.P)
return x3 return x3
......
...@@ -2,6 +2,20 @@ ...@@ -2,6 +2,20 @@
// Use of this source code is governed by a BSD-style // Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package vrf defines the interface to a verifiable random function. // Package vrf defines the interface to a verifiable random function.
package vrf package vrf
......
...@@ -728,7 +728,13 @@ func (c *Chain33) GetWalletStatus(in types.ReqNil, result *interface{}) error { ...@@ -728,7 +728,13 @@ func (c *Chain33) GetWalletStatus(in types.ReqNil, result *interface{}) error {
if err != nil { if err != nil {
return err return err
} }
*result = reply status := rpctypes.WalletStatus{
IsWalletLock: reply.IsWalletLock,
IsAutoMining: reply.IsAutoMining,
IsHasSeed: reply.IsHasSeed,
IsTicketLock: reply.IsTicketLock,
}
*result = &status
return nil return nil
} }
...@@ -982,17 +988,6 @@ func (c *Chain33) GetTimeStatus(in *types.ReqNil, result *interface{}) error { ...@@ -982,17 +988,6 @@ func (c *Chain33) GetTimeStatus(in *types.ReqNil, result *interface{}) error {
return nil return nil
} }
// WalletCreateTx wallet create tx
func (c *Chain33) WalletCreateTx(in types.ReqCreateTransaction, result *interface{}) error {
reply, err := c.cli.WalletCreateTx(&in)
if err != nil {
return err
}
txHex := types.Encode(reply)
*result = hex.EncodeToString(txHex)
return nil
}
// CloseQueue close queue // CloseQueue close queue
func (c *Chain33) CloseQueue(in *types.ReqNil, result *interface{}) error { func (c *Chain33) CloseQueue(in *types.ReqNil, result *interface{}) error {
go func() { go func() {
......
...@@ -1073,8 +1073,7 @@ func TestChain33_GetWalletStatus(t *testing.T) { ...@@ -1073,8 +1073,7 @@ func TestChain33_GetWalletStatus(t *testing.T) {
api := new(mocks.QueueProtocolAPI) api := new(mocks.QueueProtocolAPI)
testChain33 := newTestChain33(api) testChain33 := newTestChain33(api)
// expected := &types.GetSeedByPw{} api.On("GetWalletStatus").Return(nil, errors.New("error value")).Once()
api.On("GetWalletStatus").Return(nil, errors.New("error value"))
var testResult interface{} var testResult interface{}
actual := types.ReqNil{} actual := types.ReqNil{}
...@@ -1083,6 +1082,25 @@ func TestChain33_GetWalletStatus(t *testing.T) { ...@@ -1083,6 +1082,25 @@ func TestChain33_GetWalletStatus(t *testing.T) {
assert.Equal(t, nil, testResult) assert.Equal(t, nil, testResult)
assert.NotNil(t, err) assert.NotNil(t, err)
expect := types.WalletStatus{
IsWalletLock: true,
IsAutoMining: true,
IsHasSeed: false,
IsTicketLock: false,
}
api.On("GetWalletStatus").Return(&expect, nil).Once()
err = testChain33.GetWalletStatus(actual, &testResult)
t.Log(err)
assert.Nil(t, err)
status, ok := testResult.(*rpctypes.WalletStatus)
if !ok {
t.Error("GetWalletStatus type error")
}
assert.Equal(t, expect.IsWalletLock, status.IsWalletLock)
assert.Equal(t, expect.IsAutoMining, status.IsAutoMining)
assert.Equal(t, expect.IsHasSeed, status.IsHasSeed)
assert.Equal(t, expect.IsTicketLock, status.IsTicketLock)
mock.AssertExpectationsForObjects(t, api) mock.AssertExpectationsForObjects(t, api)
} }
...@@ -1343,15 +1361,6 @@ func TestChain33_DecodeRawTransaction(t *testing.T) { ...@@ -1343,15 +1361,6 @@ func TestChain33_DecodeRawTransaction(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
} }
func TestChain33_WalletCreateTx(t *testing.T) {
api := new(mocks.QueueProtocolAPI)
client := newTestChain33(api)
var testResult interface{}
api.On("WalletCreateTx", mock.Anything).Return(&types.Transaction{}, nil)
err := client.WalletCreateTx(types.ReqCreateTransaction{}, &testResult)
assert.NoError(t, err)
}
func TestChain33_CloseQueue(t *testing.T) { func TestChain33_CloseQueue(t *testing.T) {
api := new(mocks.QueueProtocolAPI) api := new(mocks.QueueProtocolAPI)
client := newTestChain33(api) client := newTestChain33(api)
......
...@@ -791,18 +791,34 @@ func TestAddTxGroup(t *testing.T) { ...@@ -791,18 +791,34 @@ func TestAddTxGroup(t *testing.T) {
q, mem := initEnv(0) q, mem := initEnv(0)
defer q.Close() defer q.Close()
defer mem.Close() defer mem.Close()
toAddr := "1PjMi9yGTjA9bbqUZa1Sj7dAUKyLA8KqE1"
//copytx //copytx
ctx2 := *tx2 crouptx1 := types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 460000000, Expire: 0, To: toAddr}
ctx3 := *tx3 crouptx2 := types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 100, Expire: 0, To: toAddr}
ctx4 := *tx4 crouptx3 := types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 100000000, Expire: 0, To: toAddr}
txGroup, _ := types.CreateTxGroup([]*types.Transaction{&ctx2, &ctx3, &ctx4}) crouptx4 := types.Transaction{Execer: []byte("user.write"), Payload: types.Encode(transfer), Fee: 100000000, Expire: 0, To: toAddr}
txGroup, _ := types.CreateTxGroup([]*types.Transaction{&crouptx1, &crouptx2, &crouptx3, &crouptx4})
for i := range txGroup.Txs {
err := txGroup.SignN(i, types.SECP256K1, mainPriv)
if err != nil {
t.Error("TestAddTxGroup SignNfailed ", err.Error())
}
}
tx := txGroup.Tx() tx := txGroup.Tx()
msg := mem.client.NewMessage("mempool", types.EventTx, tx) msg := mem.client.NewMessage("mempool", types.EventTx, tx)
mem.client.Send(msg, true) mem.client.Send(msg, true)
_, err := mem.client.Wait(msg) resp, err := mem.client.Wait(msg)
if err != nil { if err != nil {
t.Error("TestAddTxGroup failed", err.Error()) t.Error("TestAddTxGroup failed", err.Error())
} }
reply := resp.GetData().(*types.Reply)
if !reply.GetIsOk() {
t.Error("TestAddTxGroup failed", string(reply.GetMsg()))
}
} }
func BenchmarkMempool(b *testing.B) { func BenchmarkMempool(b *testing.B) {
......
...@@ -134,12 +134,12 @@ const ( ...@@ -134,12 +134,12 @@ const (
EventAddParaChainBlockDetail = 126 EventAddParaChainBlockDetail = 126
EventGetSeqByHash = 127 EventGetSeqByHash = 127
EventLocalPrefixCount = 128 EventLocalPrefixCount = 128
EventWalletCreateTx = 129 //EventWalletCreateTx = 129
EventStoreList = 130 EventStoreList = 130
EventStoreListReply = 131 EventStoreListReply = 131
EventListBlockSeqCB = 132 EventListBlockSeqCB = 132
EventGetSeqCBLastNum = 133 EventGetSeqCBLastNum = 133
EventGetBlockBySeq = 134 EventGetBlockBySeq = 134
EventLocalBegin = 135 EventLocalBegin = 135
EventLocalCommit = 136 EventLocalCommit = 136
...@@ -284,7 +284,7 @@ var eventName = map[int]string{ ...@@ -284,7 +284,7 @@ var eventName = map[int]string{
127: "EventGetSeqByHash", 127: "EventGetSeqByHash",
128: "EventLocalPrefixCount", 128: "EventLocalPrefixCount",
//todo: 这个可能后面会删除 //todo: 这个可能后面会删除
EventWalletCreateTx: "EventWalletCreateTx", //EventWalletCreateTx: "EventWalletCreateTx",
EventStoreList: "EventStoreList", EventStoreList: "EventStoreList",
EventStoreListReply: "EventStoreListReply", EventStoreListReply: "EventStoreListReply",
// Token // Token
......
...@@ -63,6 +63,10 @@ message BlockSeq { ...@@ -63,6 +63,10 @@ message BlockSeq {
BlockDetail detail = 3; BlockDetail detail = 3;
} }
message BlockSeqs {
repeated BlockSeq seqs = 1;
}
//节点ID以及对应的Block //节点ID以及对应的Block
message BlockPid { message BlockPid {
string pid = 1; string pid = 1;
......
...@@ -224,27 +224,6 @@ message Int32 { ...@@ -224,27 +224,6 @@ message Int32 {
int32 data = 1; int32 data = 1;
} }
// 某些交易需要存在一些复杂的算法,所以需要请求服务器协助构建交易,返回对应交易哈希值,后续签名可以根据此哈希值进行处理
message ReqCreateTransaction {
string tokenname = 1;
// 构建交易类型
// 0:普通的交易(暂不支持)
// 1:隐私交易 公开->隐私
// 2:隐私交易 隐私->隐私
// 3:隐私交易 隐私->公开
int32 type = 2;
int64 amount = 3;
string note = 4;
// 普通交易的发送方
string from = 5;
// 普通交易的接收方
string to = 6;
// 隐私交易,接收方的公钥对
string pubkeypair = 10;
int32 mixcount = 11;
int64 expire = 12;
}
message ReqAccountList { message ReqAccountList {
bool withoutBalance = 1; bool withoutBalance = 1;
} }
\ No newline at end of file
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