text:
How is the Output script formed?
I read about Input and output scripts on the wiki here:
https://en.bitcoin.it/wiki/Transactions
Let's say, I use my Bitcoin - QT Program, I go to "Send Coins" tab, enter a Bitcoin Address, BTC amount and then click Send.
Is the output script generated by my program?
For an output script, we need the Value, The destination Address and the scriptPubKey. My client program has all this data.
scriptPubKey refers to Public Key of? My public key or the person I intend to send the Bitcoins to?
So, now, once the output script is formed, is it broadcast over the Bitcoin Network?
Where does the Input Script come from?
the scriptSig in Input Script refers to the Public Key and Signature of whom?
When I am sending Bitcoins to a Bitcoin Address, the input Script is automatically generated by what?
Even though the wiki gives details about Input Script and output Script, I was unable to correlate it to a real time scenario where one person sends BTC to another.

Is the output script generated by my program?

Yes.

scriptPubKey refers to Public Key of?

Whoever you're sending the bitcoins to.

So, now, once the output script is formed, is it broadcast over the Bitcoin Network?

After it's signed, yes.

Where does the Input Script come from?

It is composed of two pieces - your public key, and a valid signature corresponding to that public key. So, you make it.

the scriptSig in Input Script refers to the Public Key and Signature of whom?

You.

When I am sending Bitcoins to a Bitcoin Address, the input Script is automatically generated by what?

Your client, after looking at your wallet.

Even though the wiki gives details about Input Script and output Script, I was unable to correlate it to a real time scenario where one person sends BTC to another.

There are two parts to a bitcoin transaction - the part where you prove that you own some bitcoins, and the part where you designate someone else to be able to prove they own some bitcoins.

So, the Public Key in scriptPubKey differs from the Public Key in scriptSig?

scriptPubKey is very poorly named, because when you're sending bitcoins to an address, you only know the 160-bit hash of the public key. A scriptPubKey looks like this:
OP_DUP OP_HASH160 06f1b670791f9256bffc898f474271c22f4bb949 OP_EQUALVERIFY OP_CHECKSIG

The 06f1b6... is how your client specifies who it's sending to. The parts around it are scripts that tell the bitcoin client how to validate the transaction.

Also, we only have the Bitcoin Address of the person we intend to send the Bitcoins to. How do we get the Public Key of the recipient?

We don't need to. We can tell the network the 160 bit hash, and the person you're sending to can show the public key to the network when they want to spend their bitcoins.

Thanks. So, the Public Key in scriptPubKey differs from the Public Key in scriptSig? Also, we only have the Bitcoin Address of the person we intend to send the Bitcoins to. How do we get the Public Key of the recipient? I know that Bitcoin Address is itself the 160-bit hash of the public portion of the recipient's Public/Private Key pair. But I am unable to correlate the two.

@NeonFlash I have edited my answer.

Thanks. I think I have understood now. So, the scriptPubKey which we are referring to in the Transaction Verification phase, is "NOT" the recipient's Bitcoin Address. It is the scriptPubKey stored in the "output script" of the previous transaction of the sender. The sender's scriptSig (sig + pubkey) will be verified against the scriptPubKey stored in the output script of previous transaction. Then, it can be claimed by the sender. The new output script generated by the sender, will assign the Bitcoins to recipient's address and provide a way for the recipient to claim them in future. Correct?


text:
How do nodes verify Bitcoin Transactions?
I am trying to understand the role played by various nodes in the Bitcoin Network in verifying the transactions that are taking place in real time. I think that I understand the process of Transaction (using Input and Output Scripts) and how the Transaction is formed. However I am trying to correlate it with how a Transaction is Broadcasted to other nodes and then verified?
Consider an example:
if A wants to send some BTC to B, then 2 things will occur:
(a) A will form the input script of the new transaction. It will reference the output script of a previous transaction where A received some BTC (in the past). It will prove the ownership of those BTC by using its Public Key and verifying the Signature.
(b) The output script for the new transaction will be formed by A's client. It will store the hash of the BTC Address of B and enable it to spend these BTC in future.
Now, my questions are:

All these actions are performed by the Bitcoin Client of A and it does not require any interaction with the Peer to Peer Network. It has its own local copy of the Block Chain which it can use to perform the step a. So, isn't the transaction verified by the bitcoin client of A?
I am guessing that this new transaction that was created (input and output scripts formed as described above) will be broadcasted to the entire Bitcoin Network. Now, what type of verification is being performed by other nodes on this transaction?

On what basis is a Transaction accepted by the Bitcoin Network and integrated into the Block which is a part of the Block Chain?
Thanks.

Yes, but that doesn't mean that the network has accepted it.
There are rules for accepting a transaction.  Miners only include blocks that don't break the rules.  The rules include checking that the inputs are valid, that a coin isn't double-spent, that the output isn't more than the input, etc.

A miner can choose to include a transaction or not.  A miner could even choose to include a transaction that breaks the rules!  But if he does that, other miners that are following the rules won't accept his block and he won't get his mining reward.  So he has incentive to follow the rules.

thank you for the answer here -- how much does it cost computationally for the miner to do so? would that incentivize them to include less transactions as it takes longer to validate each one?

@streetlight The computanional cost of verification is almost negligible compared to that of creating a block. Also, transactions normally have fees attached to them which will outweigh the verification cost.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
How to fork blockchain intentionally without RPC commands?
Are there any methods other than RPC command invalidateblock <hash> for creating forks?
I know that forks occur when two miners (nearly) simultanously each generate a block for a previous common block but is this the only natural way to fork the blockchain?
I want to test blockchain forks with multiple nodes and would like to have one node intentionally create forks from time to time. How can I achieve this? Do I need to make all nodes generate blocks simultanously and hope that randomly two or more blocks are created at the same time? - This would lead to a mess, right?

I'm guessing that you're trying to test how your software handles arbitrarily large reorgs, right? Have you tried splitting your network into A and B, and disconnecting them from each other to create a fork?

@NickODell: I'm more interested in testing selfish mining in regtest. I want to fork the blockchain again after reorganisation in an automated fashion so everytime selfish mining fails OR wins a round of 'race' ,the blockchain is forked again to start a new selfish mine attack. Splitting is not a solution i guess since at least the selfish miner has to watch honest miners actions in order to react according to selfish mine algorithm so they need to stay connected.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Implicit/Tacit mechanisms in Bitcoin Core disclosing Selfish Mining
I'm referring to the selfish mine attack described by two researchers from Cornell University who describe a "possible" attack with lower than 51% hashing power.
Now it's interesting to know what sorts of mechanisms, changes were implemented into the new versions of Bitcoin Core that detect selfish mining, propagate some alerts, disclose suspicious forks etc.?

EDIT:
Obviously peers get to know about other peers' progress on the blockchain through data messages, in particular through updates via inv messages.
Are there other types of "messages" exchanged - without the knowledge of the node itself - that would give away secrets about a longer private blockchain, in this case?

It's not really clear to me how that would work, given that selfish mining would appear as though some hashpower dropped out, followed by a reorganization when the new chain was published.

So you're implying that a hashpower drop-out as an indication of a potential selfish mining attack doesn't trigger an alert message or something similar?

Yeah. Now, if those nodes started mining on a chain that your client thought was invalid, and that chain became the best chain, then that would trigger an alert, sure.

Ok. Thats exactly what I'm looking for..where is this alert in the source code? Is it somewhere in main.cpp or also in othr modules?

@NickODell: you spoke of "mining on a chain that your client thought was invalid, and that chain became the best chain" - are there any other characteristics of an invalid chain than being shorter?

Suppose I mined a one point one megabyte block. Since the current limit is one megabyte, your client won't accept this. If I then mine six blocks further than the best valid chain you know about, then your client will display a warning and disable RPC.

It is impossible to detect a drop in hashrate working on a chain because foreign hashpower is only evident in the discovery speed of blocks, except if it were deducted from a pool publicly sharing its mining stats. Thus the dropped hashrate would only be evident over sufficient long spans of time.
The only indicator of selfish mining would be the actual publishing of a previously unknown longer chain. I believe I've read somewhere that this will be shown in BitcoinCore with a "Reorganization" warning.

In the case of a pool, another indicator is when the pool is asking miners to mine on a block that is not publicly known.

I meant that it might be visible, if a large mining farm deducted its power from a pool. As the mining goals of pools are more or less public information anyway, I figured that it wouldn't be necessary to mention the possibility of a pool operator trying to enlist his pool in such a scheme.


text:
Total amount of nodes and avarage active peer number
I have 2 questions:

Does anyone know where to find a reliable source for finding out a total amount of active bitcoin nodes?
How many peers does each active node have in avarage? Is there a limit to how many peers one node can have?

Does anyone know where to find a reliable source for finding out a total amount of active bitcoin nodes?

http://getaddr.bitnodes.io/ tracks listening peers on IPv4 and IPv6 only. The number is subject to gaming if people desire, there's no assurance that any of the nodes there are actually useful to connect to. At least some of the nodes listed will be duplicate due to them having both an IPv4 and IPv6 socket open at the same time and thus appearing as "two" nodes.

How many peers does each active node have in average?

Bitcoin nodes will only attempt outgoing connections which are in ranges of IP addresses that are not close together, specifically for IPv4 it won't connect to any two nodes that are in the same /16 block. This means that any node running on a popular area such as a VPS host or EC2 node will likely see substantially less incoming activity than one running in a less densely populated area. This is an attempt to raise the cost of a large scale sybil attack against the network by increasing the diversity of IP addresses needed to gain an extremely large number of connections.
As a result you have to be very careful how you gain statistics about the number of incoming connections, because not all listening sockets are equal in the eyes of a client attempting to find peers. As far as I am aware nobody does this sort of data collection on a wide scale and publishes the results, but it is probably in the high tens of connections inbound on most nodes judging by my own experience.

Is there a limit to how many peers one node can have?

The default is 125 maximum, 8 outgoing and 117 incoming.
Absent this the number is bounded by the constraints of the system it is running on.


text:
Block Broadcasting - Unsolicited Block Push
Can someone, please, direct me to the source code section(s) relevant for an Unsolicited Block Push as described in the Bitcoin Developer Guide?
I've been going through main.cpp and searched for the term MSG_BLOCK, serving as a beagle for finding the correct place in the code. But as I'm reading further, it seems to me as if a freshly mined block is not appended to a inventory message, with MSG_BLOCK, in order to send it as a "package" as response to a request (GetData Response) BUT is sent as a single message of this structure:

To me, up to now, the best canditate for Unsolicited Block Push seems to be main.cpp#L2393 part of main.cpp but I'm confused since I don't know if there is more of possibly relevant code (like main.cpp#L3830) for Unsolicited Block Push in /src/.
So: In a first step, I'm looking for code that is relevant for broadcasting a newly found block. Can someone please help?

