// This example demonstrates how to create a new bloom filter, add a transaction
// hash to it, and check if the filter matches the transaction.
func ExampleNewFilter() {
rand.Seed(time.Now().UnixNano())
tweak := rand.Uint32()
// Create a new bloom filter intended to hold 10 elements with a 0.01%
// false positive rate and does not include any automatic update
// functionality when transactions are matched.
filter := bloom.NewFilter(10, tweak, 0.0001, wire.BloomUpdateNone)
// Create a transaction hash and add it to the filter. This particular
// trasaction is the first transaction in block 310,000 of the main
// bitcoin block chain.
txHashStr := "fd611c56ca0d378cdcd16244b45c2ba9588da3adac367c4ef43e808b280b8a45"
txHash, err := wire.NewShaHashFromStr(txHashStr)
if err != nil {
fmt.Println(err)
return
}
filter.AddShaHash(txHash)
// Show that the filter matches.
matches := filter.Matches(txHash.Bytes())
fmt.Println("Filter Matches?:", matches)
// Output:
// Filter Matches?: true
}
// TestTx tests the API for Tx.
func TestTx(t *testing.T) {
testTx := Block100000.Transactions[0]
tx := coinutil.NewTx(testTx)
// Ensure we get the same data back out.
if msgTx := tx.MsgTx(); !reflect.DeepEqual(msgTx, testTx) {
t.Errorf("MsgTx: mismatched MsgTx - got %v, want %v",
spew.Sdump(msgTx), spew.Sdump(testTx))
}
// Ensure transaction index set and get work properly.
wantIndex := 0
tx.SetIndex(0)
if gotIndex := tx.Index(); gotIndex != wantIndex {
t.Errorf("Index: mismatched index - got %v, want %v",
gotIndex, wantIndex)
}
// Hash for block 100,000 transaction 0.
wantShaStr := "8c14f0db3df150123e6f3dbbf30f8b955a8249b62ac1d1ff16284aefa3d06d87"
wantSha, err := wire.NewShaHashFromStr(wantShaStr)
if err != nil {
t.Errorf("NewShaHashFromStr: %v", err)
}
// Request the sha multiple times to test generation and caching.
for i := 0; i < 2; i++ {
sha := tx.Sha()
if !sha.IsEqual(wantSha) {
t.Errorf("Sha #%d mismatched sha - got %v, want %v", i,
sha, wantSha)
}
}
}
// newShaHashFromStr converts the passed big-endian hex string into a
// wire.ShaHash. It only differs from the one available in wire in that
// it panics on an error since it will only (and must only) be called with
// hard-coded, and therefore known good, hashes.
func newShaHashFromStr(hexStr string) *wire.ShaHash {
sha, err := wire.NewShaHashFromStr(hexStr)
if err != nil {
// Ordinarily I don't like panics in library code since it
// can take applications down without them having a chance to
// recover which is extremely annoying, however an exception is
// being made in this case because the only way this can panic
// is if there is an error in the hard-coded hashes. Thus it
// will only ever potentially panic on init and therefore is
// 100% predictable.
panic(err)
}
return sha
}
开发者ID:conseweb,项目名称:stcd,代码行数:18,代码来源:params.go
示例7: TestBlockSha
// TestBlockSha tests the ability to generate the hash of a block accurately.
func TestBlockSha(t *testing.T) {
// Block 1 hash.
hashStr := "839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048"
wantHash, err := wire.NewShaHashFromStr(hashStr)
if err != nil {
t.Errorf("NewShaHashFromStr: %v", err)
}
// Ensure the hash produced is expected.
blockHash := blockOne.BlockSha()
if !blockHash.IsEqual(wantHash) {
t.Errorf("BlockSha: wrong hash - got %v, want %v",
spew.Sprint(blockHash), spew.Sprint(wantHash))
}
}
// parseBlock parses a btcws definition of the block a tx is mined it to the
// Block structure of the wtxmgr package, and the block index. This is done
// here since stcrpcclient doesn't parse this nicely for us.
func parseBlock(block *btcjson.BlockDetails) (*wtxmgr.BlockMeta, error) {
if block == nil {
return nil, nil
}
blksha, err := wire.NewShaHashFromStr(block.Hash)
if err != nil {
return nil, err
}
blk := &wtxmgr.BlockMeta{
Block: wtxmgr.Block{
Height: block.Height,
Hash: *blksha,
},
Time: time.Unix(block.Time, 0),
}
return blk, nil
}
// TestHaveBlock tests the HaveBlock API to ensure proper functionality.
func TestHaveBlock(t *testing.T) {
// Load up blocks such that there is a side chain.
// (genesis block) -> 1 -> 2 -> 3 -> 4
// \-> 3a
testFiles := []string{
"blk_0_to_4.dat.bz2",
"blk_3A.dat.bz2",
}
var blocks []*coinutil.Block
for _, file := range testFiles {
blockTmp, err := loadBlocks(file)
if err != nil {
t.Errorf("Error loading file: %v\n", err)
return
}
for _, block := range blockTmp {
blocks = append(blocks, block)
}
}
// Create a new database and chain instance to run tests against.
chain, teardownFunc, err := chainSetup("haveblock")
if err != nil {
t.Errorf("Failed to setup chain instance: %v", err)
return
}
defer teardownFunc()
// Since we're not dealing with the real block chain, disable
// checkpoints and set the coinbase maturity to 1.
chain.DisableCheckpoints(true)
blockchain.TstSetCoinbaseMaturity(1)
timeSource := blockchain.NewMedianTime()
for i := 1; i < len(blocks); i++ {
isOrphan, err := chain.ProcessBlock(blocks[i], timeSource,
blockchain.BFNone)
if err != nil {
t.Errorf("ProcessBlock fail on block %v: %v\n", i, err)
return
}
if isOrphan {
t.Errorf("ProcessBlock incorrectly returned block %v "+
"is an orphan\n", i)
return
}
}
// Insert an orphan block.
isOrphan, err := chain.ProcessBlock(coinutil.NewBlock(&Block100000),
timeSource, blockchain.BFNone)
if err != nil {
t.Errorf("Unable to process block: %v", err)
return
}
if !isOrphan {
t.Errorf("ProcessBlock indicated block is an not orphan when " +
"it should be\n")
return
}
tests := []struct {
hash string
want bool
}{
// Genesis block should be present (in the main chain).
{hash: chaincfg.MainNetParams.GenesisHash.String(), want: true},
// Block 3a should be present (on a side chain).
{hash: "00000000474284d20067a4d33f6a02284e6ef70764a3a26d6a5b9df52ef663dd", want: true},
// Block 100000 should be present (as an orphan).
{hash: "000000000003ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506", want: true},
// Random hashes should not be availble.
{hash: "123", want: false},
}
for i, test := range tests {
hash, err := wire.NewShaHashFromStr(test.hash)
if err != nil {
t.Errorf("NewShaHashFromStr: %v", err)
continue
}
result, err := chain.HaveBlock(hash)
if err != nil {
t.Errorf("HaveBlock #%d unexpected error: %v", i, err)
return
}
if result != test.want {
t.Errorf("HaveBlock #%d got %v want %v", i, result,
test.want)
continue
}
}
}
// newShaHashFromStr converts the passed big-endian hex string into a
// wire.ShaHash. It only differs from the one available in wire in that it
// ignores the error since it will only (and must only) be called with
// hard-coded, and therefore known good, hashes.
func newShaHashFromStr(hexStr string) *wire.ShaHash {
sha, _ := wire.NewShaHashFromStr(hexStr)
return sha
}
开发者ID:conseweb,项目名称:stcd,代码行数:8,代码来源:memdb.go
示例14: TestNewShaHashFromStr
// TestNewShaHashFromStr executes tests against the NewShaHashFromStr function.
func TestNewShaHashFromStr(t *testing.T) {
tests := []struct {
in string
want wire.ShaHash
err error
}{
// Genesis hash.
{
"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",
mainNetGenesisHash,
nil,
},
// Genesis hash with stripped leading zeros.
{
"19d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",
mainNetGenesisHash,
nil,
},
// Empty string.
{
"",
wire.ShaHash{},
nil,
},
// Single digit hash.
{
"1",
wire.ShaHash([wire.HashSize]byte{ // Make go vet happy.
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
}),
nil,
},
// Block 203707 with stripped leading zeros.
{
"3264bc2ac36a60840790ba1d475d01367e7c723da941069e9dc",
wire.ShaHash([wire.HashSize]byte{ // Make go vet happy.
0xdc, 0xe9, 0x69, 0x10, 0x94, 0xda, 0x23, 0xc7,
0xe7, 0x67, 0x13, 0xd0, 0x75, 0xd4, 0xa1, 0x0b,
0x79, 0x40, 0x08, 0xa6, 0x36, 0xac, 0xc2, 0x4b,
0x26, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
}),
nil,
},
// Hash string that is too long.
{
"01234567890123456789012345678901234567890123456789012345678912345",
wire.ShaHash{},
wire.ErrHashStrSize,
},
// Hash string that is contains non-hex chars.
{
"abcdefg",
wire.ShaHash{},
hex.InvalidByteError('g'),
},
}
unexpectedErrStr := "NewShaHashFromStr #%d failed to detect expected error - got: %v want: %v"
unexpectedResultStr := "NewShaHashFromStr #%d got: %v want: %v"
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
result, err := wire.NewShaHashFromStr(test.in)
if err != test.err {
t.Errorf(unexpectedErrStr, i, err, test.err)
continue
} else if err != nil {
// Got expected error. Move on to the next test.
continue
}
if !test.want.IsEqual(result) {
t.Errorf(unexpectedResultStr, i, result, &test.want)
continue
}
}
}
// TestTxValidTests ensures all of the tests in tx_valid.json pass as expected.
func TestTxValidTests(t *testing.T) {
file, err := ioutil.ReadFile("data/tx_valid.json")
if err != nil {
t.Errorf("TestBitcoindInvalidTests: %v\n", err)
return
}
var tests [][]interface{}
err = json.Unmarshal(file, &tests)
if err != nil {
t.Errorf("TestBitcoindInvalidTests couldn't Unmarshal: %v\n",
err)
return
}
// form is either:
// ["this is a comment "]
// or:
// [[[previous hash, previous index, previous scriptPubKey]...,]
// serializedTransaction, verifyFlags]
testloop:
for i, test := range tests {
inputs, ok := test[0].([]interface{})
if !ok {
continue
}
if len(test) != 3 {
t.Errorf("bad test (bad length) %d: %v", i, test)
continue
}
serializedhex, ok := test[1].(string)
if !ok {
t.Errorf("bad test (arg 2 not string) %d: %v", i, test)
continue
}
serializedTx, err := hex.DecodeString(serializedhex)
if err != nil {
t.Errorf("bad test (arg 2 not hex %v) %d: %v", err, i,
test)
continue
}
tx, err := coinutil.NewTxFromBytes(serializedTx)
if err != nil {
t.Errorf("bad test (arg 2 not msgtx %v) %d: %v", err,
i, test)
continue
}
verifyFlags, ok := test[2].(string)
if !ok {
t.Errorf("bad test (arg 3 not string) %d: %v", i, test)
continue
}
flags, err := parseScriptFlags(verifyFlags)
if err != nil {
t.Errorf("bad test %d: %v", i, err)
continue
}
prevOuts := make(map[wire.OutPoint][]byte)
for j, iinput := range inputs {
input, ok := iinput.([]interface{})
if !ok {
t.Errorf("bad test (%dth input not array)"+
"%d: %v", j, i, test)
continue
}
if len(input) != 3 {
t.Errorf("bad test (%dth input wrong length)"+
"%d: %v", j, i, test)
continue
}
previoustx, ok := input[0].(string)
if !ok {
t.Errorf("bad test (%dth input sha not string)"+
"%d: %v", j, i, test)
continue
}
prevhash, err := wire.NewShaHashFromStr(previoustx)
if err != nil {
t.Errorf("bad test (%dth input sha not sha %v)"+
"%d: %v", j, err, i, test)
continue
}
idxf, ok := input[1].(float64)
if !ok {
t.Errorf("bad test (%dth input idx not number)"+
"%d: %v", j, i, test)
continue
}
idx := uint32(idxf) // (floor(idxf) == idxf?)
//.........这里部分代码省略.........
请发表评论