func anchorChainToDirBlockInfo(aRecord *anchor.AnchorRecord) (*common.DirBlockInfo, error) { dirBlockInfo := new(common.DirBlockInfo) dirBlockInfo.DBHeight = aRecord.DBHeight dirBlockInfo.BTCTxOffset = aRecord.Bitcoin.Offset dirBlockInfo.BTCBlockHeight = aRecord.Bitcoin.BlockHeight mrBytes, _ := hex.DecodeString(aRecord.KeyMR) dirBlockInfo.DBMerkleRoot, _ = common.NewShaHash(mrBytes) dirBlockInfo.BTCConfirmed = true txSha, _ := wire.NewShaHashFromStr(aRecord.Bitcoin.TXID) dirBlockInfo.BTCTxHash = toHash(txSha) blkSha, _ := wire.NewShaHashFromStr(aRecord.Bitcoin.BlockHash) dirBlockInfo.BTCBlockHash = toHash(blkSha) dblock, err := db.FetchDBlockByHeight(aRecord.DBHeight) if err != nil { fmt.Printf("err in FetchDBlockByHeight: %d\n", aRecord.DBHeight) dirBlockInfo.DBHash = new(common.Hash) } else { dirBlockInfo.Timestamp = int64(dblock.Header.Timestamp * 60) dirBlockInfo.DBHash = dblock.DBHash } fmt.Printf("dirBlockInfo: %s\n", spew.Sdump(dirBlockInfo)) return dirBlockInfo, nil }
func TestFilterInsertUpdateNone(t *testing.T) { f := bloom.NewFilter(10, 0, 0.000001, wire.BloomUpdateNone) // Add the generation pubkey inputStr := "04eaafc2314def4ca98ac970241bcab022b9c1e1f4ea423a20f134c" + "876f2c01ec0f0dd5b2e86e7168cefe0d81113c3807420ce13ad1357231a" + "2252247d97a46a91" inputBytes, err := hex.DecodeString(inputStr) if err != nil { t.Errorf("TestFilterInsertUpdateNone DecodeString failed: %v", err) return } f.Add(inputBytes) // Add the output address for the 4th transaction inputStr = "b6efd80d99179f4f4ff6f4dd0a007d018c385d21" inputBytes, err = hex.DecodeString(inputStr) if err != nil { t.Errorf("TestFilterInsertUpdateNone DecodeString failed: %v", err) return } f.Add(inputBytes) inputStr = "147caa76786596590baa4e98f5d9f48b86c7765e489f7a6ff3360fe5c674360b" sha, err := wire.NewShaHashFromStr(inputStr) if err != nil { t.Errorf("TestFilterInsertUpdateNone NewShaHashFromStr failed: %v", err) return } outpoint := wire.NewOutPoint(sha, 0) if f.MatchesOutPoint(outpoint) { t.Errorf("TestFilterInsertUpdateNone matched outpoint %s", inputStr) return } inputStr = "02981fa052f0481dbc5868f4fc2166035a10f27a03cfd2de67326471df5bc041" sha, err = wire.NewShaHashFromStr(inputStr) if err != nil { t.Errorf("TestFilterInsertUpdateNone NewShaHashFromStr failed: %v", err) return } outpoint = wire.NewOutPoint(sha, 0) if f.MatchesOutPoint(outpoint) { t.Errorf("TestFilterInsertUpdateNone matched outpoint %s", inputStr) return } }
// Execute is the main entry point for the command. It's invoked by the parser. func (cmd *fetchBlockCmd) Execute(args []string) error { // Setup the global config options and ensure they are valid. if err := setupGlobalConfig(); err != nil { return err } if len(args) < 1 { return errors.New("required block hash parameter not specified") } blockHash, err := wire.NewShaHashFromStr(args[0]) if err != nil { return err } // Load the block database. db, err := loadBlockDB() if err != nil { return err } defer db.Close() return db.View(func(tx database.Tx) error { log.Infof("Fetching block %s", blockHash) startTime := time.Now() blockBytes, err := tx.FetchBlock(blockHash) if err != nil { return err } log.Infof("Loaded block in %v", time.Now().Sub(startTime)) log.Infof("Block Hex: %s", hex.EncodeToString(blockBytes)) return nil }) }
// parseChainNtfnParams parses out the block hash and height from the parameters // of blockconnected and blockdisconnected notifications. func parseChainNtfnParams(params []json.RawMessage) (*wire.ShaHash, int32, error) { if len(params) != 2 { return nil, 0, wrongNumParams(len(params)) } // Unmarshal first parameter as a string. var blockShaStr string err := json.Unmarshal(params[0], &blockShaStr) if err != nil { return nil, 0, err } // Unmarshal second parameter as an integer. var blockHeight int32 err = json.Unmarshal(params[1], &blockHeight) if err != nil { return nil, 0, err } // Create ShaHash from block sha string. blockSha, err := wire.NewShaHashFromStr(blockShaStr) if err != nil { return nil, 0, err } return blockSha, blockHeight, nil }
// 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 := btcutil.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) } } }
func handleMain(w http.ResponseWriter, r *http.Request) { sha, err := client.GetBestBlockHash() if err != nil { printErrorPage(w, "Unable to get best blockhash") return } blocks := make([]*btcjson.GetBlockVerboseResult, numMainPageBlocks) blocks[0], err = client.GetBlockVerbose(sha, true) if err != nil { printErrorPage(w, "Error retrieving block") return } for j := 1; j < numMainPageBlocks && blocks[j-1].PreviousHash != ""; j++ { prevsha, _ := wire.NewShaHashFromStr(blocks[j-1].PreviousHash) blocks[j], err = client.GetBlockVerbose(prevsha, true) if err != nil { printErrorPage(w, "Error retrieving block") return } } printHTMLHeader(w, "Welcome") printMainBlock(w, blocks) printHTMLFooter(w) }
// parseRescanProgressParams parses out the height of the last rescanned block // from the parameters of rescanfinished and rescanprogress notifications. func parseRescanProgressParams(params []json.RawMessage) (*wire.ShaHash, int32, time.Time, error) { if len(params) != 3 { return nil, 0, time.Time{}, wrongNumParams(len(params)) } // Unmarshal first parameter as an string. var hashStr string err := json.Unmarshal(params[0], &hashStr) if err != nil { return nil, 0, time.Time{}, err } // Unmarshal second parameter as an integer. var height int32 err = json.Unmarshal(params[1], &height) if err != nil { return nil, 0, time.Time{}, err } // Unmarshal third parameter as an integer. var blkTime int64 err = json.Unmarshal(params[2], &blkTime) if err != nil { return nil, 0, time.Time{}, err } // Decode string encoding of block hash. hash, err := wire.NewShaHashFromStr(hashStr) if err != nil { return nil, 0, time.Time{}, err } return hash, height, time.Unix(blkTime, 0), nil }
// parseTxAcceptedNtfnParams parses out the transaction hash and total amount // from the parameters of a txaccepted notification. func parseTxAcceptedNtfnParams(params []json.RawMessage) (*wire.ShaHash, btcutil.Amount, error) { if len(params) != 2 { return nil, 0, wrongNumParams(len(params)) } // Unmarshal first parameter as a string. var txShaStr string err := json.Unmarshal(params[0], &txShaStr) if err != nil { return nil, 0, err } // Unmarshal second parameter as a floating point number. var famt float64 err = json.Unmarshal(params[1], &famt) if err != nil { return nil, 0, err } // Bounds check amount. amt, err := btcutil.NewAmount(famt) if err != nil { return nil, 0, err } // Decode string encoding of transaction sha. txSha, err := wire.NewShaHashFromStr(txShaStr) if err != nil { return nil, 0, err } return txSha, btcutil.Amount(amt), nil }
// getFundingParams pulls the relevant transaction information from the json returned by blockchain.info // To generate a new valid transaction all of the parameters of the TxOut we are // spending from must be used. func getFundingParams(rawtx *blockChainInfoTx, vout uint32) (*wire.TxOut, *wire.OutPoint) { blkChnTxOut := rawtx.Outputs[vout] hash, err := wire.NewShaHashFromStr(rawtx.Hash) if err != nil { log.Fatal(err) } // Then convert it to a btcutil amount amnt := btcutil.Amount(int64(blkChnTxOut.Value)) if err != nil { log.Fatal(err) } outpoint := wire.NewOutPoint(hash, vout) subscript, err := hex.DecodeString(blkChnTxOut.ScriptHex) if err != nil { log.Fatal(err) } oldTxOut := wire.NewTxOut(int64(amnt), subscript) return oldTxOut, outpoint }
// Receive waits for the response promised by the future and returns the hashes // of all transactions in the memory pool. func (r FutureGetRawMempoolResult) Receive() ([]*wire.ShaHash, error) { res, err := receiveFuture(r) if err != nil { return nil, err } // Unmarshal the result as an array of strings. var txHashStrs []string err = json.Unmarshal(res, &txHashStrs) if err != nil { return nil, err } // Create a slice of ShaHash arrays from the string slice. txHashes := make([]*wire.ShaHash, 0, len(txHashStrs)) for _, hashStr := range txHashStrs { txHash, err := wire.NewShaHashFromStr(hashStr) if err != nil { return nil, err } txHashes = append(txHashes, txHash) } return txHashes, nil }
// Execute is the main entry point for the command. It's invoked by the parser. func (cmd *blockRegionCmd) Execute(args []string) error { // Setup the global config options and ensure they are valid. if err := setupGlobalConfig(); err != nil { return err } // Ensure expected arguments. if len(args) < 1 { return errors.New("required block hash parameter not specified") } if len(args) < 2 { return errors.New("required start offset parameter not " + "specified") } if len(args) < 3 { return errors.New("required region length parameter not " + "specified") } // Parse arguments. blockHash, err := wire.NewShaHashFromStr(args[0]) if err != nil { return err } startOffset, err := strconv.ParseUint(args[1], 10, 32) if err != nil { return err } regionLen, err := strconv.ParseUint(args[2], 10, 32) if err != nil { return err } // Load the block database. db, err := loadBlockDB() if err != nil { return err } defer db.Close() return db.View(func(tx database.Tx) error { log.Infof("Fetching block region %s<%d:%d>", blockHash, startOffset, startOffset+regionLen-1) region := database.BlockRegion{ Hash: blockHash, Offset: uint32(startOffset), Len: uint32(regionLen), } startTime := time.Now() regionBytes, err := tx.FetchBlockRegion(®ion) if err != nil { return err } log.Infof("Loaded block region in %v", time.Now().Sub(startTime)) log.Infof("Double SHA256: %s", wire.DoubleSha256SH(regionBytes)) log.Infof("Region Hex: %s", hex.EncodeToString(regionBytes)) return nil }) }
func TestMerkleBlock3(t *testing.T) { blockStr := "0100000079cda856b143d9db2c1caff01d1aecc8630d30625d10e8b" + "4b8b0000000000000b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdc" + "c96b2c3ff60abe184f196367291b4d4c86041b8fa45d630101000000010" + "00000000000000000000000000000000000000000000000000000000000" + "0000ffffffff08044c86041b020a02ffffffff0100f2052a01000000434" + "104ecd3229b0571c3be876feaac0442a9f13c5a572742927af1dc623353" + "ecf8c202225f64868137a18cdd85cbbb4c74fbccfd4f49639cf1bdc94a5" + "672bb15ad5d4cac00000000" blockBytes, err := hex.DecodeString(blockStr) if err != nil { t.Errorf("TestMerkleBlock3 DecodeString failed: %v", err) return } blk, err := btcutil.NewBlockFromBytes(blockBytes) if err != nil { t.Errorf("TestMerkleBlock3 NewBlockFromBytes failed: %v", err) return } f := bloom.NewFilter(10, 0, 0.000001, wire.BloomUpdateAll) inputStr := "63194f18be0af63f2c6bc9dc0f777cbefed3d9415c4af83f3ee3a3d669c00cb5" sha, err := wire.NewShaHashFromStr(inputStr) if err != nil { t.Errorf("TestMerkleBlock3 NewShaHashFromStr failed: %v", err) return } f.AddShaHash(sha) mBlock, _ := bloom.NewMerkleBlock(blk, f) wantStr := "0100000079cda856b143d9db2c1caff01d1aecc8630d30625d10e8b4" + "b8b0000000000000b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc" + "96b2c3ff60abe184f196367291b4d4c86041b8fa45d630100000001b50c" + "c069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f196" + "30101" want, err := hex.DecodeString(wantStr) if err != nil { t.Errorf("TestMerkleBlock3 DecodeString failed: %v", err) return } got := bytes.NewBuffer(nil) err = mBlock.BtcEncode(got, wire.ProtocolVersion) if err != nil { t.Errorf("TestMerkleBlock3 BtcEncode failed: %v", err) return } if !bytes.Equal(want, got.Bytes()) { t.Errorf("TestMerkleBlock3 failed merkle block comparison: "+ "got %v want %v", got.Bytes, want) return } }
// TestGetHeaders tests the MsgGetHeader API. func TestGetHeaders(t *testing.T) { pver := wire.ProtocolVersion // Block 99500 hash. hashStr := "000000000002e7ad7b9eef9479e4aabc65cb831269cc20d2632c13684406dee0" locatorHash, err := wire.NewShaHashFromStr(hashStr) if err != nil { t.Errorf("NewShaHashFromStr: %v", err) } // Ensure the command is expected value. wantCmd := "getheaders" msg := wire.NewMsgGetHeaders() if cmd := msg.Command(); cmd != wantCmd { t.Errorf("NewMsgGetHeaders: wrong command - got %v want %v", cmd, wantCmd) } // Ensure max payload is expected value for latest protocol version. // Protocol version 4 bytes + num hashes (varInt) + max block locator // hashes + hash stop. wantPayload := uint32(16045) maxPayload := msg.MaxPayloadLength(pver) if maxPayload != wantPayload { t.Errorf("MaxPayloadLength: wrong max payload length for "+ "protocol version %d - got %v, want %v", pver, maxPayload, wantPayload) } // Ensure block locator hashes are added properly. err = msg.AddBlockLocatorHash(locatorHash) if err != nil { t.Errorf("AddBlockLocatorHash: %v", err) } if msg.BlockLocatorHashes[0] != locatorHash { t.Errorf("AddBlockLocatorHash: wrong block locator added - "+ "got %v, want %v", spew.Sprint(msg.BlockLocatorHashes[0]), spew.Sprint(locatorHash)) } // Ensure adding more than the max allowed block locator hashes per // message returns an error. for i := 0; i < wire.MaxBlockLocatorsPerMsg; i++ { err = msg.AddBlockLocatorHash(locatorHash) } if err == nil { t.Errorf("AddBlockLocatorHash: expected error on too many " + "block locator hashes not received") } return }
// TestCalcSignatureHash runs the Bitcoin Core signature hash calculation tests // in sighash.json. // https://github.com/bitcoin/bitcoin/blob/master/src/test/data/sighash.json func TestCalcSignatureHash(t *testing.T) { file, err := ioutil.ReadFile("data/sighash.json") if err != nil { t.Errorf("TestCalcSignatureHash: %v\n", err) return } var tests [][]interface{} err = json.Unmarshal(file, &tests) if err != nil { t.Errorf("TestCalcSignatureHash couldn't Unmarshal: %v\n", err) return } for i, test := range tests { if i == 0 { // Skip first line -- contains comments only. continue } if len(test) != 5 { t.Fatalf("TestCalcSignatureHash: Test #%d has "+ "wrong length.", i) } tx := wire.NewMsgTx() rawTx, _ := hex.DecodeString(test[0].(string)) err := tx.Deserialize(bytes.NewReader(rawTx)) if err != nil { t.Errorf("TestCalcSignatureHash failed test #%d: "+ "Failed to parse transaction: %v", i, err) continue } subScript, _ := hex.DecodeString(test[1].(string)) parsedScript, err := TstParseScript(subScript) if err != nil { t.Errorf("TestCalcSignatureHash failed test #%d: "+ "Failed to parse sub-script: %v", i, err) continue } hashType := SigHashType(testVecF64ToUint32(test[3].(float64))) hash := TstCalcSignatureHash(parsedScript, hashType, tx, int(test[2].(float64))) expectedHash, _ := wire.NewShaHashFromStr(test[4].(string)) if !bytes.Equal(hash, expectedHash.Bytes()) { t.Errorf("TestCalcSignatureHash failed test #%d: "+ "Signature hash mismatch.", i) } } }
func (w *LibbitcoinWallet) gatherCoins() map[coinset.Coin]*bip32.Key { utxos := w.db.Coins().GetAll() m := make(map[coinset.Coin]*bip32.Key) for _, u := range utxos { sha, _ := wire.NewShaHashFromStr(hex.EncodeToString(u.Txid)) c := NewCoin(sha.Bytes(), uint32(u.Index), btc.Amount(int64(u.Value)), 0, u.ScriptPubKey) key, err := w.db.Keys().GetKeyForScript(u.ScriptPubKey) if err != nil { continue } m[c] = key } return m }
// 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 }
// Receive waits for the response promised by the future and returns the hash of // the block in the best block chain at the given height. func (r FutureGetBlockHashResult) Receive() (*wire.ShaHash, error) { res, err := receiveFuture(r) if err != nil { return nil, err } // Unmarshal the result as a string-encoded sha. var txHashStr string err = json.Unmarshal(res, &txHashStr) if err != nil { return nil, err } return wire.NewShaHashFromStr(txHashStr) }
// TestTxSha tests the ability to generate the hash of a transaction accurately. func TestTxSha(t *testing.T) { // Hash of first transaction from block 113875. hashStr := "f051e59b5e2503ac626d03aaeac8ab7be2d72ba4b7e97119c5852d70d52dcb86" wantHash, err := wire.NewShaHashFromStr(hashStr) if err != nil { t.Errorf("NewShaHashFromStr: %v", err) return } // First transaction from block 113875. msgTx := wire.NewMsgTx() txIn := wire.TxIn{ PreviousOutPoint: wire.OutPoint{ Hash: wire.ShaHash{}, Index: 0xffffffff, }, SignatureScript: []byte{0x04, 0x31, 0xdc, 0x00, 0x1b, 0x01, 0x62}, Sequence: 0xffffffff, } txOut := wire.TxOut{ Value: 5000000000, PkScript: []byte{ 0x41, // OP_DATA_65 0x04, 0xd6, 0x4b, 0xdf, 0xd0, 0x9e, 0xb1, 0xc5, 0xfe, 0x29, 0x5a, 0xbd, 0xeb, 0x1d, 0xca, 0x42, 0x81, 0xbe, 0x98, 0x8e, 0x2d, 0xa0, 0xb6, 0xc1, 0xc6, 0xa5, 0x9d, 0xc2, 0x26, 0xc2, 0x86, 0x24, 0xe1, 0x81, 0x75, 0xe8, 0x51, 0xc9, 0x6b, 0x97, 0x3d, 0x81, 0xb0, 0x1c, 0xc3, 0x1f, 0x04, 0x78, 0x34, 0xbc, 0x06, 0xd6, 0xd6, 0xed, 0xf6, 0x20, 0xd1, 0x84, 0x24, 0x1a, 0x6a, 0xed, 0x8b, 0x63, 0xa6, // 65-byte signature 0xac, // OP_CHECKSIG }, } msgTx.AddTxIn(&txIn) msgTx.AddTxOut(&txOut) msgTx.LockTime = 0 // Ensure the hash produced is expected. txHash, err := msgTx.TxSha() if err != nil { t.Errorf("TxSha: %v", err) } if !txHash.IsEqual(wantHash) { t.Errorf("TxSha: wrong hash - got %v, want %v", spew.Sprint(txHash), spew.Sprint(wantHash)) } }
// Receive waits for the response promised by the future and returns the result // of submitting the encoded transaction to the server which then relays it to // the network. func (r FutureSendRawTransactionResult) Receive() (*wire.ShaHash, error) { res, err := receiveFuture(r) if err != nil { return nil, err } // Unmarshal result as a string. var txHashStr string err = json.Unmarshal(res, &txHashStr) if err != nil { return nil, err } return wire.NewShaHashFromStr(txHashStr) }
// 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 btcrpcclient 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 }
// TestBlockTxShas tests the ability to generate a slice of all transaction // hashes from a block accurately. func TestBlockTxShas(t *testing.T) { // Block 1, transaction 1 hash. hashStr := "0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098" wantHash, err := wire.NewShaHashFromStr(hashStr) if err != nil { t.Errorf("NewShaHashFromStr: %v", err) return } wantShas := []wire.ShaHash{*wantHash} shas, err := blockOne.TxShas() if err != nil { t.Errorf("TxShas: %v", err) } if !reflect.DeepEqual(shas, wantShas) { t.Errorf("TxShas: wrong transaction hashes - got %v, want %v", spew.Sdump(shas), spew.Sdump(wantShas)) } }
// getArgs parses command line args and asserts that a private key and an // address are present and correctly formatted. func getArgs() requiredArgs { flag.Parse() if *toaddress == "" || *privkey == "" || *txid == "" || *vout == -1 || *amount == -1 { fmt.Println("\nThis program generates a bitcoin trans action that moves coins from an input to an output.\n" + "You must provide a key, a receiving address, a transaction id (the hash\n" + "of a tx), the amount to be transferred (in satoshis), and the index into\n" + "the outputs of that tx that fund your address. Use http://blockchain.info/pushtx\n" + "to send the raw transaction.\n") flag.PrintDefaults() fmt.Println("") os.Exit(0) } pkBytes, err := hex.DecodeString(*privkey) if err != nil { log.Fatal(err) } // PrivKeyFromBytes returns public key as a separate result, but can ignore it here. key, _ := btcec.PrivKeyFromBytes(btcec.S256(), pkBytes) addr, err := btcutil.DecodeAddress(*toaddress, &chaincfg.MainNetParams) if err != nil { log.Fatal(err) } txid, err := wire.NewShaHashFromStr(*txid) if err != nil { log.Fatal(err) } args := requiredArgs{ txid: txid, vout: uint32(*vout), toAddress: addr, privKey: key, amount: int64(*amount), } return args }
func (r FutureSearchDataTransactionsResult) Receive() ([]*wire.ShaHash, error) { res, err := receiveFuture(r) if err != nil { return nil, err } var hashes []struct { TxHash string } err = json.Unmarshal(res, &hashes) if err != nil { return nil, err } result := make([]*wire.ShaHash, len(hashes)) for i, hash := range hashes { result[i], err = wire.NewShaHashFromStr(hash.TxHash) if err != nil { // TODO do something } } return result, nil }
// Receive waits for the response promised by the future and returns the hash // and height of the block in the longest (best) chain. func (r FutureGetBestBlockResult) Receive() (*wire.ShaHash, int32, error) { res, err := receiveFuture(r) if err != nil { return nil, 0, err } // Unmarsal result as a getbestblock result object. var bestBlock btcjson.GetBestBlockResult err = json.Unmarshal(res, &bestBlock) if err != nil { return nil, 0, err } // Convert hash string. hash, err := wire.NewShaHashFromStr(bestBlock.Hash) if err != nil { return nil, 0, err } return hash, bestBlock.Height, nil }
func handleRawBlock(w http.ResponseWriter, r *http.Request) { block := r.URL.Path[len("/rawblock"):] if len(block) < 2 { printErrorPage(w, "Invalid block hash") return } sha, err := wire.NewShaHashFromStr(block[1:]) if err != nil { printErrorPage(w, "Invalid block hash") return } output, err := client.GetBlock(sha) if err != nil { printErrorPage(w, "Block not found") return } printContentType(w, "text/plain") fmt.Fprintf(w, "%v", spew.Sdump(output)) }
func (db *LevelDb) getBlkLoc(sha *wire.ShaHash) (int32, error) { key := shaBlkToKey(sha) checkpointSha, _ := wire.NewShaHashFromStr("00000000000000000a8dc6ed5b133d0eb2fd6af56203e4159789b092defd8ab2") if sha.IsEqual(checkpointSha) { return 382320, nil } data, err := db.lDb.Get(key, db.ro) if err != nil { if err == leveldb.ErrNotFound { err = database.ErrBlockShaMissing } return 0, err } // deserialize blkHeight := binary.LittleEndian.Uint64(data) return int32(blkHeight), nil }
// parseChainNtfnParams parses out the block hash and height from the parameters // of blockconnected and blockdisconnected notifications. func parseChainNtfnParams(params []json.RawMessage) (*wire.ShaHash, int32, time.Time, error) { if len(params) != 3 { return nil, 0, time.Time{}, wrongNumParams(len(params)) } // Unmarshal first parameter as a string. var blockShaStr string err := json.Unmarshal(params[0], &blockShaStr) if err != nil { return nil, 0, time.Time{}, err } // Unmarshal second parameter as an integer. var blockHeight int32 err = json.Unmarshal(params[1], &blockHeight) if err != nil { return nil, 0, time.Time{}, err } // Unmarshal third parameter as unix time. var blockTimeUnix int64 err = json.Unmarshal(params[2], &blockTimeUnix) if err != nil { return nil, 0, time.Time{}, err } // Create ShaHash from block sha string. blockSha, err := wire.NewShaHashFromStr(blockShaStr) if err != nil { return nil, 0, time.Time{}, err } // Create time.Time from unix time. blockTime := time.Unix(blockTimeUnix, 0) return blockSha, blockHeight, blockTime, nil }
func handleRawTx(w http.ResponseWriter, r *http.Request) { tx := r.URL.Path[len("/rawtx"):] if len(tx) < 2 { printErrorPage(w, "Invalid transaction sha") return } sha, err := wire.NewShaHashFromStr(tx[1:]) if err != nil { printErrorPage(w, "Invalid transaction sha") return } output, err := client.GetRawTransactionVerbose(sha) if err != nil { printErrorPage(w, "Transaction not found") return } printContentType(w, "text/plain") fmt.Fprintf(w, "%v", spew.Sdump(output)) }