Giter VIP home page Giter VIP logo

gobcy's People

Contributors

acityinohio avatar huahuayu avatar jinyuliu avatar passos avatar quentinlesceller avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gobcy's Issues

Use int64 instead of int for values

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 ints relating to value should be converted to int64 to avoid any issues.

the error: Script was NOT verified successfully

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, how to send BTC to 2 different addresses with different amounts?

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 calculate the exact fee for a send transaction?

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
}

ETH Support?

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!

how to send max amount with gobcy

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!

Empty TXRefs on BTC with GetAddrFull

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)

SendTX(skel) fails

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.

Add ETH to readme

gobcy supports ETH, which should be indicated in the README.

Also an example as there is for BTC as addition would certainly be helpful.

Error: Script was NOT verified successfully

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?

Make sure all errors are checked and handled

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).

Can not transfer with from address is a BTC segwit address.

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

Broadcasting tx from API call always return error

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?

gobcy.TempMultiTX built a tx object as NewTX(tx) must be err

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'")

TXSkel.Sign error: number of private keys != length of ToSign array

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!

All numbers in Addr are ints

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.

go get github.com/blockcypher/gobcy/ ERROR

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

Error: Script was NOT verified successfully

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 
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.