From a9e05a3030afe9c2e4e5e63250d6c190215aa08e Mon Sep 17 00:00:00 2001 From: Josh Rickmar Date: Mon, 5 Jan 2015 16:40:43 -0500 Subject: [PATCH] Implement String for OutPoint. --- msgtx.go | 16 ++++++++++++++++ msgtx_test.go | 8 ++++++++ 2 files changed, 24 insertions(+) diff --git a/msgtx.go b/msgtx.go index d1aed731..c01ba275 100644 --- a/msgtx.go +++ b/msgtx.go @@ -9,6 +9,7 @@ import ( "encoding/binary" "fmt" "io" + "strconv" ) const ( @@ -75,6 +76,21 @@ func NewOutPoint(hash *ShaHash, index uint32) *OutPoint { } } +// String returns the OutPoint in the human-readable form "hash:index". +func (o OutPoint) String() string { + // Allocate enough for hash string, colon, and 10 digits. Although + // at the time of writing, the number of digits can be no greater than + // the length of the decimal representation of maxTxOutPerMessage, the + // maximum message payload may increase in the future and this + // optimization may go unnoticed, so allocate space for 10 decimal + // digits, which will fit any uint32. + buf := make([]byte, 2*HashSize+1, 2*HashSize+1+10) + copy(buf, o.Hash.String()) + buf[2*HashSize] = ':' + buf = strconv.AppendUint(buf, uint64(o.Index), 10) + return string(buf) +} + // TxIn defines a bitcoin transaction input. type TxIn struct { PreviousOutPoint OutPoint diff --git a/msgtx_test.go b/msgtx_test.go index bfaf650e..36c715a4 100644 --- a/msgtx_test.go +++ b/msgtx_test.go @@ -6,6 +6,7 @@ package btcwire_test import ( "bytes" + "fmt" "io" "reflect" "testing" @@ -44,6 +45,8 @@ func TestTx(t *testing.T) { } // Ensure we get the same transaction output point data back out. + // NOTE: This is a block hash and made up index, but we're only + // testing package functionality. prevOutIndex := uint32(1) prevOut := btcwire.NewOutPoint(hash, prevOutIndex) if !prevOut.Hash.IsEqual(hash) { @@ -54,6 +57,11 @@ func TestTx(t *testing.T) { t.Errorf("NewOutPoint: wrong index - got %v, want %v", prevOut.Index, prevOutIndex) } + prevOutStr := fmt.Sprintf("%s:%d", hash.String(), prevOutIndex) + if s := prevOut.String(); s != prevOutStr { + t.Errorf("OutPoint.String: unexpected result - got %v, "+ + "want %v", s, prevOutStr) + } // Ensure we get the same transaction input back out. sigScript := []byte{0x04, 0x31, 0xdc, 0x00, 0x1b, 0x01, 0x62}