We can find all instances in the code where the client will send a block message by searching for PushMessage("block". This is the only match:
void static ProcessGetData(CNode* pfrom)
{
[...]
    pfrom->PushMessage("block", block);

(Source.)
This means that the standard client only ever sends a block message when specifically asked for it. That incoming getdata message is probably triggered in turn by sending the remote node an inv message. (Though that's not necessary - you can ask for a block that the other node hasn't advertised.) This is the code that sends inventory messages:
//
// Message: inventory
//
vector<CInv> vInv;
vector<CInv> vInvWait;
{
    LOCK(pto->cs_inventory);
    vInv.reserve(pto->vInventoryToSend.size());
    vInvWait.reserve(pto->vInventoryToSend.size());
    BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
    {
        // If the other node already knows the message, don't send
        if (pto->setInventoryKnown.count(inv))
            continue;

        // trickle out tx inv to protect privacy
        [...]

        // returns true if remote node hasn't seen it
        if (pto->setInventoryKnown.insert(inv).second)
        {
            // Add to the list of inventory messages to send
            vInv.push_back(inv);
            // If there's 1000 inventory messages queued up, send them
            // (Protocol limit is 50000 at a time.)
            if (vInv.size() >= 1000)
            {
                pto->PushMessage("inv", vInv);
                vInv.clear();
            }
        }
    }
    pto->vInventoryToSend = vInvWait;
}
// Send any that are left over.
if (!vInv.empty())
    pto->PushMessage("inv", vInv);

(Source.)
(pto represents the remote node in the above code.)
So the page you're looking at describes a behavior that you could implement, and that other clients will accept, but it doesn't describe the current core client behavior.

"describes a behavior that you could implement, and that other clients will accept, but it doesn't describe the current core client behavior."  I wrote the docs linked above, and I didn't realize that wasn't obvious.  Sorry.  It should be updated shortly: https://github.com/bitcoin/bitcoin.org/commit/b847610e1b129a85b3fd00c251b97864f2f89781

@DavidA.Harding That was fast. :)

@NickODell: Thanks, Nick! One thing is still not completely clear. You say: "This means that the standard client only ever sends a block message when specifically asked for it. That incoming getdata message is probably triggered in turn by sending the remote node an inv message." - does this mean: (1) node1 & node2 are both at height n on a common active chain (2) node1 is faster and finds a block n+1 and pushes it to an inv message and sends this inv message to node2 and gets a getdata message from node2 asking for block n+1 (3) node1 sends a single block message with block n+1 ?

@AliakbarAhmadi Yes.

@NickODell: Ok but in what case will a unsolicited single block message be broadcasted to peers then??? Never? Is a freshly mined block sent unsolicitedly only inside an inv message?

@AliakbarAhmadi Never. Unless you modify your client.


text:
Where can I find historical exchange rate data for Dash (ex DarkCoin)/USD?
Is there a public data provider that allows to download the full history of Dash (ex DarkCoin) vs. US Dollar exchange rates?

CoinMarketCap provide charts since February 2014 and IIRC, the name was Darkcoin back then. It include the price in both Satoshi & USD.

Thank you. But how do you get the data into a CSV/XLS file? The API provides just last values, not the full history as far as I knew.

It's only possible to export it as PNG, PDF, JPG , SVG vector image or simply print it. You could do so using the button on the top right of the chart.


text:
Receiving donations by public Bitcoin wallet ID, where to make transparent deposits?
We are a transparent NGO, so we not need secret transactions, we need to expose them...
We created a Bitcoin wallet to receive donator's deposits there (at blockchain.info), and now we have an wallet ID. Can we expose our wallet ID to the public? Donators can use the wallet ID to make donations, or we must to use address?
We need a stable and permanent ID/address to expose our transparent donation reference.

No, do not expose your wallet ID. That is used for logging in to your wallet on the site and is for you only.
Instead, simply expose your bitcoin address. Making that publicly available will mean anyone can send your donations and everyone can see the transactions happening with that address. There is no security risk in exposing your bitcoin address to everyone, if you want transparency.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How can I verify that a system is generating legit Private Key and Native SegWit address pairs?
I'm helping someone put a Native SegWit address (bc1...) on a website to collect Bitcoin donations.
I've found some javascript code that generates Private Key and Native SegWit address pairs offline. (I don't want to use a managed wallet. I prefer a paper wallet.)
I want to generate a couple "throwaway" pairs and test them to see if they are, indeed, legit. That is, the Native SegWit address indeed maps to the Private Key. How may I test this?
Update: here's an example of a pair:

L2xHquk5T9d7LZz27pDgMdrnisiLNkADscHcsJbNCs5qBStb3r1k
bc1qxhq4au5m74nv925fr6fzqaux3akn38gf3m9628

Update: I verified the pair was legit by using this tool: https://kimbatt.github.io/btc-address-generator/?page=address-details

If you verified the private key using an internet-connected tool, you should not use that key for receiving bitcoin. Stay Safe!

You could try to import the private keys that the Javascript function gives you into wallet software like Electrum, then check that the associated payment address shows up on the 'Addresses' tab. You should be able to left-click on the payment address and use the option to display its private key, just to triple check if you wish.

Good suggestion, I just tried it. Unfortunately, Electrum only shows me a "Legacy" address, not the Native SegWit address. But thanks for the suggestion.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
`fundrawtransaction` error when trying to spend an HTLC
I'm trying to use the fundrawtransaction RPC command in order to create a transaction spending an HTLC output. Here is the command i've entered:
fundrawtransaction "02000000019ab30b02450c227d38d11f1e32de4139c4b14e6496e8c791615673be577691e10000000000fdffffff01a00f000000000000160014d095ce864aa19d47371c4a87c3c61a3cdd180b0b00000000" "{\"changeAddress\": \"bc1qccvnpr2rgfh4k7mcaty4dn3nesmtsyhwn5d58q\", \"outputs\": [{\"script\": \"6352210242625461fa5e6d69921fc95973b9ad4b139cbd16bbb4dd82a59c15f90193b25567a8f1e84f1a9abb1dce8d2a0b2a1e3cbb0c5fb41baf5f8220e14e7d059b463e3b88ac76a91402ec9dcf6c138a3d8c7ae214e2ce37577766f321388670a02211af0daf491b036b0eb4ded2861dbc7b21e11c8b010f70cc282f4e9e3fb81c752ae87\", \"amount\": 0}]}"

I'm getting this error:
Unexpected key outputs (code -3)

I don't understand what this error relates to.

You are passing a JSON key outputs in the second argument to fundrawtransaction (named "options"). This is not a recognized parameter.
It looks like you are trying to pass a redeemscript to the command for it to be able to create a valid scriptsig. You probably want to pass this script as part of the solving_data key inside the "options" parameter. See the documentation for fundrawtransaction.
Note fundrawtransaction only works for legacy script though. I see you are trying to pass an amount key as well, i assume it's for the Bitcoin Core wallet to sign the transaction using a Segwit signature hash. You should probably use PSBT commands in the Bitcoin Core wallet instead.


text:
Import old paper backup (WIF private key) into modern Bitcoin-QT
When trying to import a WIF private key into Bitcoin-QT i get this error:

Only legacy wallets are supported by this command (code -4)

How can one import a private key on a non-legacy wallet?

I don't know how to perform this on the GUI, but in order to import a WIF private key on a modern Bitcoin Core you have to use a descriptor. In order to recover from a backup, you most likely want to use the combo() descriptor.
Here is an example with an example WIF private key: cSWVo8YMehg6STxqw6xGgmMJE6Ac6RCJ7owcrBZRAT7QANtyAAEj (it's a testnet-encoded WIF private key on purpose, yours will be different). There is most likely a similar flow on the graphical interface, but failing that you can always use the command line (or the command input on the GUI).
First craft a combo descriptor from this private key and get its checksum:
getdescriptorinfo 'combo(cSWVo8YMehg6STxqw6xGgmMJE6Ac6RCJ7owcrBZRAT7QANtyAAEj)'

We get:
{
  "descriptor": "combo(023ad6336ae257527ff59ec4356fa5d2ac33fff5e04be9e5958dfed9b0100b7948)#mv9rgx7y",
  "checksum": "9zedq5ns",
  "isrange": false,
  "issolvable": true,
  "hasprivatekeys": true
}

You can now import this descriptor using the importdescriptors command:
importdescriptors '[{"desc":"combo(cSWVo8YMehg6STxqw6xGgmMJE6Ac6RCJ7owcrBZRAT7QANtyAAEj)#9zedq5ns","timestamp":"now"}]'

Finally rescan the blockchain from a point before which you are certain to not have received coins. To rescan the whole chain from the genesis block do not provide any parameter:
rescanblockchain

importprivkey only works on legacy wallets, so you need create a legacy wallet and then import the private key succ.

create a new wallet with descriptor wallet unchecked.
go to console and importprivkey.


text:
Transaction created using `bitcoin-cli` failed to decode
I am creating a rawtransaction using bitcoin-cli. After I create my transaction using 'bitcoin-cli createrawtransaction ' this returns and HEX of:
[encoded data, 12382 characters]

But then when I try "signrawtransactionwithwallet" this returns TX decode failed. Make sure the tx has at least one input.
bitcoin-cli -rpcwallet=$wallet signrawtransactionwithwallet "hex"
How can fix this?

Please edit your post with the commands you typed. I could decode the transaction you provided using decoderawtransaction.

For the ones who might have same problem this is solved by adding -stdin to the request in command line

I doubt adding -stdin would change anything to the transaction decoding.

Both decoderawtransaction and signrawtransactionwithwallet on my node managed to decode the transaction. You must have simply made a mistake when copying it.


text:
What is involved in the "database compaction" of a LND node?
As lightning network channels route payments, channel updates require the 2 channel peers (Alice & Bob) to do a round of signing and trade commitment transactions for the most up-to-date channel balance.
Is this the primary reason that the channel.db file may grow so dramatically?
For each update, Alice must keep a full record of all revocation keys from all past commitment transactions in case Bob broadcasts an invalid past channel state. If these keys are deleted, Alice would not be able to create & broadcast the correct penalty transaction to punish Bob.
Database compaction is typically run on startup of the node, but what exactly is involved in that compaction? Are the revocation keys being indexed / compressed in some lossless/recoverable fashion?
Do other implementations than LND have the same process?

The compaction is only relevant for bbolt database files, which are very common with lnd. In this case, the channel database is stored as a bbolt file named channel.db. Note that you can also use PostgreSQL with lnd to persist this information, in which case you don't need compaction (PostgreSQL has a concept named "vacuum" which can run in the background).
During operation of lnd changes (especially deletions) to the bbolt database cause gaps in the database file, which cannot easily be filled with new data. As such, after a while, the database file consumes lots of disk space, even though a fraction of it is just empty space inside the file. Deduplication/compression features of your filesystem might help to reduce the actual storage footprint.
When you trigger the compaction, a new database file is created and filled with the data from the original file by copying everything over. This way the actual information is identical, but gaps in the original file are skipped and do not consume space in the resulting file. This is somewhat similar to file system defragmentation from the Windows 9x (and before) era.
This compaction does not change (or interpret) the data in any way, i.e. no data is compressed or deleted. Every information persisted in the original database is copied over to the new database, bit by bit. The only difference is that the internal database structure changes, which you do not see from the outside (aside from the intended benefit of reducing the storage footprint of the file).
As compaction is bbolt specific, I don't think other implementations make use of this. In general all databases should already have some means of freeing up space of deleted data, and I guess that all node implementations delete most unnecessary information after a while.

How does the compacting algorithm work? On my node, during compacting a 60G channel.db, a file temp-dont-use.db is created. Its size grows up to 20G and then drops to about 0-1G. Then the process continues several times. If it was just defragmentation, a single linear scan should have been sufficient.

That's part of my answer already.


text:
Mnemonic Phrase (BIP39) with Existing Seed Generating Library
The standard BIP39 does three things:
1) Generate 256+8 entropy
2) Generate sentence
3) Derive seed from sentence (using PBKDF2 with HMAC-SHA512).
I wonder what would be the security implication of doing things the reverse way:
1) Generate entropy and use it as seed
2) Derive 256 bit array from entropy (using PBKDF2 with HMAC-SHA256/HMAC-SHA512). + 8 bit checksum
3) Use above bit array to construct sentence
Essentially, instead of creating the seed from the sentence, I create the sentence from the seed. In the last step, if HMAC-SHA512 is used, it would generate a bit array of length 512 which is too long for the sentence. To solve that I would XOR the two halves of the array. Alternately, I could just use HMAC-SHA256.
The company I work for has a library that does seed generation and this is what we are mandated to use.

