本文整理匯總了Golang中github.com/decred/dcrutil.DecodeAddress函數的典型用法代碼示例。如果您正苦於以下問題:Golang DecodeAddress函數的具體用法?Golang DecodeAddress怎麽用?Golang DecodeAddress使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了DecodeAddress函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: ExamplePayToAddrScript
// This example demonstrates creating a script which pays to a decred address.
// It also prints the created script hex and uses the DisasmString function to
// display the disassembled script.
func ExamplePayToAddrScript() {
// Parse the address to send the coins to into a dcrutil.Address
// which is useful to ensure the accuracy of the address and determine
// the address type. It is also required for the upcoming call to
// PayToAddrScript.
addressStr := "DsSej1qR3Fyc8kV176DCh9n9cY9nqf9Quxk"
address, err := dcrutil.DecodeAddress(addressStr, &chaincfg.MainNetParams)
if err != nil {
fmt.Println(err)
return
}
// Create a public key script that pays to the address.
script, err := txscript.PayToAddrScript(address)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Script Hex: %x\n", script)
disasm, err := txscript.DisasmString(script)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Script Disassembly:", disasm)
// Output:
// Script Hex: 76a914128004ff2fcaf13b2b91eb654b1dc2b674f7ec6188ac
// Script Disassembly: OP_DUP OP_HASH160 128004ff2fcaf13b2b91eb654b1dc2b674f7ec61 OP_EQUALVERIFY OP_CHECKSIG
}
示例2: getNewAddress
// GetNewAddress must be run as many times as necessary with the address pool
// mutex locked. Each time, it returns a single new address while adding that
// address to the toDelete map. If the address pool runs out of addresses, it
// generates more from the address manager.
//
// This function MUST be called with the address pool mutex held and batch
// finish or rollback must be called after.
func (a *addressPool) getNewAddress(waddrmgrNs walletdb.ReadWriteBucket) (dcrutil.Address, error) {
if !a.started {
return nil, fmt.Errorf("failed to getNewAddress; pool not started")
}
chainClient, err := a.wallet.requireChainClient()
if err != nil {
return nil, err
}
// Replenish the pool if we're at the last address.
if a.cursor == len(a.addresses)-1 || len(a.addresses) == 0 {
var nextAddrFunc func(walletdb.ReadWriteBucket, uint32, uint32) ([]waddrmgr.ManagedAddress, error)
switch a.branch {
case waddrmgr.InternalBranch:
nextAddrFunc = a.wallet.Manager.NextInternalAddresses
case waddrmgr.ExternalBranch:
nextAddrFunc = a.wallet.Manager.NextExternalAddresses
default:
return nil, fmt.Errorf("unknown default account branch %v", a.branch)
}
addrs, err := nextAddrFunc(waddrmgrNs, a.account, addressPoolBuffer)
if err != nil {
return nil, err
}
for _, addr := range addrs {
a.addresses = append(a.addresses, addr.Address().EncodeAddress())
}
}
// As these are all encoded addresses, we should never throw an error
// converting back.
curAddressStr := a.addresses[a.cursor]
curAddress, err := dcrutil.DecodeAddress(curAddressStr, a.wallet.chainParams)
if err != nil {
return nil, fmt.Errorf("unexpected error decoding address %s: %s",
curAddressStr, err.Error())
}
log.Debugf("Get new address for branch %v returned %s (idx %v) from "+
"the address pool", a.branch, curAddressStr, a.index)
// Add the address to the notifications watcher.
addrs := []dcrutil.Address{curAddress}
err = chainClient.LoadTxFilter(false, addrs, nil)
if err != nil {
return nil, err
}
a.cursor++
a.index++
return curAddress, nil
}
示例3: TestSignMultiSigUTXOPkScriptNotP2SH
func TestSignMultiSigUTXOPkScriptNotP2SH(t *testing.T) {
tearDown, pool, _ := TstCreatePoolAndTxStore(t)
defer tearDown()
mgr := pool.Manager()
tx := createWithdrawalTx(t, pool, []int64{4e6}, []int64{})
addr, _ := dcrutil.DecodeAddress("1MirQ9bwyQcGVJPwKUgapu5ouK2E2Ey4gX", mgr.ChainParams())
pubKeyHashPkScript, _ := txscript.PayToAddrScript(addr.(*dcrutil.AddressPubKeyHash))
msgtx := tx.toMsgTx()
err := signMultiSigUTXO(mgr, msgtx, 0, pubKeyHashPkScript, []RawSig{RawSig{}})
TstCheckError(t, "", err, ErrTxSigning)
}
示例4: GetNewAddress
// GetNewAddress must be run as many times as necessary with the address pool
// mutex locked. Each time, it returns a single new address while adding that
// address to the toDelete map. If the address pool runs out of addresses, it
// generates more from the address manager.
func (a *addressPool) GetNewAddress() (dcrutil.Address, error) {
// Replenish the pool if we're at the last address.
if a.cursor == len(a.addresses)-1 || len(a.addresses) == 0 {
if a.branch == waddrmgr.InternalBranch {
addrs, err :=
a.wallet.Manager.NextInternalAddresses(
waddrmgr.DefaultAccountNum, addressPoolBuffer)
if err != nil {
return nil, err
}
for _, addr := range addrs {
a.addresses = append(a.addresses, addr.Address().EncodeAddress())
}
}
if a.branch == waddrmgr.ExternalBranch {
addrs, err :=
a.wallet.Manager.NextExternalAddresses(
waddrmgr.DefaultAccountNum, addressPoolBuffer)
if err != nil {
return nil, err
}
for _, addr := range addrs {
a.addresses = append(a.addresses, addr.Address().EncodeAddress())
}
}
}
// As these are all encoded addresses, we should never throw an error
// converting back.
curAddressStr := a.addresses[a.cursor]
curAddress, _ := dcrutil.DecodeAddress(curAddressStr, a.wallet.chainParams)
a.cursor++
// Add the address to the notifications watcher.
addrs := make([]dcrutil.Address, 1)
addrs[0] = curAddress
if err := a.wallet.chainSvr.NotifyReceived(addrs); err != nil {
return nil, err
}
return curAddress, nil
}
示例5: TstNewOutputRequest
func TstNewOutputRequest(t *testing.T, transaction uint32, address string, amount dcrutil.Amount,
net *chaincfg.Params) OutputRequest {
addr, err := dcrutil.DecodeAddress(address, net)
if err != nil {
t.Fatalf("Unable to decode address %s", address)
}
pkScript, err := txscript.PayToAddrScript(addr)
if err != nil {
t.Fatalf("Unable to generate pkScript for %v", addr)
}
return OutputRequest{
PkScript: pkScript,
Address: addr,
Amount: amount,
Server: "server",
Transaction: transaction,
}
}
示例6: TestSignMultiSigUTXORedeemScriptNotFound
func TestSignMultiSigUTXORedeemScriptNotFound(t *testing.T) {
tearDown, pool, _ := TstCreatePoolAndTxStore(t)
defer tearDown()
mgr := pool.Manager()
tx := createWithdrawalTx(t, pool, []int64{4e6}, []int64{})
// This is a P2SH address for which the addr manager doesn't have the redeem
// script.
addr, _ := dcrutil.DecodeAddress("3Hb4xcebcKg4DiETJfwjh8sF4uDw9rqtVC", mgr.ChainParams())
if _, err := mgr.Address(addr); err == nil {
t.Fatalf("Address %s found in manager when it shouldn't", addr)
}
msgtx := tx.toMsgTx()
pkScript, _ := txscript.PayToAddrScript(addr.(*dcrutil.AddressScriptHash))
err := signMultiSigUTXO(mgr, msgtx, 0, pkScript, []RawSig{RawSig{}})
TstCheckError(t, "", err, ErrTxSigning)
}
示例7: checkOutputsMatch
// checkOutputsMatch checks that the outputs in the tx match the expected ones.
func checkOutputsMatch(t *testing.T, msgtx *wire.MsgTx, expected map[string]dcrutil.Amount) {
// This is a bit convoluted because the index of the change output is randomized.
for addrStr, v := range expected {
addr, err := dcrutil.DecodeAddress(addrStr, &chaincfg.TestNetParams)
if err != nil {
t.Fatalf("Cannot decode address: %v", err)
}
pkScript, err := txscript.PayToAddrScript(addr)
if err != nil {
t.Fatalf("Cannot create pkScript: %v", err)
}
found := false
for _, txout := range msgtx.TxOut {
if reflect.DeepEqual(txout.PkScript, pkScript) && txout.Value == int64(v) {
found = true
break
}
}
if !found {
t.Fatalf("PkScript %v not found in msgtx.TxOut: %v", pkScript, msgtx.TxOut)
}
}
}
示例8: CoinbasePaysTax
// CoinbasePaysTax checks to see if a given block's coinbase correctly pays
// tax to the developer organization.
func CoinbasePaysTax(tx *dcrutil.Tx, height uint32, voters uint16,
params *chaincfg.Params) error {
// Taxes only apply from block 2 onwards.
if height <= 1 {
return nil
}
// Tax is disabled.
if params.BlockTaxProportion == 0 {
return nil
}
if len(tx.MsgTx().TxOut) == 0 {
errStr := fmt.Sprintf("invalid coinbase (no outputs)")
return ruleError(ErrNoTxOutputs, errStr)
}
// Coinbase output 0 must be the subsidy to the dev organization.
taxPkVersion := tx.MsgTx().TxOut[0].Version
taxPkScript := tx.MsgTx().TxOut[0].PkScript
class, addrs, _, err :=
txscript.ExtractPkScriptAddrs(taxPkVersion, taxPkScript, params)
// The script can't be a weird class.
if !(class == txscript.ScriptHashTy ||
class == txscript.PubKeyHashTy ||
class == txscript.PubKeyTy) {
errStr := fmt.Sprintf("wrong script class for tax output")
return ruleError(ErrNoTax, errStr)
}
// There should only be one address.
if len(addrs) != 1 {
errStr := fmt.Sprintf("no or too many addresses in output")
return ruleError(ErrNoTax, errStr)
}
// Decode the organization address.
addrOrg, err := dcrutil.DecodeAddress(params.OrganizationAddress, params)
if err != nil {
return err
}
if !bytes.Equal(addrs[0].ScriptAddress(), addrOrg.ScriptAddress()) {
errStr := fmt.Sprintf("address in output 0 has non matching org "+
"address; got %v (hash160 %x), want %v (hash160 %x)",
addrs[0].EncodeAddress(),
addrs[0].ScriptAddress(),
addrOrg.EncodeAddress(),
addrOrg.ScriptAddress())
return ruleError(ErrNoTax, errStr)
}
// Get the amount of subsidy that should have been paid out to
// the organization, then check it.
orgSubsidy := CalcBlockTaxSubsidy(int64(height), voters, params)
amountFound := tx.MsgTx().TxOut[0].Value
if orgSubsidy != amountFound {
errStr := fmt.Sprintf("amount in output 0 has non matching org "+
"calculated amount; got %v, want %v", amountFound, orgSubsidy)
return ruleError(ErrNoTax, errStr)
}
return nil
}
示例9: BlockOneCoinbasePaysTokens
// BlockOneCoinbasePaysTokens checks to see if the first block coinbase pays
// out to the network initial token ledger.
func BlockOneCoinbasePaysTokens(tx *dcrutil.Tx, params *chaincfg.Params) error {
// If no ledger is specified, just return true.
if len(params.BlockOneLedger) == 0 {
return nil
}
if tx.MsgTx().LockTime != 0 {
errStr := fmt.Sprintf("block 1 coinbase has invalid locktime")
return ruleError(ErrBlockOneTx, errStr)
}
if tx.MsgTx().Expiry != wire.NoExpiryValue {
errStr := fmt.Sprintf("block 1 coinbase has invalid expiry")
return ruleError(ErrBlockOneTx, errStr)
}
if tx.MsgTx().TxIn[0].Sequence != wire.MaxTxInSequenceNum {
errStr := fmt.Sprintf("block 1 coinbase not finalized")
return ruleError(ErrBlockOneInputs, errStr)
}
if len(tx.MsgTx().TxOut) == 0 {
errStr := fmt.Sprintf("coinbase outputs empty in block 1")
return ruleError(ErrBlockOneOutputs, errStr)
}
ledger := params.BlockOneLedger
if len(ledger) != len(tx.MsgTx().TxOut) {
errStr := fmt.Sprintf("wrong number of outputs in block 1 coinbase; "+
"got %v, expected %v", len(tx.MsgTx().TxOut), len(ledger))
return ruleError(ErrBlockOneOutputs, errStr)
}
// Check the addresses and output amounts against those in the ledger.
for i, txout := range tx.MsgTx().TxOut {
if txout.Version != txscript.DefaultScriptVersion {
errStr := fmt.Sprintf("bad block one output version; want %v, got %v",
txscript.DefaultScriptVersion, txout.Version)
return ruleError(ErrBlockOneOutputs, errStr)
}
// There should only be one address.
_, addrs, _, err :=
txscript.ExtractPkScriptAddrs(txout.Version, txout.PkScript, params)
if len(addrs) != 1 {
errStr := fmt.Sprintf("too many addresses in output")
return ruleError(ErrBlockOneOutputs, errStr)
}
addrLedger, err := dcrutil.DecodeAddress(ledger[i].Address, params)
if err != nil {
return err
}
if !bytes.Equal(addrs[0].ScriptAddress(), addrLedger.ScriptAddress()) {
errStr := fmt.Sprintf("address in output %v has non matching "+
"address; got %v (hash160 %x), want %v (hash160 %x)",
i,
addrs[0].EncodeAddress(),
addrs[0].ScriptAddress(),
addrLedger.EncodeAddress(),
addrLedger.ScriptAddress())
return ruleError(ErrBlockOneOutputs, errStr)
}
if txout.Value != ledger[i].Amount {
errStr := fmt.Sprintf("address in output %v has non matching "+
"amount; got %v, want %v", i, txout.Value, ledger[i].Amount)
return ruleError(ErrBlockOneOutputs, errStr)
}
}
return nil
}
示例10: TestAddresses
//.........這裏部分代碼省略.........
{
name: "testnet p2pk hybrid (0x07)",
addr: "07b0bd634234abbb1ba1e986e884185c61cf43e001f9137f23c2c409273eb16e6" +
"537a576782eba668a7ef8bd3b3cfb1edb7117ab65129b8a2e681f3c1e0908ef7b",
encoded: "muUnepk5nPPrxUTuTAhRqrpAQuSWS5fVii",
valid: true,
result: dcrutil.TstAddressPubKey(
[]byte{
0x07, 0xb0, 0xbd, 0x63, 0x42, 0x34, 0xab, 0xbb, 0x1b, 0xa1,
0xe9, 0x86, 0xe8, 0x84, 0x18, 0x5c, 0x61, 0xcf, 0x43, 0xe0,
0x01, 0xf9, 0x13, 0x7f, 0x23, 0xc2, 0xc4, 0x09, 0x27, 0x3e,
0xb1, 0x6e, 0x65, 0x37, 0xa5, 0x76, 0x78, 0x2e, 0xba, 0x66,
0x8a, 0x7e, 0xf8, 0xbd, 0x3b, 0x3c, 0xfb, 0x1e, 0xdb, 0x71,
0x17, 0xab, 0x65, 0x12, 0x9b, 0x8a, 0x2e, 0x68, 0x1f, 0x3c,
0x1e, 0x09, 0x08, 0xef, 0x7b},
dcrutil.PKFHybrid, chaincfg.TestNetParams.PubKeyHashAddrID),
f: func() (dcrutil.Address, error) {
serializedPubKey := []byte{
0x07, 0xb0, 0xbd, 0x63, 0x42, 0x34, 0xab, 0xbb, 0x1b, 0xa1,
0xe9, 0x86, 0xe8, 0x84, 0x18, 0x5c, 0x61, 0xcf, 0x43, 0xe0,
0x01, 0xf9, 0x13, 0x7f, 0x23, 0xc2, 0xc4, 0x09, 0x27, 0x3e,
0xb1, 0x6e, 0x65, 0x37, 0xa5, 0x76, 0x78, 0x2e, 0xba, 0x66,
0x8a, 0x7e, 0xf8, 0xbd, 0x3b, 0x3c, 0xfb, 0x1e, 0xdb, 0x71,
0x17, 0xab, 0x65, 0x12, 0x9b, 0x8a, 0x2e, 0x68, 0x1f, 0x3c,
0x1e, 0x09, 0x08, 0xef, 0x7b}
return dcrutil.NewAddressSecpPubKey(serializedPubKey, &chaincfg.TestNetParams)
},
net: &chaincfg.TestNetParams,
},
}
for _, test := range tests {
// Decode addr and compare error against valid.
decoded, err := dcrutil.DecodeAddress(test.addr, test.net)
if (err == nil) != test.valid {
t.Errorf("%v: decoding test failed: %v", test.name, err)
return
}
if err == nil {
// Ensure the stringer returns the same address as the
// original.
if decodedStringer, ok := decoded.(fmt.Stringer); ok {
if test.addr != decodedStringer.String() {
t.Errorf("%v: String on decoded value does not match expected value: %v != %v",
test.name, test.addr, decodedStringer.String())
return
}
}
// Encode again and compare against the original.
encoded := decoded.EncodeAddress()
if test.encoded != encoded {
t.Errorf("%v: decoding and encoding produced different addressess: %v != %v",
test.name, test.encoded, encoded)
return
}
// Perform type-specific calculations.
var saddr []byte
switch d := decoded.(type) {
case *dcrutil.AddressPubKeyHash:
saddr = dcrutil.TstAddressSAddr(encoded)
case *dcrutil.AddressScriptHash:
saddr = dcrutil.TstAddressSAddr(encoded)
示例11: Example_startWithdrawal
// This example demonstrates how to use the Pool.StartWithdrawal method.
func Example_startWithdrawal() {
// Create the address manager and votingpool DB namespace. See the example
// for the Create() function for more info on how this is done.
mgr, vpNamespace, tearDownFunc, err := exampleCreateMgrAndDBNamespace()
if err != nil {
fmt.Println(err)
return
}
defer tearDownFunc()
// Create a pool and a series. See the DepositAddress example for more info
// on how this is done.
pool, seriesID, err := exampleCreatePoolAndSeries(mgr, vpNamespace)
if err != nil {
fmt.Println(err)
return
}
// Unlock the manager
if err := mgr.Unlock(privPassphrase); err != nil {
fmt.Println(err)
return
}
defer mgr.Lock()
addr, _ := dcrutil.DecodeAddress("1MirQ9bwyQcGVJPwKUgapu5ouK2E2Ey4gX", mgr.ChainParams())
pkScript, _ := txscript.PayToAddrScript(addr)
requests := []votingpool.OutputRequest{
votingpool.OutputRequest{
PkScript: pkScript,
Address: addr,
Amount: 1e6,
Server: "server-id",
Transaction: 123},
}
changeStart, err := pool.ChangeAddress(seriesID, votingpool.Index(0))
if err != nil {
fmt.Println(err)
return
}
// This is only needed because we have not used any deposit addresses from
// the series, and we cannot create a WithdrawalAddress for an unused
// branch/idx pair.
if err = pool.EnsureUsedAddr(seriesID, votingpool.Branch(1), votingpool.Index(0)); err != nil {
fmt.Println(err)
return
}
startAddr, err := pool.WithdrawalAddress(seriesID, votingpool.Branch(1), votingpool.Index(0))
if err != nil {
fmt.Println(err)
return
}
lastSeriesID := seriesID
dustThreshold := dcrutil.Amount(1e4)
currentBlock := int32(19432)
roundID := uint32(0)
txstore, tearDownFunc, err := exampleCreateTxStore()
if err != nil {
fmt.Println(err)
return
}
_, err = pool.StartWithdrawal(
roundID, requests, *startAddr, lastSeriesID, *changeStart, txstore, currentBlock,
dustThreshold)
if err != nil {
fmt.Println(err)
}
// Output:
//
}
示例12: TestLimitAndSkipFetchTxsForAddr
func TestLimitAndSkipFetchTxsForAddr(t *testing.T) {
testDb, err := setUpTestDb(t, "tstdbtxaddr")
if err != nil {
t.Errorf("Failed to open test database %v", err)
return
}
defer testDb.cleanUpFunc()
_, err = testDb.db.InsertBlock(testDb.blocks[0])
if err != nil {
t.Fatalf("failed to insert initial block")
}
// Insert a block with some fake test transactions. The block will have
// 10 copies of a fake transaction involving same address.
addrString := "DsZEAobx6qJ7K2qaHZBA2vBn66Nor8KYAKk"
targetAddr, err := dcrutil.DecodeAddress(addrString, &chaincfg.MainNetParams)
if err != nil {
t.Fatalf("Unable to decode test address: %v", err)
}
outputScript, err := txscript.PayToAddrScript(targetAddr)
if err != nil {
t.Fatalf("Unable make test pkScript %v", err)
}
fakeTxOut := wire.NewTxOut(10, outputScript)
var emptyHash chainhash.Hash
fakeHeader := wire.NewBlockHeader(0, &emptyHash, &emptyHash, &emptyHash, 1, [6]byte{}, 1, 1, 1, 1, 1, 1, 1, 1, 1, [36]byte{})
msgBlock := wire.NewMsgBlock(fakeHeader)
for i := 0; i < 10; i++ {
mtx := wire.NewMsgTx()
mtx.AddTxOut(fakeTxOut)
msgBlock.AddTransaction(mtx)
}
lastBlock := testDb.blocks[0]
msgBlock.Header.PrevBlock = *lastBlock.Sha()
// Insert the test block into the DB.
testBlock := dcrutil.NewBlock(msgBlock)
newheight, err := testDb.db.InsertBlock(testBlock)
if err != nil {
t.Fatalf("Unable to insert block into db: %v", err)
}
// Create and insert an address index for out test addr.
txLoc, _, _ := testBlock.TxLoc()
index := make(database.BlockAddrIndex, len(txLoc))
for i := range testBlock.Transactions() {
var hash160 [ripemd160.Size]byte
scriptAddr := targetAddr.ScriptAddress()
copy(hash160[:], scriptAddr[:])
txAddrIndex := &database.TxAddrIndex{
Hash160: hash160,
Height: uint32(newheight),
TxOffset: uint32(txLoc[i].TxStart),
TxLen: uint32(txLoc[i].TxLen),
}
index[i] = txAddrIndex
}
blkSha := testBlock.Sha()
err = testDb.db.UpdateAddrIndexForBlock(blkSha, newheight, index)
if err != nil {
t.Fatalf("UpdateAddrIndexForBlock: failed to index"+
" addrs for block #%d (%s) "+
"err %v", newheight, blkSha, err)
return
}
// Try skipping the first 4 results, should get 6 in return.
txReply, err := testDb.db.FetchTxsForAddr(targetAddr, 4, 100000)
if err != nil {
t.Fatalf("Unable to fetch transactions for address: %v", err)
}
if len(txReply) != 6 {
t.Fatalf("Did not correctly skip forward in txs for address reply"+
" got %v txs, expected %v", len(txReply), 6)
}
// Limit the number of results to 3.
txReply, err = testDb.db.FetchTxsForAddr(targetAddr, 0, 3)
if err != nil {
t.Fatalf("Unable to fetch transactions for address: %v", err)
}
if len(txReply) != 3 {
t.Fatalf("Did not correctly limit in txs for address reply"+
" got %v txs, expected %v", len(txReply), 3)
}
// Skip 1, limit 5.
txReply, err = testDb.db.FetchTxsForAddr(targetAddr, 1, 5)
if err != nil {
t.Fatalf("Unable to fetch transactions for address: %v", err)
}
if len(txReply) != 5 {
t.Fatalf("Did not correctly limit in txs for address reply"+
" got %v txs, expected %v", len(txReply), 5)
}
}
示例13: main
func main() {
// 1. Load the UTXOs ----------------------------------------------------------
unspentFile, err := os.Open("unspent.json")
if err != nil {
fmt.Println("error opening unspent file unspent.json", err.Error())
}
var utxos []dcrjson.ListUnspentResult
jsonParser := json.NewDecoder(unspentFile)
if err = jsonParser.Decode(&utxos); err != nil {
fmt.Println("error parsing unspent file", err.Error())
}
// Sort the inputs so that the largest one is first.
inputs := extendedOutPoints{convertJSONUnspentToOutPoints(utxos)}
sort.Sort(sort.Reverse(inputs))
// 2. Load the config ---------------------------------------------------------
configFile, err := os.Open("config.json")
if err != nil {
fmt.Println("error opening config file config.json", err.Error())
}
cfg := new(configJSON)
jsonParser = json.NewDecoder(configFile)
if err = jsonParser.Decode(cfg); err != nil {
fmt.Println("error parsing config file", err.Error())
}
// 3. Check the config and parse ----------------------------------------------
switch cfg.Network {
case "testnet":
params = &chaincfg.TestNetParams
case "mainnet":
params = &chaincfg.MainNetParams
case "simnet":
params = &chaincfg.SimNetParams
default:
fmt.Println("Failed to parse a correct network")
return
}
maxTxSize = params.MaximumBlockSize - 75000
sendToAddress, err := dcrutil.DecodeAddress(cfg.SendToAddress, params)
if err != nil {
fmt.Println("Failed to parse tx address: ", err.Error())
}
// 4. Create the transaction --------------------------------------------------
// First get how much we're sending.
allInAmts := int64(0)
var utxosToUse []*extendedOutPoint
for _, utxo := range inputs.eops {
utxosToUse = append(utxosToUse, utxo)
allInAmts += utxo.amt
}
// Convert to KB.
sz := float64(estimateTxSize(len(utxosToUse), 1)) / 1000
feeEst := int64(math.Ceil(sz * float64(cfg.TxFee)))
tx, err := makeTx(params, utxosToUse, sendToAddress, feeEst)
if err != nil {
fmt.Println("Couldn't produce tx: ", err.Error())
return
}
if tx.SerializeSize() > maxTxSize {
fmt.Printf("tx too big: got %v, max %v", tx.SerializeSize(),
maxTxSize)
return
}
// 5. Write the transactions to files in raw form with the proper command
// required to sign them.
txB, err := tx.Bytes()
if err != nil {
fmt.Println("Failed to serialize tx: ", err.Error())
return
}
// The command to sign the transaction.
var buf bytes.Buffer
buf.WriteString("dcrctl ")
buf.WriteString(cfg.DcrctlArgs)
buf.WriteString(" signrawtransaction ")
buf.WriteString(hex.EncodeToString(txB))
buf.WriteString(" '[")
last := len(utxosToUse) - 1
for i, utxo := range utxosToUse {
buf.WriteString("{\"txid\":\"")
buf.WriteString(utxo.op.Hash.String())
buf.WriteString("\",\"vout\":")
buf.WriteString(fmt.Sprintf("%v", utxo.op.Index))
buf.WriteString(",\"tree\":")
buf.WriteString(fmt.Sprintf("%v", utxo.op.Tree))
buf.WriteString(",\"scriptpubkey\":\"")
//.........這裏部分代碼省略.........
示例14: loadConfig
//.........這裏部分代碼省略.........
if !cfg.CreateWatchingOnly {
if err = createWallet(&cfg); err != nil {
fmt.Fprintln(os.Stderr, "Unable to create wallet:", err)
return loadConfigError(err)
}
} else if cfg.CreateWatchingOnly {
if err = createWatchingOnlyWallet(&cfg); err != nil {
fmt.Fprintln(os.Stderr, "Unable to create wallet:", err)
return loadConfigError(err)
}
}
// Created successfully, so exit now with success.
os.Exit(0)
} else if !dbFileExists && !cfg.NoInitialLoad {
keystorePath := filepath.Join(netDir, keystore.Filename)
keystoreExists, err := cfgutil.FileExists(keystorePath)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return loadConfigError(err)
}
if !keystoreExists {
err = fmt.Errorf("The wallet does not exist. Run with the " +
"--create option to initialize and create it.")
} else {
err = fmt.Errorf("The wallet is in legacy format. Run with the " +
"--create option to import it.")
}
fmt.Fprintln(os.Stderr, err)
return loadConfigError(err)
}
if len(cfg.TicketAddress) != 0 {
_, err := dcrutil.DecodeAddress(cfg.TicketAddress, activeNet.Params)
if err != nil {
err := fmt.Errorf("ticketaddress '%s' failed to decode: %v",
cfg.TicketAddress, err)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return loadConfigError(err)
}
}
if len(cfg.PoolAddress) != 0 {
_, err := dcrutil.DecodeAddress(cfg.PoolAddress, activeNet.Params)
if err != nil {
err := fmt.Errorf("pooladdress '%s' failed to decode: %v",
cfg.PoolAddress, err)
fmt.Fprintln(os.Stderr, err.Error())
fmt.Fprintln(os.Stderr, usageMessage)
return loadConfigError(err)
}
}
if cfg.PoolFees != 0.0 {
err := txrules.IsValidPoolFeeRate(cfg.PoolFees)
if err != nil {
err := fmt.Errorf("poolfees '%v' failed to decode: %v",
cfg.PoolFees, err)
fmt.Fprintln(os.Stderr, err.Error())
fmt.Fprintln(os.Stderr, usageMessage)
return loadConfigError(err)
}
}
if cfg.RPCConnect == "" {
示例15: PurchaseTickets
// PurchaseTickets purchases tickets from the wallet.
func (s *walletServer) PurchaseTickets(ctx context.Context,
req *pb.PurchaseTicketsRequest) (*pb.PurchaseTicketsResponse, error) {
// Unmarshall the received data and prepare it as input for the ticket
// purchase request.
spendLimit := dcrutil.Amount(req.SpendLimit)
if spendLimit < 0 {
return nil, grpc.Errorf(codes.InvalidArgument,
"Negative spend limit given")
}
minConf := int32(req.RequiredConfirmations)
var ticketAddr dcrutil.Address
var err error
if req.TicketAddress != "" {
ticketAddr, err = dcrutil.DecodeAddress(req.TicketAddress,
s.wallet.ChainParams())
if err != nil {
return nil, grpc.Errorf(codes.InvalidArgument,
"Ticket address invalid: %v", err)
}
}
var poolAddr dcrutil.Address
if req.PoolAddress != "" {
poolAddr, err = dcrutil.DecodeAddress(req.PoolAddress,
s.wallet.ChainParams())
if err != nil {
return nil, grpc.Errorf(codes.InvalidArgument,
"Pool address invalid: %v", err)
}
}
if req.PoolFees > 0 {
err = txrules.IsValidPoolFeeRate(req.PoolFees)
if err != nil {
return nil, grpc.Errorf(codes.InvalidArgument,
"Pool fees amount invalid: %v", err)
}
}
if req.PoolFees > 0 && poolAddr == nil {
return nil, grpc.Errorf(codes.InvalidArgument,
"Pool fees set but no pool address given")
}
if req.PoolFees <= 0 && poolAddr != nil {
return nil, grpc.Errorf(codes.InvalidArgument,
"Pool fees negative or unset but pool address given")
}
numTickets := int(req.NumTickets)
if numTickets < 1 {
return nil, grpc.Errorf(codes.InvalidArgument,
"Zero or negative number of tickets given")
}
expiry := int32(req.Expiry)
txFee := dcrutil.Amount(req.TxFee)
ticketFee := dcrutil.Amount(req.TicketFee)
if txFee < 0 || ticketFee < 0 {
return nil, grpc.Errorf(codes.InvalidArgument,
"Negative fees per KB given")
}
lock := make(chan time.Time, 1)
defer func() {
lock <- time.Time{} // send matters, not the value
}()
err = s.wallet.Unlock(req.Passphrase, lock)
if err != nil {
return nil, translateError(err)
}
resp, err := s.wallet.PurchaseTickets(0, spendLimit, minConf,
ticketAddr, req.Account, numTickets, poolAddr, req.PoolFees,
expiry, txFee, ticketFee)
if err != nil {
return nil, grpc.Errorf(codes.FailedPrecondition,
"Unable to purchase tickets: %v", err)
}
respTyped, ok := resp.([]*chainhash.Hash)
if !ok {
return nil, grpc.Errorf(codes.Internal,
"Unable to cast response as a slice of hash strings")
}
hashes := marshalHashes(respTyped)
return &pb.PurchaseTicketsResponse{TicketHashes: hashes}, nil
}