types: update for new go-wire. WriteSignBytes -> SignBytes

This commit is contained in:
Ethan Buchman 2018-01-14 19:05:22 -05:00
parent 9cdba04fe9
commit 200787ede2
12 changed files with 67 additions and 81 deletions

View File

@ -4,7 +4,6 @@ import (
"bytes" "bytes"
"errors" "errors"
"fmt" "fmt"
"io"
"strings" "strings"
"time" "time"
@ -96,7 +95,11 @@ func (b *Block) Hash() cmn.HexBytes {
// MakePartSet returns a PartSet containing parts of a serialized block. // MakePartSet returns a PartSet containing parts of a serialized block.
// This is the form in which the block is gossipped to peers. // This is the form in which the block is gossipped to peers.
func (b *Block) MakePartSet(partSize int) *PartSet { func (b *Block) MakePartSet(partSize int) *PartSet {
return NewPartSetFromData(wire.BinaryBytes(b), partSize) bz, err := wire.MarshalBinary(b)
if err != nil {
panic(err)
}
return NewPartSetFromData(bz, partSize)
} }
// HashesTo is a convenience function that checks if a block hashes to the given argument. // HashesTo is a convenience function that checks if a block hashes to the given argument.
@ -493,17 +496,11 @@ func (blockID BlockID) Equals(other BlockID) bool {
// Key returns a machine-readable string representation of the BlockID // Key returns a machine-readable string representation of the BlockID
func (blockID BlockID) Key() string { func (blockID BlockID) Key() string {
return string(blockID.Hash) + string(wire.BinaryBytes(blockID.PartsHeader)) bz, err := wire.MarshalBinary(blockID.PartsHeader)
} if err != nil {
panic(err)
// WriteSignBytes writes the canonical bytes of the BlockID to the given writer for digital signing
func (blockID BlockID) WriteSignBytes(w io.Writer, n *int, err *error) {
if blockID.IsZero() {
wire.WriteTo([]byte("null"), w, n, err)
} else {
wire.WriteJSON(CanonicalBlockID(blockID), w, n, err)
} }
return string(blockID.Hash) + string(bz)
} }
// String returns a human readable string representation of the BlockID // String returns a human readable string representation of the BlockID
@ -527,6 +524,11 @@ func (h hasher) Hash() []byte {
} }
func tmHash(item interface{}) []byte {
h := hasher{item}
return h.Hash()
}
func wireHasher(item interface{}) merkle.Hasher { func wireHasher(item interface{}) merkle.Hasher {
return hasher{item} return hasher{item}
} }

View File

@ -148,10 +148,10 @@ func (dve *DuplicateVoteEvidence) Verify(chainID string) error {
} }
// Signatures must be valid // Signatures must be valid
if !dve.PubKey.VerifyBytes(SignBytes(chainID, dve.VoteA), dve.VoteA.Signature) { if !dve.PubKey.VerifyBytes(dve.VoteA.SignBytes(chainID), dve.VoteA.Signature) {
return fmt.Errorf("DuplicateVoteEvidence Error verifying VoteA: %v", ErrVoteInvalidSignature) return fmt.Errorf("DuplicateVoteEvidence Error verifying VoteA: %v", ErrVoteInvalidSignature)
} }
if !dve.PubKey.VerifyBytes(SignBytes(chainID, dve.VoteB), dve.VoteB.Signature) { if !dve.PubKey.VerifyBytes(dve.VoteB.SignBytes(chainID), dve.VoteB.Signature) {
return fmt.Errorf("DuplicateVoteEvidence Error verifying VoteB: %v", ErrVoteInvalidSignature) return fmt.Errorf("DuplicateVoteEvidence Error verifying VoteB: %v", ErrVoteInvalidSignature)
} }

View File

@ -2,7 +2,6 @@ package types
import ( import (
"fmt" "fmt"
"io"
"github.com/tendermint/go-crypto" "github.com/tendermint/go-crypto"
"github.com/tendermint/go-wire" "github.com/tendermint/go-wire"
@ -23,13 +22,17 @@ type Heartbeat struct {
Signature crypto.Signature `json:"signature"` Signature crypto.Signature `json:"signature"`
} }
// WriteSignBytes writes the Heartbeat for signing. // SignBytes returns the Heartbeat bytes for signing.
// It panics if the Heartbeat is nil. // It panics if the Heartbeat is nil.
func (heartbeat *Heartbeat) WriteSignBytes(chainID string, w io.Writer, n *int, err *error) { func (heartbeat *Heartbeat) SignBytes(chainID string) []byte {
wire.WriteJSON(CanonicalJSONOnceHeartbeat{ bz, err := wire.MarshalJSON(CanonicalJSONOnceHeartbeat{
chainID, chainID,
CanonicalHeartbeat(heartbeat), CanonicalHeartbeat(heartbeat),
}, w, n, err) })
if err != nil {
panic(err)
}
return bz
} }
// Copy makes a copy of the Heartbeat. // Copy makes a copy of the Heartbeat.

View File

@ -9,7 +9,6 @@ import (
"golang.org/x/crypto/ripemd160" "golang.org/x/crypto/ripemd160"
"github.com/tendermint/go-wire"
cmn "github.com/tendermint/tmlibs/common" cmn "github.com/tendermint/tmlibs/common"
"github.com/tendermint/tmlibs/merkle" "github.com/tendermint/tmlibs/merkle"
) )
@ -73,10 +72,6 @@ func (psh PartSetHeader) Equals(other PartSetHeader) bool {
return psh.Total == other.Total && bytes.Equal(psh.Hash, other.Hash) return psh.Total == other.Total && bytes.Equal(psh.Hash, other.Hash)
} }
func (psh PartSetHeader) WriteSignBytes(w io.Writer, n *int, err *error) {
wire.WriteJSON(CanonicalPartSetHeader(psh), w, n, err)
}
//------------------------------------- //-------------------------------------
type PartSet struct { type PartSet struct {

View File

@ -234,10 +234,11 @@ func (privVal *PrivValidatorFS) save() {
// Reset resets all fields in the PrivValidatorFS. // Reset resets all fields in the PrivValidatorFS.
// NOTE: Unsafe! // NOTE: Unsafe!
func (privVal *PrivValidatorFS) Reset() { func (privVal *PrivValidatorFS) Reset() {
var sig crypto.Signature
privVal.LastHeight = 0 privVal.LastHeight = 0
privVal.LastRound = 0 privVal.LastRound = 0
privVal.LastStep = 0 privVal.LastStep = 0
privVal.LastSignature = crypto.Signature{} privVal.LastSignature = sig
privVal.LastSignBytes = nil privVal.LastSignBytes = nil
privVal.Save() privVal.Save()
} }
@ -297,7 +298,7 @@ func (privVal *PrivValidatorFS) checkHRS(height int64, round int, step int8) (bo
// a previously signed vote (ie. we crashed after signing but before the vote hit the WAL). // a previously signed vote (ie. we crashed after signing but before the vote hit the WAL).
func (privVal *PrivValidatorFS) signVote(chainID string, vote *Vote) error { func (privVal *PrivValidatorFS) signVote(chainID string, vote *Vote) error {
height, round, step := vote.Height, vote.Round, voteToStep(vote) height, round, step := vote.Height, vote.Round, voteToStep(vote)
signBytes := SignBytes(chainID, vote) signBytes := vote.SignBytes(chainID)
sameHRS, err := privVal.checkHRS(height, round, step) sameHRS, err := privVal.checkHRS(height, round, step)
if err != nil { if err != nil {
@ -336,7 +337,7 @@ func (privVal *PrivValidatorFS) signVote(chainID string, vote *Vote) error {
// a previously signed proposal ie. we crashed after signing but before the proposal hit the WAL). // a previously signed proposal ie. we crashed after signing but before the proposal hit the WAL).
func (privVal *PrivValidatorFS) signProposal(chainID string, proposal *Proposal) error { func (privVal *PrivValidatorFS) signProposal(chainID string, proposal *Proposal) error {
height, round, step := proposal.Height, proposal.Round, stepPropose height, round, step := proposal.Height, proposal.Round, stepPropose
signBytes := SignBytes(chainID, proposal) signBytes := proposal.SignBytes(chainID)
sameHRS, err := privVal.checkHRS(height, round, step) sameHRS, err := privVal.checkHRS(height, round, step)
if err != nil { if err != nil {
@ -388,7 +389,7 @@ func (privVal *PrivValidatorFS) SignHeartbeat(chainID string, heartbeat *Heartbe
privVal.mtx.Lock() privVal.mtx.Lock()
defer privVal.mtx.Unlock() defer privVal.mtx.Unlock()
var err error var err error
heartbeat.Signature, err = privVal.Sign(SignBytes(chainID, heartbeat)) heartbeat.Signature, err = privVal.Sign(heartbeat.SignBytes(chainID))
return err return err
} }

View File

@ -3,7 +3,6 @@ package types
import ( import (
"errors" "errors"
"fmt" "fmt"
"io"
"time" "time"
"github.com/tendermint/go-crypto" "github.com/tendermint/go-crypto"
@ -50,10 +49,14 @@ func (p *Proposal) String() string {
p.POLBlockID, p.Signature, CanonicalTime(p.Timestamp)) p.POLBlockID, p.Signature, CanonicalTime(p.Timestamp))
} }
// WriteSignBytes writes the Proposal bytes for signing // SignBytes returns the Proposal bytes for signing
func (p *Proposal) WriteSignBytes(chainID string, w io.Writer, n *int, err *error) { func (p *Proposal) SignBytes(chainID string) []byte {
wire.WriteJSON(CanonicalJSONOnceProposal{ bz, err := wire.MarshalJSON(CanonicalJSONOnceProposal{
ChainID: chainID, ChainID: chainID,
Proposal: CanonicalProposal(p), Proposal: CanonicalProposal(p),
}, w, n, err) })
if err != nil {
panic(err)
}
return bz
} }

View File

@ -18,7 +18,7 @@ type ABCIResult struct {
// Hash returns the canonical hash of the ABCIResult // Hash returns the canonical hash of the ABCIResult
func (a ABCIResult) Hash() []byte { func (a ABCIResult) Hash() []byte {
return wire.BinaryRipemd160(a) return merkle.SimpleHashFromBinary(a)
} }
// ABCIResults wraps the deliver tx results to return a proof // ABCIResults wraps the deliver tx results to return a proof
@ -42,7 +42,11 @@ func NewResultFromResponse(response *abci.ResponseDeliverTx) ABCIResult {
// Bytes serializes the ABCIResponse using go-wire // Bytes serializes the ABCIResponse using go-wire
func (a ABCIResults) Bytes() []byte { func (a ABCIResults) Bytes() []byte {
return wire.BinaryBytes(a) bz, err := wire.MarshalBinary(a)
if err != nil {
panic(err)
}
return bz
} }
// Hash returns a merkle hash of all results // Hash returns a merkle hash of all results

View File

@ -1,24 +1,20 @@
package types package types
import ( import (
"bytes" "github.com/tendermint/tmlibs/merkle"
"io"
cmn "github.com/tendermint/tmlibs/common"
) )
// Signable is an interface for all signable things. // Signable is an interface for all signable things.
// It typically removes signatures before serializing. // It typically removes signatures before serializing.
// SignBytes returns the bytes to be signed
// NOTE: chainIDs are part of the SignBytes but not
// necessarily the object themselves.
// NOTE: Expected to panic if there is an error marshalling.
type Signable interface { type Signable interface {
WriteSignBytes(chainID string, w io.Writer, n *int, err *error) SignBytes(chainID string) []byte
} }
// SignBytes is a convenience method for getting the bytes to sign of a Signable. // HashSignBytes is a convenience method for getting the hash of the bytes of a signable
func SignBytes(chainID string, o Signable) []byte { func HashSignBytes(chainID string, o Signable) []byte {
buf, n, err := new(bytes.Buffer), new(int), new(error) return merkle.SimpleHashFromBinary(o.SignBytes(chainID))
o.WriteSignBytes(chainID, buf, n, err)
if *err != nil {
cmn.PanicCrisis(err)
}
return buf.Bytes()
} }

View File

@ -29,7 +29,7 @@ func MakeCommit(blockID BlockID, height int64, round int,
} }
func signAddVote(privVal *PrivValidatorFS, vote *Vote, voteSet *VoteSet) (signed bool, err error) { func signAddVote(privVal *PrivValidatorFS, vote *Vote, voteSet *VoteSet) (signed bool, err error) {
vote.Signature, err = privVal.Signer.Sign(SignBytes(voteSet.ChainID(), vote)) vote.Signature, err = privVal.Signer.Sign(vote.SignBytes(voteSet.ChainID()))
if err != nil { if err != nil {
return false, err return false, err
} }

View File

@ -3,10 +3,8 @@ package types
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io"
"github.com/tendermint/go-crypto" "github.com/tendermint/go-crypto"
"github.com/tendermint/go-wire"
cmn "github.com/tendermint/tmlibs/common" cmn "github.com/tendermint/tmlibs/common"
) )
@ -14,9 +12,9 @@ import (
// NOTE: The Accum is not included in Validator.Hash(); // NOTE: The Accum is not included in Validator.Hash();
// make sure to update that method if changes are made here // make sure to update that method if changes are made here
type Validator struct { type Validator struct {
Address Address `json:"address"` Address Address `json:"address"`
PubKey crypto.PubKey `json:"pub_key"` PubKey crypto.PubKey `json:"pub_key"`
VotingPower int64 `json:"voting_power"` VotingPower int64 `json:"voting_power"`
Accum int64 `json:"accum"` Accum int64 `json:"accum"`
} }
@ -72,7 +70,7 @@ func (v *Validator) String() string {
// Hash computes the unique ID of a validator with a given voting power. // Hash computes the unique ID of a validator with a given voting power.
// It excludes the Accum value, which changes with every round. // It excludes the Accum value, which changes with every round.
func (v *Validator) Hash() []byte { func (v *Validator) Hash() []byte {
return wire.BinaryRipemd160(struct { return tmHash(struct {
Address Address Address Address
PubKey crypto.PubKey PubKey crypto.PubKey
VotingPower int64 VotingPower int64
@ -83,25 +81,6 @@ func (v *Validator) Hash() []byte {
}) })
} }
//-------------------------------------
var ValidatorCodec = validatorCodec{}
type validatorCodec struct{}
func (vc validatorCodec) Encode(o interface{}, w io.Writer, n *int, err *error) {
wire.WriteBinary(o.(*Validator), w, n, err)
}
func (vc validatorCodec) Decode(r io.Reader, n *int, err *error) interface{} {
return wire.ReadBinary(&Validator{}, r, 0, n, err)
}
func (vc validatorCodec) Compare(o1 interface{}, o2 interface{}) int {
cmn.PanicSanity("ValidatorCodec.Compare not implemented")
return 0
}
//-------------------------------------------------------------------------------- //--------------------------------------------------------------------------------
// For testing... // For testing...

View File

@ -253,7 +253,7 @@ func (valSet *ValidatorSet) VerifyCommit(chainID string, blockID BlockID, height
} }
_, val := valSet.GetByIndex(idx) _, val := valSet.GetByIndex(idx)
// Validate signature // Validate signature
precommitSignBytes := SignBytes(chainID, precommit) precommitSignBytes := precommit.SignBytes(chainID)
if !val.PubKey.VerifyBytes(precommitSignBytes, precommit.Signature) { if !val.PubKey.VerifyBytes(precommitSignBytes, precommit.Signature) {
return fmt.Errorf("Invalid commit -- invalid signature: %v", precommit) return fmt.Errorf("Invalid commit -- invalid signature: %v", precommit)
} }
@ -327,7 +327,7 @@ func (valSet *ValidatorSet) VerifyCommitAny(newSet *ValidatorSet, chainID string
seen[vi] = true seen[vi] = true
// Validate signature old school // Validate signature old school
precommitSignBytes := SignBytes(chainID, precommit) precommitSignBytes := precommit.SignBytes(chainID)
if !ov.PubKey.VerifyBytes(precommitSignBytes, precommit.Signature) { if !ov.PubKey.VerifyBytes(precommitSignBytes, precommit.Signature) {
return errors.Errorf("Invalid commit -- invalid signature: %v", precommit) return errors.Errorf("Invalid commit -- invalid signature: %v", precommit)
} }

View File

@ -4,7 +4,6 @@ import (
"bytes" "bytes"
"errors" "errors"
"fmt" "fmt"
"io"
"time" "time"
"github.com/tendermint/go-crypto" "github.com/tendermint/go-crypto"
@ -73,11 +72,15 @@ type Vote struct {
Signature crypto.Signature `json:"signature"` Signature crypto.Signature `json:"signature"`
} }
func (vote *Vote) WriteSignBytes(chainID string, w io.Writer, n *int, err *error) { func (vote *Vote) SignBytes(chainID string) []byte {
wire.WriteJSON(CanonicalJSONOnceVote{ bz, err := wire.MarshalJSON(CanonicalJSONOnceVote{
chainID, chainID,
CanonicalVote(vote), CanonicalVote(vote),
}, w, n, err) })
if err != nil {
panic(err)
}
return bz
} }
func (vote *Vote) Copy() *Vote { func (vote *Vote) Copy() *Vote {
@ -111,7 +114,7 @@ func (vote *Vote) Verify(chainID string, pubKey crypto.PubKey) error {
return ErrVoteInvalidValidatorAddress return ErrVoteInvalidValidatorAddress
} }
if !pubKey.VerifyBytes(SignBytes(chainID, vote), vote.Signature) { if !pubKey.VerifyBytes(vote.SignBytes(chainID), vote.Signature) {
return ErrVoteInvalidSignature return ErrVoteInvalidSignature
} }
return nil return nil