You probably know that HMAC-SHA256/HMAC-SHA512 and thus PBKDF2 are one-way functions. There would be no way how to reconstruct the seed from the generated sentence in your setup, which is the only purpose of such sentence.

that what I was trying to say :D

Thanks. I feel bad not to have thought it through.


text:
Blockchain Receive Callback API in callback url not working
I want to accept payments with the Blockchain Receive Payments API
Using create different user different address on get bitcoin but not work Callback api
https://blockchain.info/api/api_receive
&& also try Monitor addresses for received and spent payments api but not work
My problem is, the callback is never called— can anyone check my code and tell me where I the problem is?
i also try to log create but not called and check callbacl log api using not call.
please solved my problem :)
create balance update api using this file create.php
$url = "https://api.blockchain.info/v2/receive/balance_update";
    $secret = $address;
    $post_data = array(
        "key"           => $this->API_KEYCODE,
        "addr"          => $address,
        "callback"      => "https://my-server.com/callback.php?customer_id=".$user_id."&secret=".$secret,
        "onNotification"=> "KEEP",
        "op"            => "RECEIVE",
        "confs"         => $conf
    );

    Log::info('START SERVICE CALL :' . json_encode($url). " : ".json_encode($post_data));
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, count($post_data));
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER , array(
        "cache-control: no-cache",
        "content-type: text/plain",
    ));
    $ccc = curl_exec($ch);
    curl_close ($ch);

    Log::info('END SERVICE CALL :' . $ccc);
    $json = json_decode($ccc, true);
    return $json;

this api successful return response in index id , address and callback url
second file callback.php
Log::info('TEST : START (BLOCKCHAIN Callback)========================================');
    Log::info('GET : '.jsone_encode($request));
    Log::info('GET : '.jsone_encode($_GET));
    $res = 'Nothing';

    $out_address = $_GET['secret'];
    $in_address = $_GET['address'];
    $user_id = $_GET['customer_id'];

    $transaction_hash = $_GET['transaction_hash'];
    $confirmations = $_GET['confirmations'];
    $value_in_satoshi = $_GET['value'];
    $value_in_btc = $value_in_satoshi / 100000000;

    $status = true;

    if($status == true) {

                $res = "*ok*";
        } else {
            //Waiting for confirmations

            $res = "Waiting for confirmations";
        }
    }
    Log::info('RES : '.$res);
    Log::info('TEST : END (BLOCKCHAIN Callback)========================================');

Where is your code?

i call balance update api and success response return but not callback my url call any log and callback_log api thought check not callback

I presume you have checked your callback address is responding on outside requests? Can you make a manual callback test if you try just key https://my-server.com/callback.php?customer_id=foo&secret=bar?

yes i also try manual is work and create log and i try to callback log api in check also blank array response

Callback is not really working. But you can use blockchain web socket alternatively.

It's not about your code; it's from Blockchain.info.
I've made a transaction right now and never received the callback.
Blockchain.info always has these types of issues from time to time.
Please aware an issue with gap limit also. They may say that you've created 20 unused addresses and you're not.

Yes We check Callback API But, Every time we get blank(null) response in the callback log.

you have any idea for the other bitcoin send and receive api provider?

block.io would be an alternative, but it sucks as hell since you should pay for each generated address.
Soon we will launch wallet my team, and I was working on for a long time.
You can receive LTC, BTC, BCH. No gap limit and many other features, not any other wallet have.


text:
Which wallets support Bitcoin Cash?
I'm looking for a big list of wallets that support Bitcoin Cash. What are the wallets that have Bitcoin Cash support?

