blockcypher / gobcy Goto Github PK
View Code? Open in Web Editor NEWA Go wrapper for the BlockCypher cryptocurrency API.
License: Other
A Go wrapper for the BlockCypher cryptocurrency API.
License: Other
The package appears to use int
to represent satoshi amounts in transactions. As in Go int
can be either int32
or int64
, some people might run into problems by trying to spend more than 21.474'836'47 BTC. All int
s relating to value should be converted to int64
to avoid any issues.
Should make the code more readable/succinct.
I send Dash coin to another dash address, but I see an error bellow:
HTTP 400 Bad Request, Message(s): Error validating generated transaction: Error running script for input 0 referencing 55457fcd4607a14ad37d5f61484cdc39c37b5016935eb8c4334ab1385134830c at 0: Script was NOT verified successfully
Can guys help! thank you.
Hi, I have some code to send BTC to one address, can some one help me send to 2 different addresses with different amounts, thank you so much.
` wif, err := btcutil.DecodeWIF(secret)
if err != nil {
return "", err
}
pkHex := hex.EncodeToString(wif.PrivKey.Serialize())
tx := gobcy.TempNewTX(from, destination, *big.NewInt(int64(amount)))
if fee != -1 {
tx.Fees = *big.NewInt(int64(fee))
}
//Post New TXSkeleton
skel, err := bs.chain.NewTX(tx, false)
if err != nil {
log.Println("bs.chain.NewTX err: ", err, tx)
return "", err
}
prikHexs := []string{}
for i := 0; i < len(skel.ToSign); i++ {
prikHexs = append(prikHexs, pkHex)
}
//Sign it locally
err = skel.Sign(prikHexs)
if err != nil {
log.Println("skel.Sign error: ", err)
return "", err
}
// add this one with segwit address:
for i, _ := range skel.Signatures {
skel.Signatures[i] = skel.Signatures[i] + "01"
}
skel, err = bs.chain.SendTX(skel)
if err != nil {
log.Println("bs.chain.SendTX err:", err)
return "", err
}
return skel.Trans.Hash, nil`
how to check a valid address without call an API!
Thank you!
Su
Hi, I have some code to transfer. I hardcode the fee is 40000 satoshi. But with a large amount (1 btc, 5 btc ...), the blockcypher will rejected the sent tx, or pending for a long time. So, Can someone help me how to calculate the exact fee for a send transaction.
Thank you so much!
func (bs *BlockcypherService) SendTransaction(secret string, from string, destination string, amount int) (string, error) {
wif, err := btcutil.DecodeWIF(secret)
if err != nil {
return "", err
}
pkHex := hex.EncodeToString(wif.PrivKey.Serialize())
tx := gobcy.TempNewTX(from, destination, amount)
tx.Fees = 40000 // how to calculate the exact fee for this transaction?
skel, err := bs.chain.NewTX(tx, false)
if err != nil {
return "", err
}
prikHexs := []string{}
for i := 0; i < len(skel.ToSign); i++ {
prikHexs = append(prikHexs, pkHex)
}
err = skel.Sign(prikHexs)
if err != nil {
log.Println(err)
return "", err
}
skel, err = bs.chain.SendTX(skel)
if err != nil {
log.Println(err)
return "", err
}
return skel.Trans.Hash, nil
}
Does this support the ETH API as well?
Sorry for opening an issue, couldn't find any other way to ask a question like that.
Thanks!
Hi guys, I have a temp wallet, I want to send all balance of the temp wallet to a master wallet.
Can you help me with this function, thank you so much!
On the open API I have been using the txrefs object to see if a txinput has been spent or not.
Now, on gobcy. GetAddrFull I seem to receive an empty TXRefs structure, even though I expected it to be filled with data (and the open API does show it non-empty)
The SendTX(skel TXSkel) (trans TXSkel, err error)
returns invalid character '<' looking for beginning of value.
The occurred while trying to send a TX with about 150 inputs.
how to replace higher fee when the transaction is stuck (pending for a long time)
thank you!
To see usage from within the Golang API.
gobcy supports ETH, which should be indicated in the README.
Also an example as there is for BTC as addition would certainly be helpful.
Hi! I'm trying to create a transaction on bitcoin testnet
From:
Public: mvGY7eLArdCv2vAFEQ1UjP1JxpPG7Qk5h6
Private: 93PAkRzFDAgRq8hgdcpAmKri6ApfY1hnbymvEK7WWEppDQVP8vP
To:
Public: ms1MWPgadxuRaaVSVa9i7gobFy6D8HubtJ
On the testnet.
`package main
import (
"fmt"
"github.com/blockcypher/gobcy"
)
func main() {
//note the change to BlockCypher Testnet
bcy := gobcy.API{"MY-KEY", "btc", "test3"}
//Post New TXSkeleton
skel, err := bcy.NewTX(gobcy.TempNewTX("mvGY7eLArdCv2vAFEQ1UjP1JxpPG7Qk5h6", "ms1MWPgadxuRaaVSVa9i7gobFy6D8HubtJ", 400000), false)
//Sign it locally
err = skel.Sign([]string{"93PAkRzFDAgRq8hgdcpAmKri6ApfY1hnbymvEK7WWEppDQVP8vP"})
if err != nil {
fmt.Println(err)
}
//Send TXSkeleton
skel, err = bcy.SendTX(skel)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%+v\n", skel)
}
`
From the examples, I think I have to do it like this, but it keeps giving me the error, can you give me some advice?
I noticed a few places in the code don't check errors they just generate. This for example caused me to lose half an hour debugging code since I accidentally passed an address instead of private key and the code forgot to assert the error wasn't nil. Some examples of this:
https://github.com/blockcypher/gobcy/blob/master/tx.go#L146
https://github.com/blockcypher/gobcy/blob/master/gobcy.go#L130
Similarly, here:
https://github.com/blockcypher/gobcy/blob/master/gobcy.go#L62
an error is not checked and it didn't catch the server backend API returned a message that wasn't compatible with JSON (sent a separate email about that).
I can not transfer with from_address is a segwit address.
error:
HTTP 400 Bad Request, Message(s): Error validating generated transaction: Error running script for input 0 referencing 642fa2f5db306ae7f17d1afc50be5798e3e8ccd8d4a4c6c4b040b45e25defa37 at 0: Script was NOT verified successfully.
I have converted the segwit to legacy address but it still doesn't work for me.
2 addresses with different balances (balance of legacy is 0
the error:
HTTP 400 Bad Request, Message(s): Unable to find a transaction to spend for address 1KC5iLrRUhvsdofmym3kECnjpgQPxy2uTb., Error validating generated transaction: insufficient priority and fee for relay
can guys help me?
the code:
wif, err := btcutil.DecodeWIF(secret)
if err != nil {
return "", err
}
// fromAddress is a segwit address:
pkHex := hex.EncodeToString(wif.PrivKey.Serialize())
tx := gobcy.TempNewTX(fromAddress, destination, amount)
tx.Fees = fee
skel, err := bs.chain.NewTX(tx, false)
if err != nil {
return "", err
}
prikHexs := []string{}
for i := 0; i < len(skel.ToSign); i++ {
prikHexs = append(prikHexs, pkHex)
}
err = skel.Sign(prikHexs)
if err != nil {
log.Println(err)
return "", err
}
skel, err = bs.chain.SendTX(skel)
if err != nil {
log.Println(err)
return "", err
}
return skel.Trans.Hash, nil
I'm trying to broadcast a signed raw transaction via REST API call to the endpoint:
https://api.blockcypher.com/v1/bcy/test/txs/push?token=<token>
passing the tx in the request body:
{"tx": <signedRawTx>}
as stated in the documentation.
My problem is that the request always fails with an error like this one:
Error validating transaction: Transaction 03f4e5f76bc773bfb6639651ff63668ac6dfc8b75c42855fde16af5407b61592 orphaned, missing reference 2dce14ce7b628641f0305e8511868b4d8758428161bf93b2979f2d9eb00495ce.
But if I try to broadcast the same transaction from your service (https://live.blockcypher.com/btc-testnet/pushtx/) it doesn't fail.
Am I calling the wrong endpoint?
116688
gobcy.TempMultiTX built a tx object as NewTX(tx) must be err
trans, err := gobcy.TempMultiTX(sender.Address...)
then
API.NewTX(trans, true)
raise ("Error building input: Cannot use P2SH as input without 'script_type' set to 'multisig-n-of-m'")
Hi, Kudos to Blockcypher team.
I got this error while trying to broadcast Transaction on BTC TestNet3 (test3)
*TXSkel.Sign error: number of private keys != length of ToSign array,
The original line of code that produces this error looks like
err := txSkeleton.Sign([]string{privateKey})
,
i tried to get rid of the error by repeating the private key inside .Sign([]string{}) - something like this
err := txSkel.Sign([]string(privateKey)) if err != nil { err = txSkel.Sign([]string{privateKey, privateKey}) //try to Sign again by repeating private key entry if err != nil { //return error message } }
It worked once, then i started seeing the error again
*TXSkel.Sign error: number of private keys != length of ToSign array
Any help will be very much appreciated. Thanks!
For blockchains with large amounts (cough dogecoin cough) or very large or active wallets, total received, sent or balance can overflow an int. Someday, even NumTx could.
Thanks for the feedback @ThePiachu ! Will add this to the queue.
Hey,
I tried to install this by doing:
go get github.com/blockcypher/gobcy/
But it failed and spit this out:
github.com/blockcypher/gobcy imports
github.com/btcsuite/btcd/btcec: cannot find module providing package github.com/btcsuite/btcd/btcec
I'm unable to successfully [sign and] send a transaction using this library. I keep getting the error:
HTTP 400 Bad Request, Message(s): Error validating generated transaction: Error running script for input 0 referencing 97043eae569096c8435a431a6a0b1751a9aee08851abf318a8d8dcbe35e56063 at 0: Script was NOT verified successfully.
I'm essentially following the example in the docs with a few differences. I'm using an HD (BIP 84) Wallet.
I'm sure I'm signing with the correct private key (in the hex format), I'm able to derive [the input] addresses returned as part of the TxSkel
that's returned to me using the same private keys that I use to sign the transaction.
Here's a snippet of the code:
walletName := os.Getenv("WALLET_NAME")
btcAmount, _ := btcutil.NewAmount(txRequest.Amount)
satoshiAmount := int(btcAmount.ToUnit(btcutil.AmountSatoshi))
input := gobcy.TXInput{
WalletName: walletName,
}
output := gobcy.TXOutput{Value: satoshiAmount, Addresses: []string{txRequest.RecipientAddress}}
tempTx := gobcy.TX{Inputs: []gobcy.TXInput{input}, Outputs: []gobcy.TXOutput{output}}
skeleton, err := blockCypherClient(txRequest.CurrencyIso).NewTX(tempTx, false)
if err != nil {
log.Printf("%+v", err)
}
log.Printf("%+v", skeleton.Trans)
// Output: 2020/07/23 01:04:57 {BlockHash: BlockHeight:-1 Hash:a6d523fedc8dfcf003278640d9a6daf9dd8920cd5dca926f2d3a40247c25938d Addresses:[bc1q26w9elz890cj0tcwfvut6uqaez6gk7hkm727pc 34oefDtSVSdiEoVgikXkyemgKXkQnZ8QZS] Total:100000 Fees:10000 Size:124 Preference:high RelayedBy:41.184.252.142 Received:2020-07-23 00:04:57.546679367 +0000 UTC Confirmed:0001-01-01 00:00:00 +0000 UTC Confirmations:0 Confidence:0 Ver:1 LockTime:0 DoubleSpend:false DoubleOf: ReceiveCount:0 VinSize:2 VoutSize:1 Hex: DataProtocol: ChangeAddress: NextInputs: NextOutputs: Inputs:[{PrevHash:97043eae569096c8435a431a6a0b1751a9aee08851abf318a8d8dcbe35e56063 OutputIndex:0 OutputValue:100000 Addresses:[bc1q26w9elz890cj0tcwfvut6uqaez6gk7hkm727pc] Sequence:4294967295 ScriptType:pay-to-witness-pubkey-hash Script: Age:640274 WalletName:} {PrevHash:7e85fae44ff92e53e9316b9e09bdee8d53f848ad13b355992b460cafa7556e59 OutputIndex:0 OutputValue:10000 Addresses:[bc1q26w9elz890cj0tcwfvut6uqaez6gk7hkm727pc] Sequence:4294967295 ScriptType:pay-to-witness-pubkey-hash Script: Age:640275 WalletName:}] Outputs:[{SpentBy: Value:100000 Addresses:[34oefDtSVSdiEoVgikXkyemgKXkQnZ8QZS] ScriptType:pay-to-script-hash Script:a914222989e5ecdf370e31faf7f0175240c094c3f78387 DataHex: DataString:}]}
var privateKeys []string
for _, input := range skeleton.Trans.Inputs {
address := models.Address{}
DB.Where("value = ?", input.Addresses[0]).First(&address)
privateKey := getAddressPrivateKey(address) // this is how I generate the hex private key. Function code below
privateKeys = append(privateKeys, privateKey)
}
err = skeleton.Sign(privateKeys)
if err != nil {
log.Printf("%+v", err)
}
skeleton, err = blockCypherClient(txRequest.CurrencyIso).SendTX(skeleton)
if err != nil {
log.Println(err)
// Output: HTTP 400 Bad Request, Message(s): Error validating generated transaction: Error running script for input 0 referencing 97043eae569096c8435a431a6a0b1751a9aee08851abf318a8d8dcbe35e56063 at 0: Script was NOT verified successfully.
}
Here are the functions I use to generate the private key(s):
func getKeyAccounts() (publicKeyAccount, privateKeyAccount *bip32.Key) {
mnemonic := os.Getenv("SEED_PHRASE")
seed := bip39.NewSeed(mnemonic, "")
// create a master Key from mnemonic seed
masterPrivateKey, _ := bip32.NewMasterKey(seed)
masterPrivateKey.Version = Bip84PrivateWalletVersion
masterPublicKey := masterPrivateKey.PublicKey()
masterPublicKey.Version = Bip84PublicWalletVersion
// Generate a BIP84 path key derivation
purposeChildKey, _ := masterPrivateKey.NewChildKey(PurposeBIP84)
coinTypeChildKey, _ := purposeChildKey.NewChildKey(CoinTypeBTC)
// generate first child account of m/84'/0'/0'
childAccount, _ := coinTypeChildKey.NewChildKey(0 + Apostrophe)
childAccount.Version = Bip84PrivateWalletVersion
childAccountPublicKey := childAccount.PublicKey()
return childAccountPublicKey, childAccount
}
func getAddressPrivateKey(address models.Address) string {
path := address.Path // I save the path as a string in my database. It's in the format m/0/1, m/0/2...etc
pathSlice := strings.Split(path, "/")
_, extendedPrivateKeyAccount := getKeyAccounts()
firstChildIdx64, _ := strconv.ParseUint(pathSlice[1], 10, 32)
firstChildIdx32 := uint32(firstChildIdx64)
firstChild, _ := extendedPrivateKeyAccount.NewChildKey(firstChildIdx32) // to get the m/0 child
secondChildIdx64, _ := strconv.ParseUint(pathSlice[2], 10, 32)
secondChildIdx32 := uint32(secondChildIdx64)
secondChild, _ := firstChild.NewChildKey(secondChildIdx32) // to get m/0/i child
prvKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), secondChild.Key)
btcwif, _ := btcutil.NewWIF(prvKey, &chaincfg.MainNetParams, true)
privateKeyHex := hex.EncodeToString(btcwif.PrivKey.D.Bytes()) // sure this is the correct hex private key. I can always find my way back to correct the input address with this string
return privateKeyHex
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.