If you don't want to read the whole list, and just want to choose a Bitcoin Cash wallet...
(SPV = Simplified Payment Verification, does not depend on a server so it's a more decentralized.)
Sorted by various things
For PC/MAC

Electron Cash (a.k.a Electrum for Bitcoin Cash)

For Android

CoPay (SPV)

BTC.com

UnitWallet (SPV)

For iOS

CoPay (SPV)

Bitcoin.com (SPV) (updated rarely)

BTC.com

*CoPay uses a different address format. Not to be confused, please read this
Major Full Nodes

Bitcoin Unlimited Cash Edition

One of the most used cash full node wallet softwares. It has XThin support that saves bandwith while downloading new blocks and uses Parallel Validation to validate blocks faster and safer.
Website: www.bitcoinunlimited.info
Download Cash Release: www.bitcoinunlimited.info/download

Bitcoin ABC

First Bitcoin Cash full node wallet software. The most popular Bitcoin Cash node as it's the first.
Website: bitcoinabc.org
Download: download.bitcoinabc.org

Bitcoin XT

First Bitcoin scaling software - first version released in 8/2015. It supports XThin, and it supports XThin's alternative Compact Blocks too - making it (theoretically) faster and bandwidth-cheaper while downloading new blocks than other clients. It's the least used Bitcoin Cash full node, for no reason.
Website: bitcoinxt.software
Download: https://github.com/bitcoinxt/bitcoinxt/releases/latest
If you want to run one of the full-nodes but don't want to store the blockchain (140 GB)
You can use pruning, by pruning you can choose how much space allocate to these full node softwares. It supports both Bitcoin and Bitcoin Cash.
Other Major/Semi Major Wallets

Electron Cash (lightweight wallet)

The only major talented lightweight wallet - doesn't store the entire blockchain on your computer. It's a changed version of Electrum, one of the most used Bitcoin wallets.
Website & Download: electroncash.org
WARNING: There are fake Electron Cash wallets that steal your money. It is safe if and only if you're downloading it from www.electroncash.org!

BTC.com Wallet (online wallet - mobile)

The most used online wallet Bitcoin Cash & one of the best mobile Bitcoin Cash wallets
Use it here: bcc-wallet.btc.com
Google Play: https://play.google.com/store/apps/details?id=com.blocktrail.mywallet
App Store: https://itunes.apple.com/us/app/btc-com-bitcoin-wallet/id1019614423

Blockchain.info (online - mobile)

One of the major online wallets (most used?) that completely supports Bitcoin Cash. https://cointelegraph.com/news/blockchaininfo-releases-full-bitcoin-cash-support-users-receive-coins
Note: that for anyone opening a new wallet or for anyone who didn't have BTC before 1st August in their wallet, you cannot use it for storing BCH. https://support.blockchain.com/hc/en-us/articles/115005180866-Can-I-use-bitcoin-cash-BCH-in-a-new-or-existing-wallet-

Coinbase (online - mobile)*

One of the major online wallets. They are going to add option to withdraw all of your Bitcoin Cash on 1 January 2018.
Announcement: https://support.coinbase.com/customer/portal/articles/2853600-bitcoin-cash---frequently-asked-questions

Bread [former name: Breadwallet] (mobile)

Breadwallet is the safest iOS Bitcoin wallet with Bitcoin Cash one-time-withdrawal support. It doesn't use a server, instead it connects to three peers, making it more decentralized. There is a rumour that they are going to add an option to switch to Bitcoin Cash and use it like the normal Bitcoin wallet. [noref]
Announcement: https://breadwallet.com/blog/breadwallet-plan-bitcoin-cash-bch/

CoPay - BitPay (mobile - lightweight - Chrome extension - desktop)

Bitcoin Cash full support has been released, but it uses a new address format.
Announcement: https://blog.bitpay.com/bitcoin-cash-wallet/

 Coinomi (mobile)

Coinomi is one of the most known Bitcoin Cash wallets (actually it supports over 70 cryptocurrencies), however it may not be a good idea to have more than 50$, as it went closed source last year. Their developers say on its website that the private keys don't leave your device.
Android: https://play.google.com/store/apps/details?id=com.coinomi.wallet
iOS: Coming in future

Armory

One of the good Bitcoin software. Allows you to withdraw BCC (BCH, Bcash on Armory). You should read instructions below.
If further hard forks happen on BCC, its developers won't update Armory to be compatible with it. (Source)
Instructions: https://bitcointalk.org/index.php?topic=2070058.0

Mycelium

Actually Mycelium can't do anything about your Bitcoin Cash, but you can use BTC.com's tool to claim it
https://blog.btc.com/how-to-recover-your-trapped-bitcoin-cash-from-other-wallets-24b929543f26
Or you can claim it using Coinomi
https://steemit.com/btc/@libert/step-by-step-guide-on-claiming-bitcoincash-from-mycellium-wallet-201783t112141477z

Bitcoin.com wallet (mobile - desktop - Chrome extension)

A good option as a wallet. It's changed version of CoPay that fully supports Bitcoin Cash and runs on Windows, Mac, Linux, iOS, Android.
Download: www.bitcoin.com/choose-your-wallet/bitcoin-com-wallet

Jaxx (mobile, Chrome extension)

Jaxx has full Bitcoin Cash support (Android and Chrome extension).
Announcement: https://www.reddit.com/r/btc/comments/7bu6yo/jaxxio_now_supports_bitcoin_cash/

TSBW (online)

It's an open source wallet that can be used without opening an account. The easiest software to use with paper wallets.
WARNING: Developer accused of stealing funds. More info 1 More info 2
Bitcoin Cash: https://tsbw.io/bcc/

BitcoinCashTribe (online)

Works similar to TSBW.
Website: https://bitcoincashtribe.com/index.php

BitPie & Bither

They have full Bitcoin Cash support.
BitPie announcement: http://docs.bitpie.com/en/latest/bitpiebcc/index.html
Bither announcement: http://docs.bitpie.com/en/latest/bitherbcc/index.html

Exodus (lightweight)

One of the popular wallets that support Bitcoin Cash 100%.
Announcement: https://redd.it/766ojz
Download: https://www.exodus.io/releases/

Xapo (mobile)

You can withdraw all of your BCH at once before December 14th, or convert your BCH to BTC by one-click.
Announcement: https://blog.xapo.com/time-to-convert-your-bitcoin-cash-bch/

BitGo (online - Chrome extension)

BitGo supports Bitcoin Cash.
Announcement: https://blog.bitgo.com/bch-availability-c252727ea1be

StrongCoin (online)

StrongCoin supports Bitcoin Cash.
Announcement: https://strongcoin.com/blog/bitcoin_cash_is_now_supported_in_strongcoin_wallet

Parity Bitcoin (full node + lightweight)

Parity Bitcoin is a high performance wallet that can be run as a full node or a lightweight client. (Warning: Don't be confused with Parity! Parity Bitcoin is the Bitcoin/Bitcoin Cash version of Parity Ethereum client.)
Announcement: https://blog.parity.io/parity-bitcoin-is-now-supporting-segwit-segwit2x-and-bitcoin-cash/

Bitcore (full node)*

The 5.0 version which is coming soon, supports Bitcoin Cash if pointed to a Bitcoin Cash node. Doesn't have a user interface, not the best choice for a user. Useful APIs. (This is not a wallet for users! This is for developers!)
Announcement: https://news.bitcoin.com/now-bitcore-nodes-can-switch-to-any-bitcoin-implementation-even-forks/

Bitcoin Cash wallet (by Chris Pacia)

Changed version of OpenBazaar's SPVWallet for Bitcoin Cash. It has both GUI and command line support.
Downloads (Windows & Linux): https://github.com/cpacia/BitcoinCash-Wallet/releases/latest

Bitcoin Cash wallet (by HashEngineering) (Android)

Changed version of Andreas Schildbach's Bitcoin Wallet for Bitcoin Cash.
Announcement: https://www.reddit.com/r/btc/comments/72xost/beta_for_bitcoin_cash_wallet_for_android_recover/

StashWallet

A new HD Android wallet that fully supports Bitcoin Cash.
Website: https://stashcrypto.com

Freewallet (mobile)

A Bitcoin Cash Android wallet. WARNING: READ THIS
Website: https://freewallet.org
Google Play: https://play.google.com/store/apps/details?id=bcc.org.freewallet.app

 UnitWallet (mobile)

One of the Bitcoin-Cash-only wallets, fork of bread[wallet].
Website: https://www.unitwallet.co
Google Play: https://play.google.com/store/apps/details?id=com.unitwallet
Hardware Wallets

bitWallet (iOS)

A new Bitcoin wallet with Bitcoin Cash and a few altcoins support. It's good to keep in mind that it's not open source.
Website: http://www.sollico.com/bitwallet/
Download: https://itunes.apple.com/us/app/bitwallet/id777634714

Trezor

One of the major hardware wallets. Allows you to claim your Bitcoin Cash (They call it Bcash) if it's updated to latest firmware (1.5.1+). Fully supports Bitcoin Cash.
Trezor Guide: https://blog.trezor.io/claim-bcash-bitcoin-cash-bch-bcc-trezor-wallet-f0a810d5864a

KeepKey

One of the major hardware wallets + fully functioning Bitcoin Cash wallet.
https://coingeek.com/keepkey-wallets-now-support-bitcoin-cash/

Ledger

One of the major hardware wallets. Supports Bitcoin Cash if you update your firmware to latest version.
Guide: http://support.ledgerwallet.com/knowledge_base/topics/bitcoin-cash

Digital Bitbox

Its firmware supports Bitcoin Cash, but the desktop client doesn't. You can claim your Bitcoin Cash by sending all of them to your Bitcoin Cash wallet.
Cannot be used as a Bitcoin Cash hardware wallet.
Guide: https://digitalbitbox.com/bitcoincash

Paper Wallet

The safest Bitcoin/Bitcoin Cash hardware wallet. You can claim your Bitcoin Cash by importing to a Bitcoin Cash software.
You can create a paper wallet on cashaddress.org or bitaddress.org or bitcoin.com
All Bitcoin paper wallets are compatible to Bitcoin Cash as they both use the same private keys/addresses.

TODO: Add description:

https://mobi.me

https://www.wmtransfer.com/

https://bitcoin-india.org/

https://www.melis.io/

https://www.coin.space/

The wallets that don't support Bitcoin Cash aren't on the list.
List is sorted by various things.
*: Description will be updated.

Armory 0.96.2 also has bcash support.

For now it is 100% compatible so long as you follow these instructions: https://bitcointalk.org/index.php?topic=2070058.0

You can also create a paper wallet at https://cashaddress.org NOTE: I couldn't comment on the very well done post above since I Just signed up.

Try BitcoinCashTribe. Disclaimer: I am one of the devs there

BitGo's Chrome extension was sunset. There is however a SDK to interact with the API.


text:
Bitcoin core node not sending outbound connections only inbound traffic
My bitcoin core is not sending outbound connections. It's only getting inbound connections. Iv deleted the whole node then reinstalled it. Still it was only getting inbound connections. Iv checked firewall settings and the node is set to receive inbound and outbound connections. Does anyone know what problem might be? Could I just sync blockchain with only inbound connections?

I suspect you mean the other way around. What does "getpeerinfo" tell you?

No I mean it's getting inbound but no outbound connections.

That's very strange. How did you determine this is the case?

i clicked on the information tab and looked at the inbound and outbound connections and inbound had 12 connections and inbound showed 0 connections.

You made a typo there saying "inbound" twice. You may want to clarify.


text:
Where do I include my wallet address after finding the hash less than target - bitcoin
Please help me understand the logic behind mining a bitcoin from scratch. I want to create a bitcoin miner, it will not receive any blocks from any pools. All should be done inside the miner.
So, I have made some progress, I've coded with vb.net and successfully got a result of a hash (old example)
Version 2
Prev. Block 00000000000000000A2940884E0C3BC96510CAD11912A527E9D15DF42F0E1D67
Merkle Root 2E99F445C007A9158207CC30CEBAD2B3D26C45FDAB2EBDF50D261335FC00D92C
Time    12/16/14 18:05:40
Bits    404454260
Nonce   3225483075

Block Hash  000000000000000015A8D88216918C8DE090268A5E7F53FEEF72CD111F7F27FF

So, suppose old example is a real one, so, I want to know where do I include my bitcoin wallet address if I want to get the block reward to my wallet address? Should I have hashed the wallet address with the above and hash with the wallet and come up with a hash which is less than the target? Or after getting a good hash, just send data to blockchain with the wallet address to receive the block reward? or should I create some other hash with my wallet address? what should I do to include my wallet address in this?
pseudo code would also be nice If you can provide for me to understand how to include my wallet address.
my pseudo code upto now
**Step 1**
version -> convert to hex

Prev. Block -> convert to hex

Merkle Root -> convert to hex

Time  -> get unix time and convert to hex

Bits -> convert to hex

Nonce -> convert to hex

**step 2**
Add hex values of all the above and then hash it with Double SHA256 to receive the hash value.

**step3**
Check if the final hash value is less than the target

**step 4?** what should I do with the above hash? where should I include my wallet address?

Mining a valid block involves multiple steps.
To begin with, you must know which block you are mining on top of, which is specified by the previous block hash.
Then, you must obtain a merkle root that locks in a valid set of transactions. Usually, this is a set of transactions from the mempool + the coinbase transaction, such that there are no double spends or invalid transactions. These transactions are assembled into a merkle tree, from which the merkle root is placed into the block header.
The coinbase transaction in particular is important, as it must follow the coinbase transaction rules (inclusion of block height, correct output for the block reward, extraNonce). It must be placed as the first transaction in the block, and contains the output that sends the BTC to your wallet.
Finally, you must add in the other fields such as block version, time, nonce, etc.
This complete block header of 80 bytes is the payload that is hashed and compared against the target value. If your resulting hash does not meet the target requirements, you must change the nonce in the block header, the extraNonce in the coinbase transaction, or any of the transactions in your merkle tree to obtain a new merkle root, and hash the new block header. This process is repeated until you find a valid hash for the target.
In order, your approach would be like:

Get a list of transactions you'd like to include (this can be an empty list)
Select your wallet address to receive the block reward
Build a coinbase transaction that pays this reward to your selected address (plus any transaction fees)
Make the coinbase tx the first one in your list
Build a merkle tree from this list
Select the merkle root from this tree
Proceed as you're doing already

Did you see the pseudo code I wrote? can you simplify the steps as I did? because internet has a lot of essay like writings but no simplified steps. when we're coding we follow steps. can you please provide the simplified steps if you don't mind?

@PrettyGirl I've added a more concise list, but beyond this, I would recommend picking up a book like Mastering Bitcoin to understand what's going on - you seem to be missing a few basic concepts here that are resulting in a bunch of confusion

now I understood where my wallet address should include, it should include in the merkle root :) phew. Now I should focus on how to generate the merkle root which includes my wallet address. right? :)


text:
How to generate the hash of public key in Bitcoin
I'm trying to hash the public key with SHA256 and then ripemed160 and get the hash. but it gives the wrong hash
Public key:  2b4632d08485ff1df2db55b9dafd23347d1c47a457072a1e87be26896549a8737
Hash should be: 93ce48570b55c42c2af816aeaba06cfee1224fae
Imports System.Security.Cryptography
Imports System.Text
Imports System.Globalization
Imports System.Numerics

Private Function HexStringToByteArray(ByVal shex As String) As Byte()
    Dim B As Byte() = Enumerable.Range(0, shex.Length).Where(Function(x) x Mod 2 = 0).[Select](Function(x) Convert.ToByte(shex.Substring(x, 2), 16)).ToArray()
    Return Enumerable.Range(0, shex.Length).Where(Function(x) x Mod 2 = 0).[Select](Function(x) Convert.ToByte(shex.Substring(x, 2), 16)).ToArray()
End Function

Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click

Dim public_key as String = "2b4632d08485ff1df2db55b9dafd23347d1c47a457072a1e87be26896549a8737"
   Dim pubkey_hash As String

    Dim sha256 As SHA256 = SHA256Managed.Create()
    Dim bytes As Byte() = System.Text.Encoding.Unicode.GetBytes(public_key)
    Dim hash As Byte() = sha256.ComputeHash(bytes)
    Dim stringBuilder1 As New StringBuilder()

    For i As Integer = 0 To hash.Length - 1
        stringBuilder1.Append(hash(i).ToString("X2"))
    Next

    bytes = HexStringToByteArray(stringBuilder1.ToString())

    Dim ripemd160 As RIPEMD160 = RIPEMD160Managed.Create()
    Dim hash_160 As Byte() = ripemd160.ComputeHash(bytes)

    Dim stringBuilder2 As New StringBuilder()

    For i As Integer = 0 To hash_160.Length - 1
        stringBuilder2.Append(hash_160(i).ToString("X2"))
    Next

    Dim arr() As Char = stringBuilder2.ToString

    pubkey_hash = arr.tostring
    TextBox14.Text = pubkey_hash

   End Sub

and is there any way I can shorten this code? loops & if statements etc

I'm voting to close this question as off-topic because it is a general programming error specific to the language use, and unrelated to bitcoin apart from the fact that the data being processed is bitcoin keys.

@RaghavSood, it is related to bitcoin of course, it's the generation of the public key hashing of bitcoin to be used inside a transaction

where do I post bitcoin related code questions?

You can post here the code related to bitcoin code, but I think your title question should be "How to generate the hash of public key in Bitcoin'" and after you can explain your error

@vincenzopalazzo changed the title

Before try to understand your code you want to see how bitcoin create the hex from string, look the method HexStr https://github.com/bitcoin/bitcoin/blob/ab9de435880c9d77e4137b65050591ef2d14f809/src/util/strencodings.h#L125

@vincenzopalazzo code updated

I swear I've seen this (sort of strange) code example before.

I'm starting to wonder how difficult it is to find people who are helping others in this site.

I'm starting to wonder how difficult it is to find people who are helping others in this site

I don't have your same idea, but sorry for the delay in the answer but in Italy exist at the moment the alert "coronavirus".
My test to resolve your problem
I don't know the language of the code that you have public in the question but I have a project to decompiler script bitcoin but is in the start phases.
I'm answering with C++ code.
Exist two types of Public key, that is compressed and uncompressed, the difference is:

Compressed public key started with a flag "02" (I think this is your cases)
Uncompressed start with the flag "03"
If the you key start with "04" doesn't is the public key but is a P2PK script.

But a good reference that explains the compressed public key is this What is a compressed Bitcoin key?
So, I think your error is the public key input,your public key is 02b4632d08485ff1df2db55b9dafd23347d1c47a457072a1e87be26896549a8737 and not 2b4632d08485ff1df2db55b9dafd23347d1c47a457072a1e87be26896549a8737, you have lose the the part of flag of the compressed public key.
So, my C++ code to test my idea is this:
    cout << "Test for Bitcoin.stack question" << endl;
    cout << "Public Key: " << "02b4632d08485ff1df2db55b9dafd23347d1c47a457072a1e87be26896549a8737\n";
    string keyTmp = "02b4632d08485ff1df2db55b9dafd23347d1c47a457072a1e87be26896549a8737";
    string flag = keyTmp.substr(0, 2);
    if(flag == "02"){
          cout << "Compressed with y event";
    }else if(flag == "03"){
      cout << "Compressed with y odd";
    }else{
      assert(flag == "04");
    }
    Bytes bytesTmp = hexBytes(keyTmp.c_str());

    //SHA256
    Sha256Hash shaHash = Sha256::getHash(bytesTmp.data(), bytesTmp.size());
    uint8_t result[Ripemd160::HASH_LEN];
    Ripemd160::getHash(shaHash.value, sizeof(shaHash), result);

    cout << "Hash Public key: " << ToString(result);

The hash public key ofter run this code is: 93ce48570b55c42c2af816aeaba06cfee1224fae
References
The reference of the project are off-topics here but I think without it this post can be fake, so I'm adding the reference of the library used to implement my code in this answer.

Bitcoin-Cryptography-Library
decompiler-bitcoin-script: this is my start project to undestend how bitcoin script work, so you can found the idea if you want implement other feature inside your work.
Github gits code

wow, you solved it, thanks a lot, it was lacking the 'zero' infront of the key which it should have started as 02. :) , hope you'll be fine with the coronavirus you're facing at the moment :)

at the moment I'm fine, thanks, I'm happy that my solution resolved your problem. Have a good day.


text:
How to redeem a basic Tx?
Given a raw, standard Tx (wiki):
01000000

01
26c07ece0bce7cda0ccd14d99e205f118cde27e83dd75da7b141fe487b5528fb
00000000
8b
48304502202b7e37831273d74c8b5b1956c23e79acd660635a8d1063d413c50b218eb6bc8a022100a10a3a7b5aaa0f07827207daf81f718f51eeac96695cf1ef9f2020f21a0de02f01410452684bce6797a0a50d028e9632be0c2a7e5031b710972c2a3285520fb29fcd4ecfb5fc2bf86a1e7578e4f8a305eeb341d1c6fc0173e5837e2d3c7b178aade078
ffffffff

02

b06c191e01000000
19
76a9143564a74f9ddb4372301c49154605573d7d1a88fe88ac

00e1f50500000000
19
76a914010966776006953d5567439e5e39f86a0d273bee88ac
00000000

and a private key:
18E14A7B6A307F426A94F8114701E7C8E774E7F9A47E2C2035DB29A206321725

How does one construct a new transaction to redeem the coin from the second output? I've been trying to figure this out for a long while using etotheipi's diagram, but can't seem to grasp how a proper transaction is to be created. A step-by-step guide would be welcome.

@Daniel, i'm not certain, but this might be because bitcoind signrawtransaction requires a real previous output transaction in the blockchain in order to calculate the funds? the hash for the transaction given in this question is f2b3eb2deb76566e7324307cd47c35eeb88413f971d88519859b1834307ecfec, which blockexplorer.com says does not exist

@mulllhausen How was this done if the txid is wrong?

In this answer, I will go through the steps necessary to redeem the second output of the transaction listed above. The answer will be limited to redeeming an output of the particular type present in this transaction (an output which requires providing a new transaction signed with a private key whose corresponding public key hashes to the hash in the script of the output in question), as this answer is already fairly long, even without taking into account other output types.
Short summary: We begin by constructing a new transaction, with a scriptSig containing the scriptPubKey of the output we want to redeem. The scriptPubKey of this transaction will contain a script that pays to a hash of a public key (Bitcoin address). We perform a double-SHA256 hash on this transaction with the four-byte hash code type SIGHASH_ALL appended to the end. We sign this hash with the private key supplied above. The scriptSig of this new transaction is then replaced with a script that first pushes the DER-encoded signature, plus the one-byte hash code type SIGHASH_ALL, to the stack, followed by the DER-encoded private key's corresponding public key.
Step-by-step description:
We start creating a new raw transaction which we hash and sign.

Add four-byte version field: 01000000
One-byte varint specifying the number of inputs: 01
32-byte hash of the transaction from which we want to redeem an output: eccf7e3034189b851985d871f91384b8ee357cd47c3024736e5676eb2debb3f2
Four-byte field denoting the output index we want to redeem from the transaction with the above hash (output number 2 = output index 1): 01000000
Now comes the scriptSig. For the purpose of signing the transaction, this is temporarily filled with the scriptPubKey of the output we want to redeem. First we write a one-byte varint which denotes the length of the scriptSig (0x19 = 25 bytes): 19
Then we write the temporary scriptSig which, again, is the scriptPubKey of the output we want to redeem: 76a914010966776006953d5567439e5e39f86a0d273bee88ac
Then we write a four-byte field denoting the sequence. This is currently always set to 0xffffffff: ffffffff
Next comes a one-byte varint containing the number of outputs in our new transaction. We will set this to 1 in this example: 01
We then write an 8-byte field (64 bit integer) containing the amount we want to redeem from the specified output. I will set this to the total amount available in the output minus a fee of 0.001 BTC (0.999 BTC, or 99900000 Satoshis): 605af40500000000
Then we start writing our transaction's output. We start with a one-byte varint denoting the length of the output script (0x19 or 25 bytes): 19
Then the actual output script: 76a914097072524438d003d23a2f23edb65aae1bb3e46988ac
Then we write the four-byte "lock time" field: 00000000
And at last, we write a four-byte "hash code type" (1 in our case): 01000000
We now have the following raw transaction data:
01000000
01
eccf7e3034189b851985d871f91384b8ee357cd47c3024736e5676eb2debb3f2
01000000
19
76a914010966776006953d5567439e5e39f86a0d273bee88ac
ffffffff
01
605af40500000000
19
76a914097072524438d003d23a2f23edb65aae1bb3e46988ac
00000000
01000000

(signing stage) Now we double-SHA256 hash this entire structure, which yields the hash 9302bda273a887cb40c13e02a50b4071a31fd3aae3ae04021b0b843dd61ad18e
We then create a public/private key pair out of the provided private key. We sign the hash from step 14 with the private key, which yields the following DER-encoded signature (this signature will be different in your case): 30460221009e0339f72c793a89e664a8a932df073962a3f84eda0bd9e02084a6a9567f75aa022100bd9cbaca2e5ec195751efdfac164b76250b1e21302e51ca86dd7ebd7020cdc06 To this signature we append the one-byte hash code type: 01. The public key is: 0450863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b23522cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6
We construct the final scriptSig by concatenating:

One-byte script OPCODE containing the length of the DER-encoded signature plus 1 (the length of the one-byte hash code type)
The actual DER-encoded signature plus the one-byte hash code type
One-byte script OPCODE containing the length of the public key
The actual public key

We then replace the one-byte, varint length-field from step 5 with the length of the data from step 16. The length is 140 bytes, or 0x8C bytes: 8c
And we replace the temporary scriptSig from Step 6 with the data structure constructed in step 16. This becomes: 4930460221009e0339f72c793a89e664a8a932df073962a3f84eda0bd9e02084a6a9567f75aa022100bd9cbaca2e5ec195751efdfac164b76250b1e21302e51ca86dd7ebd7020cdc0601410450863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b23522cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6
We finish off by removing the four-byte hash code type we added in step 13, and we end up with the following stream of bytes, which is the final transaction:
01000000
01
eccf7e3034189b851985d871f91384b8ee357cd47c3024736e5676eb2debb3f2
01000000
8c
4930460221009e0339f72c793a89e664a8a932df073962a3f84eda0bd9e02084a6a9567f75aa022100bd9cbaca2e5ec195751efdfac164b76250b1e21302e51ca86dd7ebd7020cdc0601410450863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b23522cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6
ffffffff
01
605af40500000000
19
76a914097072524438d003d23a2f23edb65aae1bb3e46988ac
00000000

Python example code:
I have created an example Python script which does all the above. It is intentionally as verbose as possible, and heavily commented, with as few functions as possible, in order to resemble the step-by-step guide above. The number of code lines can easily be reduced to one half, but I choose to post it in this verbose format as I judge that it's the easiest to follow (ie. no 'jumping' backwards and forwards through functions). The script contains 76 non-empty, non-comment lines.
The script depends on bitcointools (for serializing and deserializing transactions, and base58 encoding/decoding) and ecdsa_ssl.py from my fork of joric's brutus repository (for constructing public/private EC key pairs and ECDSA signing). The easiest way to get the script to run is to clone bitcointools into a folder, and put ecdsa_ssl.py from the above URL in the same folder along with this script, and executing the script from there.
You will want to replace the address in the SEND_TO_ADDRESS variable in this script with the address you want the coins sent to, unless you're feeling generous :).

#bitcointools
from deserialize import parse_Transaction, opcodes
from BCDataStream import BCDataStream
from base58 import bc_address_to_hash_160, b58decode, public_key_to_bc_address, hash_160_to_bc_address

import ecdsa_ssl

import Crypto.Hash.SHA256 as sha256
import Crypto.Random

#transaction, from which we want to redeem an output
HEX_TRANSACTION="010000000126c07ece0bce7cda0ccd14d99e205f118cde27e83dd75da7b141fe487b5528fb000000008b48304502202b7e37831273d74c8b5b1956c23e79acd660635a8d1063d413c50b218eb6bc8a022100a10a3a7b5aaa0f07827207daf81f718f51eeac96695cf1ef9f2020f21a0de02f01410452684bce6797a0a50d028e9632be0c2a7e5031b710972c2a3285520fb29fcd4ecfb5fc2bf86a1e7578e4f8a305eeb341d1c6fc0173e5837e2d3c7b178aade078ffffffff02b06c191e010000001976a9143564a74f9ddb4372301c49154605573d7d1a88fe88ac00e1f505000000001976a914010966776006953d5567439e5e39f86a0d273bee88ac00000000"
#output to redeem. must exist in HEX_TRANSACTION
OUTPUT_INDEX=1
#address we want to send the redeemed coins to.
#REPLACE WITH YOUR OWN ADDRESS, unless you're feeling generous
SEND_TO_ADDRESS="1L4xtXCdJNiYnyqE6UsB8KSJvqEuXjz6aK"
#fee we want to pay (in BTC)
TX_FEE=0.001
#constant that defines the number of Satoshis per BTC
COIN=100000000
#constant used to determine which part of the transaction is hashed.
SIGHASH_ALL=1
#private key whose public key hashes to the hash contained in scriptPubKey of output number *OUTPUT_INDEX* in the transaction described in HEX_TRANSACTION
PRIVATE_KEY=0x18E14A7B6A307F426A94F8114701E7C8E774E7F9A47E2C2035DB29A206321725

def dsha256(data):
   return sha256.new(sha256.new(data).digest()).digest()

tx_data=HEX_TRANSACTION.decode('hex_codec')
tx_hash=dsha256(tx_data)

#here we use bitcointools to parse a transaction. this gives easy access to the various fields of the transaction from which we want to redeem an output
stream = BCDataStream()
stream.write(tx_data)
tx_info = parse_Transaction(stream)

if len(tx_info['txOut']) < (OUTPUT_INDEX+1):
   raise RuntimeError, "there are only %d output(s) in the transaction you're trying to redeem from. you want to redeem output index %d" % (len(tx_info['txOut']), OUTPUT_INDEX)

#this dictionary is used to store the values of the various transaction fields
#  this is useful because we need to construct one transaction to hash and sign
#  and another that will be the final transaction
tx_fields = {}

##here we start creating the transaction that we hash and sign
sign_tx = BCDataStream()
##first we write the version number, which is 1
tx_fields['version'] = 1
sign_tx.write_int32(tx_fields['version'])
##then we write the number of transaction inputs, which is one
tx_fields['num_txin'] = 1
sign_tx.write_compact_size(tx_fields['num_txin'])

##then we write the actual transaction data
#'prevout_hash'
tx_fields['prevout_hash'] = tx_hash
sign_tx.write(tx_fields['prevout_hash']) #hash of the the transaction from which we want to redeem an output
#'prevout_n'
tx_fields['output_index'] = OUTPUT_INDEX
sign_tx.write_uint32(tx_fields['output_index']) #which output of the transaction with tx id 'prevout_hash' do we want to redeem?

##next comes the part of the transaction input. here we place the script of the *output* that we want to redeem
tx_fields['scriptSigHash'] = tx_info['txOut'][OUTPUT_INDEX]['scriptPubKey']
#first write the size
sign_tx.write_compact_size(len(tx_fields['scriptSigHash']))
#then the data
sign_tx.write(tx_fields['scriptSigHash'])

#'sequence'
tx_fields['sequence'] = 0xffffffff
sign_tx.write_uint32(tx_fields['sequence'])

##then we write the number of transaction outputs. we'll just use a single output in this example
tx_fields['num_txout'] = 1
sign_tx.write_compact_size(tx_fields['num_txout'])
##then we write the actual transaction output data
#we'll redeem everything from the original output minus TX_FEE
tx_fields['value'] = tx_info['txOut'][OUTPUT_INDEX]['value']-(TX_FEE*COIN)
sign_tx.write_int64(tx_fields['value'])
##this is where our scriptPubKey goes (a script that pays out to an address)
#we want the following script:
#"OP_DUP OP_HASH160  OP_EQUALVERIFY OP_CHECKSIG"
address_hash = bc_address_to_hash_160(SEND_TO_ADDRESS)
#chr(20) is the length of the address_hash (20 bytes or 160 bits)
scriptPubKey = chr(opcodes.OP_DUP) + chr(opcodes.OP_HASH160) + \
   chr(20) + address_hash + chr(opcodes.OP_EQUALVERIFY) + chr(opcodes.OP_CHECKSIG)
#first write the length of this lump of data
tx_fields['scriptPubKey'] = scriptPubKey
sign_tx.write_compact_size(len(tx_fields['scriptPubKey']))
#then the data
sign_tx.write(tx_fields['scriptPubKey'])

#write locktime (0)
tx_fields['locktime'] = 0
sign_tx.write_uint32(tx_fields['locktime'])
#and hash code type (1)
tx_fields['hash_type'] = SIGHASH_ALL
sign_tx.write_int32(tx_fields['hash_type'])

#then we obtain the hash of the signature-less transaction (the hash that we sign using our private key)
hash_scriptless = dsha256(sign_tx.input)

##now we begin with the ECDSA stuff.
## we create a private key from the provided private key data, and sign hash_scriptless with it
## we also check that the private key's corresponding public key can actually redeem the specified output

k = ecdsa_ssl.KEY()
k.generate(('%064x' % PRIVATE_KEY).decode('hex'))

#here we retrieve the public key data generated from the supplied private key
pubkey_data = k.get_pubkey()
#then we create a signature over the hash of the signature-less transaction
sig_data=k.sign(hash_scriptless)
#a one byte "hash type" is appended to the end of the signature (https://en.bitcoin.it/wiki/OP_CHECKSIG)
sig_data = sig_data + chr(SIGHASH_ALL)

#let's check that the provided privat key can actually redeem the output in question
if (bc_address_to_hash_160(public_key_to_bc_address(pubkey_data)) != tx_info['txOut'][OUTPUT_INDEX]['scriptPubKey'][3:-2]):
   bytes = b58decode(SEND_TO_ADDRESS, 25)
   raise RuntimeError, "The supplied private key cannot be used to redeem output index %d\nYou need to supply the private key for address %s" % \
                           (OUTPUT_INDEX, hash_160_to_bc_address(tx_info['txOut'][OUTPUT_INDEX]['scriptPubKey'][3:-2], bytes[0]))

##now we begin creating the final transaction. this is a duplicate of the signature-less transaction,
## with the scriptSig filled out with a script that pushes the signature plus one-byte hash code type, and public key from above, to the stack

final_tx = BCDataStream()
final_tx.write_int32(tx_fields['version'])
final_tx.write_compact_size(tx_fields['num_txin'])
final_tx.write(tx_fields['prevout_hash'])
final_tx.write_uint32(tx_fields['output_index'])

##now we need to write the actual scriptSig.
## this consists of the DER-encoded values r and s from the signature, a one-byte hash code type, and the public key in uncompressed format
## we also need to prepend the length of these two data pieces (encoded as a single byte
## containing the length), before each data piece. this length is a script opcode that tells the
## Bitcoin script interpreter to push the x following bytes onto the stack

scriptSig = chr(len(sig_data)) + sig_data + chr(len(pubkey_data)) + pubkey_data
#first write the length of this data
final_tx.write_compact_size(len(scriptSig))
#then the data
final_tx.write(scriptSig)

##and then we simply write the same data after the scriptSig that is in the signature-less transaction,
#  leaving out the four-byte hash code type (as this is encoded in the single byte following the signature data)

final_tx.write_uint32(tx_fields['sequence'])
final_tx.write_compact_size(tx_fields['num_txout'])
final_tx.write_int64(tx_fields['value'])
final_tx.write_compact_size(len(tx_fields['scriptPubKey']))
final_tx.write(tx_fields['scriptPubKey'])
final_tx.write_uint32(tx_fields['locktime'])

#prints out the final transaction in hex format (can be used as an argument to bitcoind's sendrawtransaction)
print final_tx.input.encode('hex')

Are you sure step 11 is correct? It just shows the origin address. Shouldn't that be a script like "OP_DUP OP_HASH160 destination_address_in_hash_160_format OP_EQUALVERIFY OP_CHECKSIG"? Where OP_DUP is replaced with "76", etc, as described here.

I'm stuck at step 15... Any idea what I might be doing wrong? http://bitcoin.stackexchange.com/questions/10784/how-to-sign-a-transaction-hash-in-ruby-or-python

Regarding my first comment, I just noticed that the address is indeed wrapped in 76 a9 and 88 ac. So it sends everything back to the origin.

No it doesn't send it back, it sends it to 1runeksijzfVxyrpiyCY2LCBvYsSiFsCm.

@SjorsProvoost As mentioned, the script redeems output number OUTPUT_INDEX from the transaction described in hexadecimal format in HEX_TRANSACTION and sends it to the address contained in SEND_TO_ADDRESS.

@Daniel Yes. ECDSA signatures require a random number. Bad things happen if it's not random.

If you want to redeem a transaction with multiple inputs, how do you generate the hash that you have to sign for each input? Is it the same hash for all of them?

@runeks > "[...] replace the address in the SEND_TO_ADDRESS variable [...] unless you're feeling generous :)" Just for the records, it seems that several souls felt generous after reading your answer. It is amazing the power of bitcoin.

The "generate" step generates a private key object from the hex data in PRIVATE_KEY. So, essentially, it's just parsing 32 bytes of hex-encoded data into a private key.

Adding to the elegant solution given by runeks: in case of multiple inputs(which is quite common), we construct two different tx  repeating from step 1-13 . in first tx we keep input 2 as 00 and in second tx we keep input 1 as 00. then we sign both these tx and replace them in the two inputs, generating 2 input n output signed tx.

point 3 is in Little Endian

Gavin's bitcointools has been dead since at least Nov 2017. Runeks has an indirect fork at https://github.com/runeksvendsen/bitcointools/ which does seem to operate as required.

@blockwala what do you mean by '00' in a given input? just replacing the scriptsig, or replacing the hole input structure (previos tx hash, previous output index, script length and script sig and sequence)?

This gist, partially based on the answer by Runeks, shows how to transfer 0.01 bitcoins in Ruby. It fetches information from the previous transaction from Blockchain.info, so you just need to feed it your private key and address (the latter being redundant but useful for the demonstration). I added a lot of comments to explain the steps involved.

Once you know the Transaction ID, the vout, the scriptPubKey of that transaction, and the WIF encoded private key corresponding to the public key hashed to yield the address, you can create a raw transaction, and sign it, without being online.
I have written a PHP library to deal with raw transactions (amongst other bitcoin functionality). Here's how you would redeem a regular transaction: https://github.com/Bit-Wasp/bitcoin-lib-php It needs an update to support P2SH signatures, but it'll redeem a regular transaction just fine.


text:
What if a malicious owns more than half of the nodes in bitcoin network?
my question is simply What if a malicious owns more than half of the nodes in bitcoin network? she can simply fraud then. isn't there any algorithm to prevent someone from having more than half of nodes in bitcoin network?

maybe you mean "nodes in bitcoin network" but not not in blockchain?

Yes you are right, I mean in bitcoin network @Zergatul

No. The 51% hack is considered one of the main ways a hacker could control the network. However, it is almost completely implausible because of the sheer amount of power that would be required to have 51%. For example, the total hash rate of the network is currently 6.09 Exahashes per second. So, if a hacker wanted to take control of the network, he would need to buy about 6.1 Exahashes per second of hash power. An antminer S9, for 3,000 dollars, gives you 14 terrahashes per second. Thus, the supposed hacker would need to buy 435,000 Antminer S9's which would cost 1.305 billion. That's not even considering the growth rate of the network and the sheer amount of space and energy required to host all of those Antminers.

No need by buy ASICs to do 51%-attack. Just create a mining pool with 5% bonus available for withdraw after a year of mining. :)

I believe the question was referring to number of nodes not mining power?

I should have clarified it, yes. But the mining power is the number that actually matters I believe.

Yes you are correct, but I will post another answer to clarify that for everyone

In verifying transactions, it is not the number of nodes that an attacker owns, but the hashing power which matters. Having many bad nodes (Sybil attack) could affect the network in other ways such as not relaying all transactions, etc, but you can't trick an honest node into accepting a different blockchain without mining enough blocks for it to become the largest chain in the network, and that requires more than 51% of the hashing power to race against the rest of the network.


text:
Why participants transact bitcoins use pseudonyms rather than persistent real-world identitie?
I recently read an article that tries to make reveal the identity of participants which transact bitcoins. my question is why participants use pseudonym instead of real-world identities and cause transaction be anonymous.
what is the use of this anonymity and why is blockchain structure designed in this form? wasn't it more safe if the identity of participants was clear?

have you read the bitcoin whitepaper?

yes, I have read some, but couldn't find an answer to my question @renlord

Data privacy is one of the key designs of Blockchain technology.
If you expose the identity of the participants you expose all the transactions to the non-participants in those transacations which can make the entire system useless by way of generating all the data privacy issues such as Information mishandling, snooping and location tracking.

authors: Oлекс Ианков


text:
Is mining a fair mechanism in blockchain network?
As we know, propagation of a new block in blockchain network has some delay and many nodes receive the new block later. so if it is that the first one who finds the nonce properly wins the block can we say that the mechanism of mining is not fair enough (Because of delay in propagation of a block some blocks receive the block sooner and have more time to calculate the nonce)?

I don't understand the reasoning in your question.

I edited the question and added the bold sentence to explain the reasoning. @PieterWuille

Considering that a block is mined on average every 10 minutes and that the average time to propagate to all nodes is 12.6 seconds, I think it is pretty fair.
We could also guess that the big miner have incentives to get the newly mined hash very fast so it must be lower than 12.6 for them.

so you mean 12.6 seconds in proportion to 10 minutest is not very much and can be negligible?

@ShakibaZar Yes, and for the ones that really care it is lower than 12.6 seconds

how it can be lower than 12.6 for the ones who care? do they have any role in choosing when to receive the block?

@ShakibaZar big miners have resources so they can use Satellite internet for example, which will tell them about the new valid block very fast no matter on which continent it happened


text:
Transactions tree not list?
I try to understand how Bitcoin handles change or the combination of multiple transactions to provide sufficient funds for a given price.
Bitcoin transactions contain an array for the input transactions and an array for the UTXO outputs (vout).
For example: If I'm Frank and I send Charlie 1 BTC with an input transaction which holds 1.2 BTC, does that mean, that my next TX using the 0.2 BTC and Charlies TX using the 1 BTC form two new TX chains?

Or would I just reference the latest TX in the chain of transactions, containing both parts of the 1.2 BTC and sometimes the 0.2 BTC is referenced as VIN element and sometimes the 1.0 BTC?

Can you clarify what you mean by "same list"? What list are you talking about?

@AndrewChow I mean if there spawns a new chain of TXs, one referencing the 0.2 BTC, one referencing the 1.0 BTC or if both are referenced in the same chain of transactions.

Possible duplicate of How does change work in a bitcoin transaction?

In your example, there will be two chains of transactions as different transactions are spending the outputs of one transaction. Because there are two distinct transactions spending from those two outputs, there are now two transaction chains coming from one transaction. However this does not mean that the transaction chains won't converge or meet. Calling it a transaction chain or a tree isn't really accurate. It's actually a directed acyclic graph.

You're right. Makes sense!


text:
Blockchain download stuck on Bitcoin core wallet
The caching up process was progressing (slowly but still progressing) until it got stuck after processing 436820 blocks:
https://i.sstatic.net/c8h0z.png
3 days after, I'm still at 70.76%
Says I'm connected though (to 8 peers)
Any clue?
(debug.log: https://pastebin.com/QSaUY2gm)

Can you post the debug.log file?

related: What can I do when the blockchain synchronization is stuck at a specific block?

That's very weird. Your peers are syncronized; there's no error suggesting that your node rejected a block; and it was open for 2 minutes without validating any more blocks.


text:
Why was/is Bitcoin written in C++ instead of C?
Why C++ and not C? Are there some features of C++ not present in C required for Bitcoin to function as it does?
I can see that a similar question has been asked before but I am more curious as to the specific features of C++ meaning that it was chosen for for Bitcoin's codebase instead of C (under the very large assumption it wasn't written in C++ purely as Satoshi's favourite language).

Maybe yes or maybe not, that is, there is no specific reason sometimes for choosing the programming language (This in general) especially in open source projects the language depends a lot on who is part of the project.
Surely C ++ is a ubiquitous language nowadays, just think that java and python were born from this language.
In my opinion, in first the choice of C ++ has been given a lot since the presentation of the idiom to objects, we say that C does not have the classes it is not possible to realize many techniques that are in the everyday reality for current programmers.
Then just think that in 2009 all these "Go" languages were not present.
So my definitive answer is:
"I think that in the periods when bitcoin core was released and in the previous one in which C ++ was developed it was a reference language for object-oriented programming and it was probably better to use an object-oriented language for technical reasons. as hereditary polymorphism.
I believe that this code cannot be written in C above all the transactions
look here in my fork where I'm studying bitcoin core Click me
This is just my thought, I may be wrong.
Sorry for my terrible English but I'm learning

Bitcoin Core hardly uses polymorphism. There are plenty of reasons to prefer C++ over C (such as avoiding manual memory management).

@PieterWuille feel free to adjust my answer


text:
How are my mining rewards calculated?
I saw some videos where a single home laptop can run a mining software and collect fractions of Bitcoins every now and then. However, a mining reward is a full 25 BTC. My questions:

Does that mean that the mining software joins my laptop to a pool?
If yes, then if I get fractions of a BTC over time, does that mean that my pool succeeded in resolving a block and collected 25 BTC?
If yes, how is the reward distributed?

How the reward is divided depends on the pool. But there is absolutely no point in mining bitcoins on a laptop. You will never pay a thousandth of your costs.

This is a hypothetical question, just to understand the mechanisms. No intention to mine.

you may want to read Andreas' book on mastering bitcoin, at the end of chapter 8. It is online available (here: https://www.safaribooksonline.com/library/view/mastering-bitcoin/9781491902639/) and there are many translations.

pebwindkraft first comment above directed me to the answer: the section about pool mining says it all.

In a nutshell:
You point your mining software at a pool
Your laptop hashes the candidate block sending results that are close to a solution to the pool every now an then.
If the pool is of proportional type, you will get your proportion of the reward based on your portion of contributed hash rate /work.
There are other types of pools and their payout algorithms will vary.


text:
How to figure from logs if solomining the wallet fails (linux)?
Is there a way to figure from logfiles if mining on a coin(d) ie bitcoind client on a linux OS fails?

Fails, or just doesn't succeed finding a block?

Lets assume there should be multiple blocks mined already. Isnt there a way to see from logfiles if something fails to credit mined blocks or what else can go wrong.


text:
Building Vertcoin ERROR - makefile.unix:219: recipe for target 'vertcoind' failed
Building Vertcoin on Xubuntu 16.10 build error:
Last lines of the output:
obj/util.o: In function `boost::program_options::detail::basic_config_file_iterator<char>::getline(std::string&)':
/usr/include/boost/program_options/detail/config_file.hpp:171: undefined reference to `boost::program_options::to_internal(std::string const&)'
obj/util.o: In function `boost::program_options::detail::basic_config_file_iterator<char>::basic_config_file_iterator(std::istream&, std::set<std::string, std::less<std::string>, std::allocator<std::string> > const&, bool)':
/usr/include/boost/program_options/detail/config_file.hpp:155: undefined reference to `boost::program_options::detail::common_config_file_iterator::common_config_file_iterator(std::set<std::string, std::less<std::string>, std::allocator<std::string> > const&, bool)'
collect2: error: ld returned 1 exit status
makefile.unix:219: recipe for target 'vertcoind' failed
make: *** [vertcoind] Error 1

Pastebin.com link of the full output
Additional info:
$ g++ --version
g++ (Ubuntu 4.8.5-4ubuntu4) 4.8.5

$ gcc --version
gcc (Ubuntu 4.8.5-4ubuntu4) 4.8.5

$ uname -a
Linux droidx 4.8.0-26-generic #28-Ubuntu SMP Tue Oct 18 14:39:52 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

$ cat /usr/include/boost/version.hpp | grep "BOOST_LIB_VERSION"
//  BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION
#define BOOST_LIB_VERSION "1_61"

i switched the OS meanwhile, leaving the question open  as it appears to be a general problem running the 16.10 distros.


text:
How to convert a bitcoin address to the respective hash160 using bash?
I want to convert a list of bitcoin addresses to their respective hash160 values as illustrated using bash :

came across this repo https://github.com/cryptocoinjs/bs58  which does the job but still have no clue how todo it without such tool in bash.

Are you looking for a built-in tool package with your O.S.? Because you could use that node library in bash.

i did but its incredibly slow - if i understand the process i can rewrite it for bash which would be optimal.


text:
cgminer Rejected as lowdifficulty
I got an issue with cgminer constantly rejecting shares. How can I fix it?
Here's example rejection (note that Diff jumps - sometimes it's 6/1 sometimes it's 1/1) :
[2013-04-09 14:24:05] Rejected fe26cac1 Diff 4/1 GPU 0 (lowdifficulty)

Here's the .bat file I use:
cgminer --scrypt -o eu-stratum.btcguild.com:3333 -u MyUser -p 123

My OS is Win 7 32 bit.

What is your share difficulty set to in the btcguild settings?

Under 2 GH/s (I got weak PC here where I try to set it up)

I just tried 8-16 and 16-32 - both fail with the same result. What's weird is that I have cgminer setup on another PC with much better GPU and it works flawlessly there with difficulty set to 8-16.

To closevoters:  this question is on topic as per the current FAQ.  If we want it to be off-topic we should clarify the wording there.

I had this issue also the fix for me was  adding--scrypt -o to the beginning so it look like this :
--scrypt -o stratum+tcp://stratum.scryptguild.com:3333  -u iwantcoins_nick -p nopw --load-balance

Also worth trying to tune your other GPU settings, this will increase your hashrate, and hopefully reduce your rejected share rate.


text:
Why is it important for checkpoints to contain well-formed blocks?
In the source code of the standard client, checkpoints.cpp has this comment:
//
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
//   (no blocks before with a timestamp after, none after with
//    timestamp before)
// + Contains no strange transactions
//

Why should it matter? Presumably the client would have accepted it anyway if they were downloading it normally, and if you were to specify a later block, that would still force the client to download the strange block. I don't understand the point of this restriction.

There are two things :

Why are checkpoints needed in the first place,
Why do the checkpointed blocks need to adhere to the standards you are quoting (which is your question)

I don't think checkpoints are required at all or useful in any way, there has been some debate around this, the fact remains that checkpoints are still present in the Satoshi implementation.
I believe there is no specific reason why the checkpointed blocks must have "reasonable timestamps" or not contain "strange transactions". The only reason I can think of is to not confuse someone reviewing the checkpointed blocks. As you said, such a block would still be downloaded and properly validated. So I think it has more to do with cosmetics and clarity than with an actual technical constraint.
(Also note that "strange transactions" doesn't really mean much, it does not seem to be defined as a transaction that passes the IsStandard check)

"I don't think checkpoints are required at all or useful in any way," I actually disagree on this point, as my client grabs the blockchain quite a lot faster when getting blocks before a checkpoint.

AFAIK checkpoints are not used to improve performance of the initial chain download, and even if it did your client would still have to scan each single block and look at each single transaction in it in order to find transactions that are relevant to its wallet.

True, but it doesn't need to verify the signatures. I don't know how significant that is performance-wise.

Verifying the signature takes a negligible amount of time, it's looking the inputs up that does. The initial download performance is I/O bound, not CPU bound.

That makes sense. You mention that the IsStandard check fails on transactions in some checkpoints. Do you have any examples?

I never said that :)

let us continue this discussion in chat


text:
Speeding up bitcoin transactions?
I am writing an app which trades bitcoins and one of the biggest problems I have run into is that it takes so long to move them from one wallet to another. I thinks it due too mtgox and other sites using a 6 confirmation system before registering that data.
I have two thoughts on how the time might be brought down and I am wondering how feasible each is.

Process my own bitcoin transactions. Would it be possible to route my transactions through my own computer so that it gets top priority?
Use fewer conformations before excepting a transaction as complete. Would the system allow me to use a bitcoin if it has only has 4 conformations?

Is there another way that I'm not thinking of?

The security of the Bitcoin system depends on time passed since the transaction was included in a block.  Let's call this confirmation 1.

Are you having trouble getting your trades into a block, or want to have more confirmations?

The fact remains is that you should wait 1 hour after the transaction is included in a block before spending that output.  That one hour just happens to roughly correspond with 6 blocks.
So why do we wait 1 hour? It's because we want to make reasonably sure that no one out there has a computer strong enough to spend the output twice, and causing a split in the ledger.
I wouldn't plan on basing my business on short block times, and would instead only use the block chain for deposits and withdrawals from your private system.
If you're having trouble getting your Tx included in a block the easy solution for that is to pay transaction fees, or run a private mining rig that will accept such transactions.

I was under the impression that it was not about time, and more about lodging it in the blockchain. But are you saying that I can in fact use my own rig to speed up transactions?

The only reason you would need your own rig is if no other pool accepted your transaction.  Do you intend to not pay a network fee?

The network fee is trivial. My goal is to minimize the time it takes me to send bitcoins from one of my wallets to another. When my transaction gets sent to a pool I assume its put into some queue and then gets executed when its my turn. I'm wondering If I had my own minner, would I be able to make transactions faster by essentially cutting line?

A single miner won't do it, but may help. The best bet is to send the Tx to a large pool, and possibly add miners to it.

For what it's worth, I did send money from Mt Gox, to myself, and after 1 confirmation I sent it to another user. Example:  Part 1 c99186ea5285166ea8ad75388f42acd60990b8748a45d1ff0f45271a1cb6f749 part 2 4d6d4eedb8d98c626bd1450d45055fa610cd05494c79f7e655043456e38a6b5d

assuming its a good miner perhaps this one with a 25 GH/s

That is a good one, but it won't reliably get you always in the front of the line (for free).  The best bet for you sounds like just pay the Tx fee and work with software that doesn't require 6 confirmations.  If you really want a miner check here for my ebay listings ;)

let us continue this discussion in chat

thanks. And how were you able to get access to you bitcoin after 1 conformation on mtgox? It wont even register for me till all 6 are done


text:
Why does each block store a Merkle root?
I understand how a Merkle root is calculated and stored in the block. But how do miners verify a transaction using the Merkle root?
Here are 18 conditions that verify a transaction. None of them uses Merkle root.

possible duplicate of What is the Merkle root?

Merkle roots do not verify transactions, they verify a set of transactions.  Transaction ID's are hashes of the transaction, and the Merkle tree is constructed from these hashes.  It means that if a single detail in any of the transactions changes, so does the Merkle root.  It also means that if the exact same transactions are listed in a different order, the Merkle root will also change.
So the Merkle root is cryptographic proof of which transactions are in the block, and which order they are in.  It provides a convenient piece of information to be included in the block header which is then hashed and included in the next block header.  Without the Merkle root in the block header, we would have no cryptographic proof of which transactions are included in a block, nor proof that their contents haven't been tampered with.
Using a Merkle tree is preferable over a hash chain or a hash of concatenated transactions because it allows for a much quicker and simpler test of whether a particular transaction is included in the set.  For more details, see the section on Merkle trees in the Developer's Guide.

This answer would be improved if it mentioned the Merkle tree's use for membership proofs which is why a Merkle tree is used instead of i.e. just a digest over all transactions. See Alin Tomescu's answer.

@Murch, I updated this to contain why other hashing schemes weren't used.

Merkle roots are stored in Bitcoin block headers so as to enable efficient membership proofs for transactions in a block, which are necessary for Simple Verified Payment verification (SPV) nodes that only store block headers and not block contents.
It is misleading to say that "Without the Merkle root in the block header, we would have no cryptographic proof of which transactions are included in a block, nor proof that their contents haven't been tampered with."
We can always just hash-chain transactions together and store a hash-chain root in the block header, for example. (Or, we can just concatenate all TXIDs together and store that hash in the header.)
However, that would not be as efficient: membership proofs with respect to a hash chain are O(n) when there are n transactions in the chain, versus O(\log{n}) proofs w.r.t. a Merkle tree.
Much later edit: I suppose no one actually answered your question: "But how do miners verify a transaction using the Merkle root?".
As I understand your question, the answer is they don't use the Merkle tree. Miners, just like full nodes on the P2P network, receive new transactions from other full nodes and verify them by checking their digital signature and that they spend valid coins (pretty much as described in your link). Merkle trees are not involved at this point. Later on, the miner takes all the verified transactions and creates a Merkle tree on top of them. As more transactions come to the miner, the miner verifies them and adds them to the Merkle tree.
Why are things added to the Merkle tree by the miner? Again, as I describe above, the only reason we have Merkle trees is so SPV nodes can efficiently verify that miners verified the transactions in the block.
There is one scenario one might describe as "miners verify a transaction using the Merkle root" though I wouldn't use that phrasing: When a miner hears about a new block, it will want to verify its validity (recall that miners don't want to extend an invalid chain). As part of the verification, the miner needs to make sure that the Merkle tree was correctly computed over the TXIDs. However, this does not imply transactions were verified: the miner still has to verify transactions individually as described in your link. One consequence of this verification is SPV security for free: When an SPV node sees a Merkle membership proof for a transaction, they can assume it's valid (because SPV nodes assume miners verify blocks).

Actually, it is not incorrect. If the Merkle root were omitted without replacement, we would indeed have no information about the transactions or their authenticity. However, you're right to point out that it is not without alternatives and the above phrasing make it sound that way.

Exactly, it is incorrect in the sense that the Merkle root is necessary for efficiency, not for integrity/authenticity, where a simple hash-chain or just a hash of all transactions (no chaining) would work just as well.

I've changed "incorrect" to "misleading" which I think better expresses the issue. If you mind, feel free to roll back. :)

Yes, that's perfect!

Merkle Trees are useful for checking set membership in a distributed system. First, a brief algorithmic description:
Scenario: Alice, the verifier, is in possession of a digest of a set S (i.e. but not its elements), an element x. She wants to know if x belongs to S. If the answer is yes, she would like to see a proof. Since Alice does not have S, she asks Bob, the prover. Bob presumably has all the elements of S.
Simple Solution: Bob checks whether x is in S and if so returns the entire set S to Alice as a proof. Alice, can verify that x is truly in S by recomputing the digest of S and match it against the one she has.
Merkle Solution: Bob checks x is in S and if so returns log n hashes of the internal nodes that the are siblings of the nodes on the path from x to the root in the Merkle tree of S. Alice can, using the these hashes, can reconstruct the Merkle root and compare it against the hash that is in her possession.
Note that

In the bitcoin original paper, these trees are mentioned as a way to reclaim disk space: Continuing with the example above, Bob realizes that certain elements from S became inactive (e.g. fully spent transactions in a block), ones that Alice will never ask for membership. Bob can safely delete them, as long as he stores the relevant portion of the Merkle tree that concern the active/unspent transactions. In bitcoin, this does not affect the block descriptor as the Merkle Root would be part of every Merkle Path and hence it is intact. Thus, deleting obsolete transactions does not alter the integrity of the blockchain. On the other hand, naïvely, storing a hash of all the transactions from the block will "freeze" the block from any future deletions.
In both solutions, it is cryptographically intractable for Bob to make up a proof, if he is not in possession of the elements of S because digests are one-way functions.
Alice, could be a client, who might not want to store the entire set for space considerations.
In the first solution, the entire set S needs to be transmitted, though Alice needs to perform just one hash.
However, the Merkle solution is exponentially superior when it comes to communication as only log n hashes are transmitted from the prover to the verifier, but Alice needs to perform log n hash computations. Computing hash digests is fast, hence Merkle Trees have found applications here.

Merkle root is not used to verify the integrity of transactions in block, but not to verify the transaction itself.

If any Transaction is changed the merkle root changes its value. So to verify the integrity of a group of transactions we use Merkle root.
This might help What Is A Merkle Tree