Why not multiply "six confirmations" and divide Time-Between-Blocks and Reward by the same factor? It seems that choosing a good factor to use to expand Bitcoin's capacity is a good idea.  The software would divide some of its calculated values by this factor, such as the target time between blocks during difficulty calculation, the number of blocks between difficulty adjustments, and the subsidy.  To achieve the security of "one hour's worth of hashing power," the recommendation for confirmations would be multiplied by this factor.  It seems that using a factor of two from time to time (whenever the community finds it valuable) would be appropriate.

Let's suppose we choose a factor N. This will allow the blockchain itself to grow N times as fast, providing N times the transaction fees to miners, multiplying the number of rewards by N (but dividing the reward itself by N), dividing the average wait for a confirmation by N, and multiplying the rate at which transactions are confirmed by N.  This also reduces the variance of mining revenue.

This allows time (instead of network bandwidth and computer memory) to be used to expand the carrying capacity of the bitcoin ecosystem.  Should such a proposal be written into a BIP?

The objections to this idea so far have been answered in the comments.  If anyone feels that there is an objection adequate enough to drop the idea, please post an answer.  If anyone wants to create a BIP, please let me know so I don't have to do it myself.  I don't mind doing it myself, but I'll probably be slow.

In consideration of replacing the 1 block with N blocks in the same time frame, N > 1, I see the following points:

Advantages

Expected time until first confirmation is reduced
Mining revenue is distributed smoother among pools
Capacity of network is increased
Smaller peak traffic than increasing blocksize by N

Disadvantages

A hardfork is required to adjust the block interval
Increased chance of chain forks and higher stale rate due to block validation taking a larger portion of block interval
Thin clients need to store a larger amount of headers
Slightly bigger bandwidth usage than larger blocks

Still, it may be that 10 minutes is too conservative and a smaller block interval would provide an overall benefit. For example, at Scaling Bitcoin Milan, Arthur Gervais presented simulation results that he interpreted to suggest that Bitcoin could safely use 1 minute blocks.

CoinDesk covered the topic in A Lower Block Time Could Help Bitcoin Scale, But Will It Work?.


How transactions get added to a ledger? I just can't seem to understand how bitcoin works. Here is what I understand so far.

Alice sends 1 Bitcoin to bob's public address
A new transaction gets created for miners to approve. A transaction will have the following properties

Sender's public address
Receivers public address
Amount
Timestamp

The transaction gets broadcasted to multiple nodes on the bitcoin network
Miners/Nodes listening for incoming transactions receive Alice's transaction and want to make sure that the transaction is legit and there is not double spending.
Miners/Nodes start looking up the ledger (block chain) which holds all the transactions that every happened from the beginning of time to find if all the previous transactions by Alice have been completed and if they are, only then execute the new transaction.
When a miner validates the new transaction it transfers the 1BTC over to Bob's account minus transaction fee.
And Bob is 1BTC richer and he lives happily ever after.

Please correct me if I am wrong and I honestly don't understand whats the story with the 'n' number of zeros being added to the a string to prove a transaction is valid.

Please help. I'm trying to understand this so that I can contribute to Bitcoin's source code.

The process actually goes like this:

Alice sends 1BTC to Bob's address. A new transaction gets created with:

As many inputs as necessary (unspent outputs from Alice's previously received transactions) formed by:

Previous transaction ID (txid, the transaction which sent Alice the coins she's going to spend) and output index (vout, which output of the transaction is being spent)
Alice's public key (whose hash(publicKey) must match the hash included in the previous transaction)
A signature over the whole transaction, signed with Alice's private key and verifiable with the included public key

As many outputs as necessary/wanted pointing to Bob's addresses (remember each address is just a hash, not public key!)

This is the hash Bob will have to match with his public key to spend the coins!

The raw transaction is broadcast
Miners receive this transaction, verify and validate it (check signatures, check that inputs are valid and unspent, check that hash included in unspent outputs equals hash of the provided public key)

Up til here you got it more or less. Now here's what you didn't get:

Miners add this transaction to their current block, which holds even more unconfirmed transactions
The miner keeps hashing the block with an incrementing nonce

In each nonce incrementation, the hash is different
If hash(block+nonce) < target (target varies with difficulty), the block has been mined and is considered valid

When block is mined, it's broadcast to the rest of the network, which in turn update their blockchain and start mining from this block (if it's the head of the longest known chain)

Getting a block and nonce whose H(block+nonce) < target is a probabilistic process and you can only get a mined block via trial and error. If you mine a block, you've spent lots of trials and errors (proof of work) but verifying that the block is correct is very cheap.

These mined blocks form a chain. Miners compete to form the longest chain. This is what makes Bitcoin secure: to change the chain you have to mine as many blocks as you'd like to change plus one, before anyone else finds a single block.


Under what circumstances will a full node disconnect a peer? I know a full node will disconnect from a node if that node "misbehaves". For example, a node's connection will be dropped if it sends too many messages that don't follow the rules (what rules?) and nodes that send a lot of expired, duplicate, or otherwise useless messages. What other reasons do full nodes disconnect from a peer?

For example, do full nodes disconnect from connections that don't send enough data?

For a node to be disconnected the default threshold of banscore is 100. In versions prior to v0.18, the default time to keep the misbehaving peer from reconnecting is 86,400 seconds or 1 day. However, this was circumvented by attackers with multiple IP addresses.

v0.18 release, allows peers that your node automatically disconnected for misbehavior (e.g. sending invalid data) to reconnect to your node if you have unused incoming connection slots. If your slots fill up, a misbehaving node will be disconnected to make room for nodes without a history of problems (unless the misbehaving node helps your node in some other way, such as by connecting to a part of the Internet from which you don't have many other peers).

Following are the reasons for disconnection, or increasing the banscore.

Peers which provide a chain with less work than the minimum-chain-work during IBD are  disconnected
If the node is providing invalid data like mutated block or data not meeting consensus requirements
If the compact block had a valid header, but contained invalid txs, the peer should not be punished
Ban outbound (but not inbound) peers if on an invalid chain.
Invalid header, invalid block checkpoint, and invalid previous block will result in outright ban
If previous block is missing, the banscore is incremented by 10. This is done so as to prevent DoS attacks
If the peer sends a getblocktxn with out-of-bounds tx indices it will result in a ban
There are other items related to bloom version and bloom size which might result in ban
First message should be a version message and each connection can send version message only once. If not, the banscore is incremented by 1
If the node is sending addr messages with more than 1000 addresses, then banscore is incremented by 20
Sending inv messages that exceeds the max size, then banscore is incremented by 20.
Sending header messages with more than 2000 elements, resulting in incrementing banscore by 20.
Nodes must NEVER send a data item > 520 bytes or misbehaving score is incremented by 100

There are other couple reason which might have been ommited. You can search "misbehaving" in the netprocessing.cpp file for all the reasons.

  Do full nodes disconnect from connections that don't send enough data?

Not particularly but somewhat yes. When the chain tip does not advance for over 30 minutes, the full node assumes that the tip may be stale and hence will try to connect to an additional outbound peer. There is a periodic check that ensures that if the extra peer connection is in use, the node will disconnect the peer that least recently announced a new block.


Canadian Taxes for Buying Bitcoins I saw this post, but it really didn't help me.

How should I fill out my tax forms if I am only buying and holding bitcoins, not selling them?

This page appears to suggest that I only need to worry about taxes if I profit off of them when I sell them:

Buying and Selling Bitcoins

Income Tax Implications

Where a person trades or sells Bitcoins like a commodity (i.e., speculating
on the changes in the value of Bitcoins), the resulting gain or loss may be
on account of income or capital.  Determining whether such a transaction is
on account of income or capital can only be made following an assessment of
all the facts relating to the particular taxpayer’s circumstances.
Paragraphs 9 to 32 of Interpretation Bulletin IT-479R, “Transactions in
securities”, provide general comments for purposes of determining whether
transactions are income or capital in nature.

The determination of the income tax consequences relating to the treatment
of gains and losses arising from the purchase and sale of Bitcoins would be
generally the same as for transaction[enter link description here][3]s
involving other types of commodities.

Example:

Mr. X bought a Bitcoin on June 1, 2013 for $100.  Mr. X then sold the
Bitcoin on December 1, 2013 for $500.

Based on his particular facts and circumstances, Mr. X determined that the
gain was on account of capital.

Mr. X has a capital gain since he sold a capital property for more than the
total of its adjusted cost base and the outlays and expenses incurred to
sell the property.

Mr. X’s capital gain is $400 ($500 less $100).  Mr. X will need to report
$200 as a taxable capital gain (only 1/2 of the capital gain is taxable) on
his 2013 Income Tax and Benefit Return.

Although I don't know how reputable that page is, so here is the official, incomprehensible source.

That's correct. You have no taxes and no need to report them if you have not sold/spent any of the coins in the tax year.

You do need to keep records of your purchases, because when you do come to sell, you'll need to work out the potential gains you've made.

If you do need to work out your gains, you can use https://bitcoin.tax or other capital gains calculators that can work out the total gains from all your selling or spending.


Are Ethereum Tokens issued in an ICO similar to stocks on a stock market? Are Ethereum Tokens issued in an ICO similar to stocks on a stock market? In which ways are they similar, and in which ways are they not?

To give some background to my question. I just joined an ICO for a company that has a business idea I believe in. So now I will get some Ethereum tokens. From what I understand, owning these tokens gives me similar things as if I would have bought stocks in this company on the stock market, so in this respect I can see it as if I own a part of this company. Is this the correct way of looking at it? Specifically:

Will the company now pay dividends based on how the tokens are distributed? And if so, where can I find more information on how much of the profit that will be payed as dividends?
Does the token give me any way to influence how the company is run? Like voting for the CEO or so? How is this administered?
Where can I trade my token and check the current market rate?

I understand that the details probably vary from ICO to ICO. But in general, how does it work? What information should I look for when a company does an ICO?

Tokens, in general, are not the same as shares in that they do not provide ownership stake or voting rights in the corporation. Typically, they are simply vehicles with which to conduct transactions for the goods or services within the corporate entity from which they are issued.  After the ICO where the company sets the price for the tokens, their value is based on supply and demand.  Demand is usually speculative and created by people's perception of what they think the particular corporation's importance will be in this new, rapidly evolving, yet very powerful world of blockchain technology. This speculative nature, as well as the fact that tokens provide no form of ownership, is what has led many established traditional Wall Street corporate investors to call this new investment vehicle dangerous, fraudulent, Ponzi-like, a big "bubble", etc.  There's no doubt that many of the companies issuing cryptocurrency tokens will disappear in time leaving their tokens worthless, but there is also good reason to believe the best ones will become large, powerful, and ubiquitous in our future. The tokens, which by the way are usually finite in number, of the surviving companies in this nascent cryto-world will have more value as the demand for their use increases. Some people will buy and hold the tokens as stores of value while others will actively use the tokens for the goods and/or services of the company. Usually tokens are traded on established exchanges such as Coinbase, Kraken, Poloniex, etc. that connect buyer and seller but every exchange decides with which coins they want to deal.  Due diligence of a company should be performed before deciding to which ICO's one should "contribute" (the term used to buy tokens in an ICO) just as one would when buying a traditional stock.

Think of tokens like concert tickets.  You don't buy ownership in the band, but need the ticket to consume (see) the band.  Tickets can be bought and sold and their value depends on the popularity of the band/demand to see the band.  There are exchanges, like StubHub, that facilitate buying and selling. There are limited numbers of tickets just like there are a finite number of tokens.  An ICO would be like prepurchasing tickets for future concerts at a very low cost.  The band may or may not be around in the future but if you can spot the diamond in the rough, your tickets could be very valuable in the future. If you prepurchase tickets to a band that goes nowhere, you lose everything.


What are these strange outputs in the Litecoin blockchain? I have found that there are some strange outputs in the Litecoin blockchain that pay small amounts to the scriptPubKey 736372697074. In ASCII, this translates to "script", reminding me of how nodes used to advertise support for P2SH by putting the string "/P2SH/" within a mined blocks coinbase's scriptSig.

The outputs have very small amounts, although they are unspendable since the 'p' ASCII character happens to correspond to OP_RETURN, and seem to show up in blocks between (roughly) blocks 81,374 and 114,829.

What are these outputs?

Those are from an early version of P2Pool, which mistakenly sent outputs to the literal string "script" rather than the variable script. This was naturally fixed, but left lying around are a number of these outputs.


I encountered Signature is found in scriptCode exception when trying to make a BTC transfer When I transferred a 0.001 BTC from miBEA6o6nZcaLZebR1dsDv4AMHRwJk1mbi to miV1sbmLM9fptRfWD5o8hs5L6ucUeJzmp5, the following error occurred: mandatory-script-verify-flag-failed (Signature is found in scriptCode) (code 16).
This is my broadcast data:
01000000020e920885bc349b3ef0fcecb0acc04c74c59bdfc67d76242fc934f7f9d7d5c915010000006b483045022100dc4681014ce850d2808c82978d92b94f4940ef5ef9c63e3c9f248a0cdf9266df02203cf0344dfbe933d5335ab06da1040cf373d866efe156824e9938ba633bd54591012103a5be350852bb09e24edc83f8e02070a74597a8b775af46e8efbef394ae4fa98effffffff33c8ba1adb1b885e553610e9431bbdbfe14078a1de8ef60d9e29316ea759e8df010000006b483045022100a4cb81427b8613276d458df994d1c9b02aad66fa69be5aef10e71a392a9df10402205b8b919147543aa6c11b12b8b2c44edf498973c6539021cb349ecff674df3f93012103a5be350852bb09e24edc83f8e02070a74597a8b775af46e8efbef394ae4fa98effffffff02a0860100000000001976a914208a8852a3cec93382c8bebbbd6c9ef4676f512088ac8041100000000000232103a5be350852bb09e24edc83f8e02070a74597a8b775af46e8efbef394ae4fa98eac00000000`

The test method I performed: https://github.com/lingting/VirtualCurrency/blob/0.3.1/src/test/java/live/lingting/virtual/currency/omni/Transfer.java#L130
Transfer operation, signed code: https://github.com/lingting/VirtualCurrency/blob/0.3.1/src/main/java/live/lingting/virtual/currency/service/impl/BtcOmniServiceImpl.java#L248
The signature is at: https://github.com/lingting/VirtualCurrency/blob/0.3.1/src/main/java/live/lingting/virtual/currency/service/impl/BtcOmniServiceImpl.java#L335
Signature code:
        List<TransactionInput> inputs = tx.getInputs();

    for (int i = 0; i < inputs.size(); i++) {
        Script script = ScriptBuilder.createOutputScript(fromAddress);
        TransactionInput txIn = tx.getInput(i);

        Sha256Hash hash = tx.hashForSignature(i, script, SigHash.ALL, false);
        ECKey.ECDSASignature ecdsaSignature = key.sign(hash);
        TransactionSignature txSignature = new TransactionSignature(ecdsaSignature, SigHash.ALL, false);
        if (ScriptPattern.isP2PK(script)) {
            txIn.setScriptSig(ScriptBuilder.createInputScript(txSignature));
        }
        else if (ScriptPattern.isP2SH(script)) {
            txIn.setScriptSig(ScriptBuilder.createP2SHMultiSigInputScript(ListUtil.toList(txSignature), script));
        }
        else if (ScriptPattern.isP2PKH(script)) {
            txIn.setScriptSig(ScriptBuilder.createInputScript(txSignature, key));
        }
        else if (ScriptPattern.isP2WPKH(script)) {
            Script scriptCode = ScriptBuilder.createP2PKHOutputScript(key);
            TransactionSignature signature = tx.calculateWitnessSignature(i, key, scriptCode, txIn.getValue(),
                    SigHash.ALL, false);
            txIn.setScriptSig(ScriptBuilder.createEmpty());
            txIn.setWitness(TransactionWitness.redeemP2WPKH(signature, key));
        }
        else {
            throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR,
                    "Unable to sign this scriptPubKey: " + script);
        }
    }

I would like to ask what is wrong with my code. In my submission this time https://github.com/lingting/VirtualCurrency/commit/0ea9b090d6fe2e4821afc10b5725436d56f2909d#diff-25a6634263c1b1f6fc4697a04e2b9904ea4b042a89f59dc848a. I can still submit the code normally. , I also tested it at the time, and there are several transfers in the test address I generated to prove it, but why is it not possible now?

The referenced outputs are P2PK
createOutputScript(fromAddress) implies P2PKH
P2PKH scriptSig doesn't match with P2PK pubkeyscript

Resources used to write this three-line answer:

Compile Core
Use 30 GB bandwidth to download the blockchain
Two-three hours of time

but I'm happy to help more if this isn't enough.


How does tx fee calculation work when txin and txout are similar amounts? This website has an example called "When Too Much is Not Enough" on its main page. I'll quote it an case this is changed in the future:

  Suppose you have only two outputs in your wallet, worth 1 XBT and 2
  XBT. You want to buy something for 2.999 XBT. The coin selection code
  has no choice; it has to select both coins to get a big enough total
  to make the transaction. That means the change will be 0.001 XBT,
  which triggers the 0.0001 XBT fee for having an output that's less
  than 0.01 XBT. As a result your transaction will fail, because the
  amount you're sending plus the fee is more than you have.

  What this means is that there's no way of spending 2.999 XBT when you
  have 3 XBT. You could send the full 3 XBT to the vendor without a fee
  (assuming the outputs are sufficiently old to satisfy step 3), but
  some vendors ask you to send the exact amount they specify.

Since the 1 BTC input and the 2 BTC input are interchangeable in this respect, let's (for the sake of simplicity) settle that the bitcoin client decides to send the 2 BTC input in full for this example.

Then it has to split the 1 BTC input into a 0.999 BTC output and a 0.001 BTC output. I assume that doing so requires a fee because one of the outputs is smaller than 0.01 BTC. So 0.0001 BTC have to be paid for this. This means that there now is a 0.999 BTC junk and a 0.0009 BTC. The 2 BTC junk and the 0.999 BTC junk are send away and the 0.0009 BTC junk remains at its owner.

Can you tell me what I did wrong to get an outcome different from the one of the authors of that website?

Obviously, the example is erroneous. They also neglect to consider that you could send 2.999 XBT and designate all of the remainder of 0.001 XBT as fee.


How can one generate a vanity Bitcoin address with both a given prefix and suffix? I want generate a unique Bitcoin address with vanitygen that has both a given prefix and a given suffix:
  1Bit******************Bit

How would I be able to achieve that?

Vanitygen has a regex option, for generating addresses that match an arbitrary regular expression.  I think that

vanitygen -r '^1Bit.*Bit$'

would work.

Note that it will not be able to estimate the expected time that would be required.


Hash rate : Algebraic Equation I recently made a post on stack, Calculate hash rate in IOS, in hopes of deciphering how the hash rate is calculated when benchmarking performance. The reason I wanted to do this is to compare against the results that are presented in Is it Possible to Mine Cryptocurrencies with an iPhone? After days of hunting around on the internet, I've come to a conclusion that calculating the hash rate is not as straight forward as it seems.
My Thoughts
I was under the impression, especially after reading How can I calculate how many hashes I generate per second?, Explaining Hash Rate Or Hash Power In Cryptocurrencies and How is hash rate of mining hardware calculated, that calculating the hash rate is done as follows:
Have collection of x number of messages (M) 80 bytes in size
Loop through records, and calculate the sha256(sha256(M))
Divide the number of computed hashes against elapsed time
    # the result is hash rate ( in seconds, given your elapsed time is in s )

After doing so, I see results up to 24000 hashes per second, or 24KH/s. Obviously, this is alarming, as the reference article I am attempting to compare to, has these results:

The iPhone 6 has 25/30 Hash Rate (H/s)
The iPhone 8 55 H/s
The iPhone X (iPhone 10) 65 hashes per second

I later continued my hunt, and stumbled upon this Stack post how to calculate hash rate of your rig?, and the accepted answer mentions that the hash rate is something that is defined empirically. While I do not doubt the author, I now find it difficult to determine what hash rate really is. ( Does the "nonce" have any impact on calculating the hash rate? i.e Is the standard hash rate determined by calculating the number of times my machine can ensure that the hashed result begins with 3 ( or 5, or 7 ) leading zeros in 1 second? )
TL;DR
I want to compute a hash rate for my IOS device. What algorithm and algebraic expression should I use to calculate the hash rate, to be able to compare my results against other devices, like laptops and graphics cards?

The hash rate is literally how many distinct block header hashes you can try per second. Nothing more, nothing less. Note that I say "try" and not "compute". Determining whether a particular block header is interesting is somewhat faster than fully computing the hash:

You can drop the last few rounds of the hash implementation, and only compute the first 32 bits of the output (and if that those 32 bits are 0, recompute the hash in less optimized software to determine if it's a fully valid block).
You can exploit the fact that successive attempted block headers only differ in a few bytes, reusing part of the computation.
You can precompute things to find combinations of multiple block header attempts that share more parts of the evaluation than random ones (this is what AsicBoost is based on).

So determining the exact hashrate of certain hardware is a nontrivial engineering effort because of the above, and is complicated by things like architecture specific optimization, and things like exploiting special hardware instructions.

Such engineering has obviously not been done for iPhone, as it's a nonsensical target for computation. My back of the envelope computation suggests it could probably do a few MH/s, but as that still means ~50 million years to find a block, not much effort will be spent on this.


In Bitcoin Qt, what does "Message" mean in the request payment form? In Bitcoin Qt, if I go to "Receive" and right click on an address, one of the options is to "Show QR Code" for an address. Below the QR code, there is a form looks like this:

[ ] Request payment
Amount: ____ BTC
Label: ____
Message: ____

My question is: what does the "Message" field do?

The Bitcoin protocol does not support any kind of message associated with transactions. The message when generating QR codes is simply a short string that is passed along with the Address and Amount to the person scanning the QR code as a hint to recognize what the Address has been used for. A merchant may for example put a short description of the item you bought in the message field. You then scan it and your Bitcoin client may use that field to mark the transaction, so that you later recognize which transaction was used for what.

The message however will never be posted to the network and is only stored in your Bitcoin client, i.e., if you restore your wallet the messages may not be restored.


As a solo miner how can I prioritize my own unconfirmed transactions? Is it possible to prioritize my own unconfirmed transaction through my mining machines without being in a pool? And if its possible how can I do that?

If you are the pool itself, or are solo mining you can use the prioritisetransaction command to add weight to your own transaction, if you are a client of a pool you do not have any control over what you are mining.


What is the true number of confirmations before a LTC mined block moves out of the immature state? I've read it's 100, 101, 120...

I have a mined block that has more than 140 confirmations but is still displayed as "immature" by the wallet.

How many confirmations are required before it leaves the immature state?  Is this number variable?

Thanks

100. You could argue 120 too. It's the same as Bitcoin.

static const int COINBASE_MATURITY = 100;

Source

Now, this is the amount of time before other nodes will let you spend your mining income. However, the client will wait 120 blocks before telling you that the generation has matured.

int CMerkleTx::GetBlocksToMaturity() const
{
    if (!IsCoinBase())
        return 0;
    return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
}

Source


Lightning: Why would Bitcoin Network Accept a Breach Remedy? The Lightning Network Whitepaper discusses a situation in which one party of a payment channel broadcasts an outdated commitment transaction.  The other party through a breach remedy transaction will get the cheating party's coins.

How does this work though?  If the dishonest party broadcasts a transaction to the Bitcoin network, isn't that transaction more likely to be accepted (since it was first) than a subsequent (up to date and legit) transaction?

You are right. If the dishonest party publishes an outdated commitment transaction it is most likely be accepted by the Bitcoin network.

The key trick is that the old state has an output script that gives the other party the opportunity to spend all outputs (even the one that was supposed to belong to the dishonest party) with the so called breach remedy transaction. This mechanism works via a time lock in one output of the commitment transaction and is called a Revocable sequence maturity contract (RSMC)

So if Alice and Bob have a channel with 5 mBTC for Alice and 7 mBTC for Bob. But Alice decides to publish an old commitment transaction in which Alice has 9 mBTC the outputs of that tx look like this :

Bob can immediately spend 3 mBTC
anyone with a Revocarion secret can immediately spend 9 mBTC
alice can spend 9mBTC after a timelock of for example 144 blocks.

The breach remedy transaction is the transaction spending the revocable output. So it is not an alternative to the fraudulent commitment transaction but rather a guaranteed way to spend the output of the commitment transaction that is supposed to belong to the dishonest person. It is guaranteed as the timelock prevents the dishonest person from spending their output.


How to distinguish between change and actual sent amount looking at transaction data I am building analytics starting from blockchain raw data (blk**.dat files).

I have read in the bitcoin wiki that once the inputs have been chosen for a transaction, they must be all used: so a change is generated back to the original sender (via the same address or a different change one, depending on the client configuration).

While building analytics, I would like to exclude these outputs from any kind of metric, since they let the coin work but do not represent any intelligence at all.

Is there a way to looking at the outputs of a transaction and split them into meaningful sent amounts and change?

There is no way to know with certainty which output is the actual spend, and which is the change, without being involved in the transaction yourself. It is possible to infer this though, consider the following:

Transaction 'X' has 2 inputs (0.5, 0.5), and 2 outputs (0.7, 0.3). Logically, we can infer that the larger output (0.7) is the spend, because if the spend was the 0.3 output, the user could have saved costs by just using one of the 0.5 inputs to send the transaction.

However, it is possible for users to purposefully transact in a less efficient way, in order to obfuscate their spending habits, so you can never be absolutely certain.


What is the size of different types of channel funding/closing transactions for the Lightning Network? This matters a lot for people who want to host a Lightning Network node and will influence LN-transaction fees, because a node-host has to justify the miner fees of setting up channels for others with the income by charging fees themselves.

If a channel-funding transaction is for example 500 bytes in size, it will often cost more than 10$. Sub-one-cent transactions through 5 channels can now only be achieved if more than 5000 transactions pass through each channel before it closes which is quite a lot.

If transactions are that funding transactions are that expensive, centralization is a major concern, because smaller users can't justify paying for 5-10 or even more channels to sustain true decentralization and will rather have one channel to a big hub.

The size of a transaction is no longer relevant. What matters is the weight (which is based on size), especially because LN uses segwit which has different weight values for segwit spends.

The expected weights for the commitment transactions and HTLC success and timeout transactions can be found here: https://github.com/lightningnetwork/lightning-rfc/blob/master/03-transactions.md#appendix-a-expected-weights.

The weight for the funding transaction is harder to know as that entirely depends on the inputs being spent and that is dependent on the sender. Since the inputs and their signatures make up the vast majority of a transaction, it is impossible to say what weight funding transactions will have as they will basically all be different.


Removing old public keys I have an 'Electrum' wallet. I found some old public keys and imported them into it and then sent the bitcoins to an address in the main wallet. Now the transactions are confirmed and there are 0 bitcoins balance in the imported keys I presume it's safe to delete those keys from the wallet? Is there any circumstance in which I'd ever need them again? (Assuming of course nobody is going to pay anything to their addresses)

You can delete them with the second click options if you think so.

If you ever receive coins in that imported addresses you won't know if you don't have them imported in Electrum or in other client. Or if you've registered somewhere signing messages with it (like in #bitcoin-otc)

In case you want to keep them you will have to keep a backup of those keys separately by copying the wallet file as they won't become part of your Electrum seed.


How can the compressed UTXO set be stored in just 4GB? According to S. Delgado-Segura, C. Pérez-Sola, G. Navarro-Arribas, J. Herrera-Joancomartí, "Analysis of the Bitcoin UTXO set", Financial Cryptography and Data Security, pp. 78-91, 2019, the distribution of the UTXO set as of 2017 was:

No of UTXO                  52,543,649   100%      Size
Pay-to-PubkeyHash (P2PKH)   43,079,604    81.99%   147-179 bytes
Pay-to-ScriptHash(P2SH)      8,987,799    17.11%   40 - ? bytes
Pay-to-Pubkey(P2PK)             66,759     0.1%    113 bytes
Others                         409,487     0.8%    114-1483 bytes

There are 66.6 million UTXO in April 2020. Assuming the same distribution, the size of UTXO set should be approximately:

No of UTXO: 66.6 million = 100%
Pay-to-PubkeyHash (P2PKH)   81.99%    147-179 bytes   7.475712318GB
Pay-to-ScriptHash(P2SH)     17.11%    40 - ? bytes    0.424506515GB
Pay-to-Pubkey(P2PK)          0.1%     113 bytes       0.007008947GB
Others                       0.8%     114-1483bytes   0.056567788GB
Total                                                 7.963795569GB

Per statoshi.info the serialized UTXO set is 4GB as off April 2020.

I understand UTXO data does not have lot of leading zeros. How can the serialized UTXO set be compressed to 4GB?

The sizes you give don't match the paper. I can't even find mention of the sizes you give in the paper itself. Those sizes are incredibly wrong and way too large. They seem to be for input sizes, not output sizes. Input sizes are irrelevant to the UTXO set.

P2PKH are 21 bytes, P2SH are 21 bytes, P2PK are 33 bytes, everything else is their actual script size.

P2PKH = 1.147 GB
P2SH = 0.2393 GB

I've decided to omit the other outputs types because there are so few of them that their size is negligible.

The amounts are at most 0.5328 GB. However the amounts are compressed, so that should actually be smaller.

The outpoints (txids and output indexes) are at most 2.398 GB.

So in total the serialized UTXO set is approximately 4.3171 GB which is close to what we actually observe.

There are some more bytes due to the omitted scripts and because of the LevelDB's overhead, but there shouldn't be much (and certainly not several GB). Additionally the amounts and the output indexes are compressed which significantly reduces the serialized size. So in total, it's ~4 GB. My node reports 3.9 GB.


Low-s value in bitcoin signature What are the problems related in using the "normal" ( bigger than N/2) value of the s number in transaction signature and why we use the lower one?
Is it about the math behind the ecdsa?

Details are in BIP 146:

We require that the S value inside ECDSA signatures is at most the curve order divided by 2...
...
A high S value in signature could be trivially replaced by S' = 0xFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141 - S.

Signatures encode two important values for verification r and S. If (r, S) is a valid signature, then so is (r, -S), which is equivalent to (r, curver_order -S).


What is miner supposed to do when waiting for longpoll i am coding simple miner.
I succesfully implemented Getwork in basic form. Next thing is gonna be Longpolling.
If i understand correctly longpoll is just connection that is waiting for next block. So, what happens when I am waiting for longpoll and submit share ? I am supposed to mine further(increase nonce and continue) or simply wait for longpoll. Using only getwork and SSE2 optimized scrypt I was able to get 5kHash/s on my i5-4670K on single thread.

If you run out of work while waiting for longpoll to finish, then what you should do is submit another getwork request.

Note that just because you find a share in a particular piece of work, doesn't mean that you're done with that piece of work. There still might be shares or even a block solution in there somewhere.


What are the relevant hardware-mining options as of 13 May, and and how should one choose one over another? After reading on the topic of bitcoin for the past few hours I've heard a few terms again and again: mining with the CPU (pointless as of today), GPU mining (lots of people doing this), and then ASIC, and FPGA (field-programmable gate array).

With just a few hours experience in this, and although I've obviously seen the wiki's here and there which compare this hardware to that, the answer to this question could take into account some real-world factors, especially concerning the availability of the ASIC units (which are said to be much more efficient). E.g., there's talk of one particular one shipping, yet orders aren't being filled, doubts as to if they ever will be, etc.

So with that, an ASIC might be worth less consideration than another setup. The answer I'm looking addresses these different types of hardware (excluding CPU which we know are worthless) and which one might be right for someone who wants to join in on bitcoin hobby-wise, and eventually break even in terms of investment (within say, a year). This is only considering hardware and not pools, which I'm aware of.

In order of hashrate:

ASIC >> FPGA > GPU >> CPU

">" meaning "more powerful", while ">>" stays for "completely outclasses".

Currently there are some ASICs out there, but not so many to totally destroy the chances for the other devices to mine anything, so there's still some people mining with FPGAs and some with GPUs.

Of course those using FPGAs and GPUs already have them, and it would be a pretty bizarre business decision to start using one of them right now (might make some kind of sense for the resell value: an ASIC's only purpose is mining bitcoins, while the other devices once obsolete might be used for something else).

Officially there are three ASIC manufacturers:

Avalon: first to complete an ASIC, ships big devices, but currently isn't taking new orders.
Butterfly Labs: vapourware! Started collecting money almost one year ago, and constantly misleads his customers stating they are going to be "ready in two weeks". Recently shipped a few devices to some selected members (journalists, etc.) and they were very inferior to their specifications.
ASICMINER: instead of focusing on selling hardware, they produce their own devices and use them, selling you shares in their company, giving you dividends; recently they also started accepting orders for small USB ASIC miner.


computational effort needed to mine a block given the number of leading zeros in the resulting hash? What is the computational effort to mine a block successfully given the number of leading zeros in a resulting hash?

The difficulty does not specify a certain amount of computational effort that needs to be expended. In other words, the difficulty is not set to '1000 effort', and miners slowly progress from 0 to 1000, with the first one to expend 1000 effort winning the next block.

Instead, you need to think of it like a lottery. You can expend effort to make a guess, and if your guess is correct, you win the next block! The higher the difficulty, the lower the odds of any one guess generating a valid block.


Invalid p2sh transaction accepted by the network I have try to build a 2 of 2 p2sh transaction from scratch using the book "programming bitcoin" by Jimmy Song, we are not directly guided to make one of those so I had to modify some of the function we had to build in the book but I guess it must be working.
Here is my tx on testnet: https://www.blockchain.com/btc-testnet/tx/7eba40f4c00e3da529309011c6fd8066c97fd24adca60b0d024976c360bcdd8b
And here is my code: https://pastebin.com/1mCv73i2
using the functions of the book: https://github.com/jimmysong/programmingbitcoin
My question are:

Why did the transaction was accepted by the network despite not working as intended
Why did my input did not go to the desired p2sh address "2N7e6ZAGXoepdVYu2Y8ho7fTf6oxE3j9UwS"
It is on the testnet but if it was not can I retrieve my satoshis on this tx ?

edit: I found my error about my redeemscript and updated my code, but now I have a "Code: -25, Error: bad-txns-inputs-missingorspent" error when I want to broadcast it
here is my raw transaction, and I have updated the pastebin for the code:
https://pastebin.com/8sQBpnVY

Why did the transaction was accepted by the network despite not working as intended

The network does not check the validity of output scripts. An output script can contain pretty much any data and the transaction will still be consensus valid. But your transaction is not actually invalid. It's just like a bare multisig now, but since the pubkeys are hashes, it isn't.

Why did my input did not go to the desired p2sh address "2N7e6ZAGXoepdVYu2Y8ho7fTf6oxE3j9UwS"

You set the output script to dat_redeem_script_op rather than target_script. So the output script is actually your multisig script rather than the P2SH script you intended.

It is on the testnet but if it was not can I retrieve my satoshis on this tx ?

No. Even if you had done this correctly with P2SH, it would still be unspendable. This is because your "public keys" are actually public key hashes. However you do not use any opcodes to for public key hashing. OP_CHECKMULTISIG takes public keys so it will try to interpret your public key hashes as pubkeys and fail to do so.
If you had constructed the multisig script correctly with public keys, this would be spendable as a bare multisig. It would be spendable in the same way that a P2SH multisig is spendable except you do not provide the multisig script in the input's scriptSig.


How to get BTC and ETH prices from Binance in Google Sheets? I've been using the CRYPTOFINANCE() function in Google Sheets for a while but I can't seem to find out how to pull data from my exchange (Binance).

I'm specifically looking for the BTC/USD and ETH/USD markets. Using the syntax in the doc1 gives me #ERROR in my cells.
My syntax is =CRYPTOFINANCE("BINANCE:BTC/USD")

Anybody had this problem before and managed to fix it?

Following up on my question.

Leon had a point in his comment, Binance doesn't have USD pairs, only USDT.

I updated my cryptofinance calls to =CRYPTOFINANCE("BINANCE:BTC/USDT") and =CRYPTOFINANCE("BINANCE:ETH/USDT") and it worked like a charm!


Can a miner not find a share in his work unit? I understand that a mining pool operator distribute work units at it miners.

Is it possible that a miner can find no share in his work unit?

If is the case, this mean a miner can work for nothing?

A good pool should manage difficulty levels so that every qualified
1 worker finds at least some share.  It may be a very small share, but something should be counted.

1 By qualified, I mean a processor in the same league as the rest of the pool.  If you join an Intel CPU miner to a pool of ASIC miners, your miner would not be qualified, and it would be appropriate to not get any shares.


How can I change BTC into normal cash? Can you eventually hold the bitcoins in your hand, like real cash dollars or euros or something? If so, how?

I've gone through all the service previews and introduction videos (actually, a video), and didn't see anything about this particular point.

I don't have a credit card, and I'm in a country where banking services aren't so profound and  people don't use credit cards (Libya). Does a Bitcoin account rely on having a credit card, and will the coins you gather be added to your bank account?

Bitcoins are a purely electronic currency. If you want to sell them in exchange for dollars or euros, you can do that. But as Bitcoins, they exist purely electronically. There are physical Bitcoins but basically, they're just the key to an electronic account printed in some form.

I think you're missing the concept that Bitcoins act like a currency or commodity. You can have 10 Bitcoins just like you can have 10 ounces of gold. The key difference is that the Bitcoins exist electronically rather than phyiscally. If you have Bitcoins and want dollars, you have to find someone who has dollars and wants Bitcoins, then you exchange with them.

Bitcoins are not a payment or fund transfer system for national currencies like PayPal and Western Union are. Bitrcoins are a currency that has an efficient built-in transfer system.


What will be required to increase the "soft" 500KB per-block data limit We've alerady hit the point where a block has become 90% full, thanks to the popularity of SatoshiDICE.

The limit can be increased from the 500 KB max per-block in the software to 1 MB per-block limit in the Bitcoin protocol, reportedly.

To increase this to the level allowed by the protocol, is it just a client update for miners, or does it require a new client for everyone who needs to be able to accept blocks with the larger limit?

The 500kB limit is related to the fee rules. Miners won't include transactions into their blocks unless they have at least some minimum fee. The Satoshi client determines the minimum fee (for miners -- relayers and senders use slightly different rules) like this:

When the block currently being mined is less than 27kB, certain transactions are allowed without any fee.
When the block currently being mined is less than 250kB, the fee is 0.0005 BTC per kB of transaction size.
After 250kB, the fee per kB increases as the block size increases to an asymptote at 500kB. At 500kB and beyond the fee is infinite and no more transactions will be accepted.

To increase the limit, we'd only need a few significantly-sized miners to change their fee policies. DeepBit already doesn't use the Satoshi client's dynamic fee increase after 250kB, though I think they still have a limit at 500kB.


How to set a specific fee in satoshis per transaction? I'm currently working on a personal project which is a small bitcoin exchange website, I've figured out how to create a raw transaction and broadcast it (createrawtransaction -> fundrawtransaction -> signrawtransactionwithwallet -> sendrawtransaction).
There's a option in fundrawtransaction which lets you set the fee but it's in BTC/kB. Are there any options on how to send the transaction specifying the final fee in satoshis? Or how do I know the final size of the transaction to calculate the fee? I want users to choose the fee in satoshis and not in BTC/kB.
I don't know if this has something to do but I'm using bech32 addresses. Thanks for your help!

How to set the absolute fee
The transaction fee is implicitly defined by the difference between the sum of input and the sum of output amounts.
fee = Σ(inputs) - Σ(outputs)

Since you are building your transactions explicitly, you can set the exact transaction fee by defining the corresponding specific amounts of the outputs for the recipient(s) and the change output. As the weight of inputs and outputs is predictable, you can calculate the appropriate fees by knowing the count and type of inputs and outputs in advance.
Why it's a bad idea
While your wallet can determine the input count during the transaction building, your users will not know in advance how many inputs it will take to fund their transaction. Since transactions get processed in order of their feerate rather than their absolute fee, the user will not be able to make an informed decision for an absolute fee without knowing the weight of the transaction. Per my experience, users get absolute fees wrong more often than not (most users even get feerates wrong), which leads to substantial support traffic with complaints about overpaying or underpaying. This is why withdrawal interfaces usually give predetermined choices (e.g. express, normal, thrifty) or take a feerate rather than an absolute fee.
If you want the recipient to pay the fee, you may want to consider using subtractfeefromamount.


can I create addresses based on what I want to look like? Hi I am completely new to bitcoin. I was wondering if it is possible to create addresses based on how the final outcome you would like to be. For example, I dont like something like that 1L5gu6zJHxtAiDM74heP7wW84PYQ5Ltc9o as it is extremely difficult to remember. Could it be possible to create something like that eg., 1L5a5a5a5a5a...c9o i.e. decide the final letters or an approximation?

Not really, a Bitcoin address is the result of applying multiple hash functions to a public key. Since you can't decide how the result of a hash function will look like depending on the input, you won't be able to do so with a Bitcoin address.

You can find the Bitcoin address creation process explained in the Bitcoin wiki.

However, as commented by @m1xolyd1an and @pieter-wuille, VanityGen can be used to create a more personalised address, instead of a purely random one. Since VanityGen is based on a probabilistic search, the pattern that you will be able to include in your address will be quite short. Trying to include long patters requires a lot of time, becoming infeasible.


Java: bitcoinj; how to download a full block? I would like to download a full block using Java and bitcoinj and then parse it to an array to be able to work with it. Here is some (very basic) pseudocode:

connect to network;
download latestBlock;
write/convert block to readable array;
read blockArray;
   sout: blockArray[23][55] // this should get me eg. a txid, address, ...
// or similar. I just want to be able to read values from the block

Is there a way to do this? I found the following solution here (Using bitcoinj to discover peers and download the block chain):

public class DumpLastBlock {
public static void main(String args[]) throws Exception {
    WalletAppKit kit = new WalletAppKit(MainNetParams.get(), new java.io.File("."), "test");
    kit.startAndWait();
    BlockChain chain = kit.chain();
    BlockStore bs = chain.getBlockStore();
    Peer peer = kit.peerGroup().getDownloadPeer();
    Block b = peer.getBlock(bs.getChainHead().getHeader().getHash()).get();
    System.out.println(b);
    }
}

Unfortunately, kit.startAndWait() isn't available anymore.

Can someone help me to get the latest block and be able to read its values?

Thank you very much :)

Example in bitcoinj source code is exactly what you are looking for:

BriefLogFormatter.init();
// Parse command line arguments
OptionParser parser = new OptionParser();
OptionSet opts = null;
List<String> nonOpts = null;
try {
    parser.accepts("localhost", "Connect to the localhost node");
    parser.accepts("help", "Displays program options");
    opts = parser.parse(args);
    if (opts.has("help")) {
        System.out.println("usage: org.bitcoinj.examples.FetchBlock [--localhost] <blockHash>");
        parser.printHelpOn(System.out);
        return;
    }
    nonOpts = opts.nonOptionArguments();
    if (nonOpts.size() != 1) {
        throw new IllegalArgumentException("Incorrect number of block hash, please provide only one block hash.");
    }
} catch (OptionException | IllegalArgumentException e) {
    System.err.println(e.getMessage());
    System.err.println("usage: org.bitcoinj.examples.FetchBlock [--localhost] <blockHash>");
    parser.printHelpOn(System.err);
    return;
}

// Connect to testnet and find a peer
System.out.println("Connecting to node");
final NetworkParameters params = TestNet3Params.get();
BlockStore blockStore = new MemoryBlockStore(params);
BlockChain chain = new BlockChain(params, blockStore);
PeerGroup peerGroup = new PeerGroup(params, chain);
if (!opts.has("localhost")) {
    peerGroup.addPeerDiscovery(new DnsDiscovery(params));
} else {
    PeerAddress addr = new PeerAddress(params, InetAddress.getLocalHost());
    peerGroup.addAddress(addr);
}
peerGroup.start();
peerGroup.waitForPeers(1).get();
Peer peer = peerGroup.getConnectedPeers().get(0);

// Retrieve a block through a peer
Sha256Hash blockHash = Sha256Hash.wrap(nonOpts.get(0));
Future<Block> future = peer.getBlock(blockHash);
System.out.println("Waiting for node to send us the requested block: " + blockHash);
Block block = future.get();
System.out.println(block);
peerGroup.stopAsync();


Wrong testnet address generation [python] I'm trying to generate a testnet address without success.Main net address is working fine. Here is my code. The generated testnet address from this code is :CNFNz61dzQ2NQ9RCnjJFrm2de7nLbbT9xSv which is in wrong format.

import os
import ecdsa
import hashlib
import base58

#private_key = os.urandom(32).encode("hex")
private_key =
"7c7cd1c5f24b255ae113459dccdba8df3ff2e76ca0932d02f81be27311c64e32"

print "this is my private key: " + private_key

sk = ecdsa.SigningKey.from_string(private_key.decode("hex"), curve =
ecdsa.SECP256k1)

vk = sk.verifying_key

public_key = ('\04'+ vk.to_string()).encode("hex")

print "this is my public key: " + public_key

ripemd160 = hashlib.new('ripemd160')

ripemd160.update(hashlib.sha256(public_key.decode("hex")).digest())

ripemd160.digest()
#main network id
#middle_man = '\00' + ripemd160.digest()

#testnet id
middle_man = '\6f' + ripemd160.digest()

checksum =
hashlib.sha256(hashlib.sha256(middle_man).digest()).digest()[:4]

binary_addr = middle_man + checksum

addr = base58.b58encode(binary_addr)

# main address = 19kyG9Q5QXMEZSpte6fpTeo1BWKV5Pa6ch
print "testnet address: " + addr

Update:
Finally i found a solution. It seems there was a problem in line

middle_man = '\6f' + ripemd160.digest()

when importing raw bytes into a string

So I import struct and replaced the code above with:

middle_man = struct.pack('=B',111) + ripemd160.digest()

http://gobittest.appspot.com/Address  was really helpfull thanks.

You didn't post the wrong result that you get... As I am not a python specialist, and don't know the library calls, I have an idea: you may want to place your private key here, and add print(s) after every step as debug commands, and compare line by line. I just checked the privkey and the pubkey, the page returns the same result as your main address. If you enter in step 4 the "6f", you get this testnet address: "mpGvZCV4DYnVLZJWMfeCHa1L3VvC1hetT8".

When done, you can edit your question and show how you fixed it, or extend the question with your results.


P2WSH, witness_v0_scripthash: how to derive an address Is there an address associated with P2WSH scripts?
for testnet txid =6717c8971dccbf826790efc16fb357f1e225fed3448247b8556c9f13a6c0ce42, i get:

"vout": [
    {
      "value": 0.05994165,
      "n": 0,
      "scriptPubKey": {
        "asm": "0 43aac20a116e09ea4f7914be1c55e4c17aa600b7",
        "hex": "001443aac20a116e09ea4f7914be1c55e4c17aa600b7",
        "type": "witness_v0_keyhash"
      }
    }
  ]

Is there no address associated with this?

It's a Segwit output and hence does not have the address associated with it. The locking script for a Segwit transaction includes the witness version (0 in this case) and the redeem script (which is 43aac20a116e09ea4f7914be1c55e4c17aa600b7). Given that the length of the redeem script is 20-byte, this locking address is pay-to-witness public key hash (P2WPKH). Hence the redeem script is hash160 of the compressed public key.

Since Segwit was implemented with a soft fork, there are clients that have not fully updated their software. For those clients, the locking script will look in a way that anyone can spend the output. But for Segwit aware clients, they would realize that it is a Segwit transaction with 0 as the witness version.

You could create a pay-to-script-hash of the P2WPKH. By that I mean that you could embed the witness as a script and generate an address. What you need to do is take hash160 of (0x001443aac20a116e09ea4f7914be1c55e4c17aa600b7). The first byte 00 is the witness version, second byte (14) represents the bytes to push to the stack (20-bytes) and the rest is your witness. Then you can base58check encode it using a prefix of '0x05'

In the future it is expected that most clients will upgrade to Segwit. At that time, it is proposed that the address to be locked will be a base32encode of the script (0 43aac20a116e09ea4f7914be1c55e4c17aa600b7). The address will start with bc for mainnet, separated by 1 and then the encoded version including the checksum. This addresses are called Bech-32 address.

This is how the address will look. Refer BIP-173 for more details.

Mainnet P2WPKH: bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4

Testnet P2WPKH: tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx

Mainnet P2WSH: bc1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qccfmv3

Testnet P2WSH: tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7


How can I securely create a QR code from a bitcoin address? My Problem
I am trying to generate a QR code for a public bitcoin address, preferably using command-line tools. The process poses a security risk because malicious software can generate a QR code that represents an address different than the one given as input.
What Have I Tried
Searching this site and Github. I only found some unmaintained repos with very low usage.
My Question
How can I securely generate a QR representation for a bitcoin address from the command, using open-source software I can trust?

Use any software you normally use to create QR codes. Ask it to create QR for text bitcoin:<address>.
That's all you need: a QR generation tool you trust.


Why does this non-coinbase transaction not have a sender address? This is the transaction in concern: https://blockchain.info/rawtx/6b1c57d98a557b5f578c02f6c386ef049df5890ebddd01d286bf345f47c5cecc

I think it is a transaction having nothing to do with coinbase because there is a prev_out field in the items in the input array. However, there is no field "addr" in the prev_out item, unlike this transaciton: https://blockchain.info/rawtx/304b90ea66d80652f2473c0b455bfa7775fa32b2de3f170c15bfe8e65c0a7adc
and most of the other transactions.

Is there any reason for lacking an "addr" field? Could this indicate some malpractice?

the transaction 6b1c57d98a557b5f578c02f6c386ef049df5890ebddd01d286bf345f47c5cecc spends multisignature output.

blockchain.info does not resolve such kind of inputs to addresses


How do I set up a mining pool server? I want to setup a pool-server and a client image that gets work from that server.

I have access for an hour a day to about 40 computers that I can tftp boot, so once I learn how to make, configure, run, and connect to the server then I can make my image.

If you want to run your private pool with a minimal amount of extra configuration, run bitcoind with -server and some additional configuration for RPC commands. This would allow you to create a simple pool for your personal use.

However, are you sure your mining endeavours would be profitable? You'd better check my calculator website that I linked right there. You might find it not worth your time to even set this thing up unless you have some really good GPUs in those machines.


How to make a transaction with locktime on testnet? I tried to make transaction with nLocktime on bitcoin testnet. I am not able to broadcast it.
Can someone please help me to make a basic transaction with 1 input and 1 output, so that I can broadcast on the testnet. (p2pkh -> p2pkh)

Usecase:

mvvz9TNZ37fFnUHXZPUJYV3MDutbkb9ipA -> mgGUnb6BhgxzrjWau4X4WD9Lfp9YS4kMy7
Transfering: 0.017 BTC at block height 1567415 (now 1567406)

Raw transaction (before signing):

020000000140c96a4c43a5db3c57be3fd92f491a5d40ccf00afe349c596bc35fac7bbee59a000000001976a914a9156a64ea643e7c4db772c96c6a570712e0cc1988acfeffffff01a0f01900000000001976a914083b56fb8b320a6373d4738bb81496b096e8034c88acb7ea170001000000

After Signature:

020000000140c96a4c43a5db3c57be3fd92f491a5d40ccf00afe349c596bc35fac7bbee59a000000008a4730440220271919b389ed3b635522167d3e2a0201cd85d67941816af4c1638664054c078202203b93ddf929692c2a6d081ef422de9f375183fd595e8ca9e8135af86e47e47c580141043db79f05b69d34dfd3d8658a557ddb6b1a8ebca9070968b1e3833ca6b581d8a30073638dafca0bf6a5a2a08ff89ce91186fefa5a46d2a3349eb47904ab981114feffffff01a0f01900000000001976a914083b56fb8b320a6373d4738bb81496b096e8034c88acb7ea1700

How to use CLTV and CSV?

Note: Although this answer is written for testnet, it is absolutely valid for the mainnet as well. The script will be similar, just the address encoding will be different (P2PKH start with 1 vs m for testnet as we use 0x00 as prefix in address base58check in mainnet).

  I tried to make transaction with Locktime on bitcoin testnet. I am not able to broadcast it.

When nLocktime is specified, you cannot broadcast the transaction until that nLocktime value is reached. In your case, when writing this answer, the testnet height was at 1567414 while nLocktime is set as 1567415. Other than that your transaction is correct from a script point of view.

  And how to use CLTV and CSV?

CLTV and CSV are script level timelocks, unlike nLocktime and nSequence which are transaction and input level timelocks. CLTV or CSV are specified in the output locking script, and when spending those outputs, the user must set the nLocktime or the nSequence value to satisfy the locking condition.

CLTV

Using your example, below will be the script for CLTV in the outputs and the hex of the outputs. The desired block height is 1567415 which is 0x17eab7 in hexadecimal and 0xb7ea17 in little-endian. nLocktime value should be equal or greater to this number in order to spend the outputs that are locked with CLTV. So, for this transaction to go through nLocktime value should be equal to or lower than the current block height which is equal to 0x0017eaae (1567406) or 0xaeea1700 in little-endian. However, do note that when spending this output that is locked with CLTV as an input in a transaction your nsequence should be between 0xf0000000 to 0xfffffffe. Using 0xffffffff disables timelock.

"vout": [
            {
                "value": 0.01700000,
                "n": 0,
                "scriptPubKey": {
                    "asm": "b7ea17 OP_CHECKLOCKTIMEVERIFY OP_DROP OP_DUP OP_HASH160 083b56fb8b320a6373d4738bb81496b096e8034c OP_EQUALVERIFY OP_CHECKSIG",
                    "hex": "03b7ea17b17576a914083b56fb8b320a6373d4738bb81496b096e8034c88ac",
                    "reqSigs": 1,
                    "type": "pubkeyhash",
                    "addresses": [
                        "mgGUnb6BhgxzrjWau4X4WD9Lfp9YS4kMy7 "
                    ]
                }
            }
        ]

Using this output to your unsigned transaction hex, it gives the following script:

Raw transaction before signing:
020000000140c96a4c43a5db3c57be3fd92f491a5d40ccf00afe349c596bc35fac7bbee59a000000001976a914a9156a64ea643e7c4db772c96c6a570712e0cc1988acfeffffff01a0f01900000000001f03b7ea17b17576a914083b56fb8b320a6373d4738bb81496b096e8034c88acaeea170001000000

CSV

CSV is a relative timelock, so the height of the blocks in relative sense is provided. For example, in your case the testnet height was at 1567406 while you wanted the transaction to be spent at height 1567415. So your relative height is 9 blocks. We are using nLocktime for the current transaction to be the current block height which is 0xaeea1700 in little-endian.

"vout": [
            {
                "value": 0.01700000,
                "n": 0,
                "scriptPubKey": {
                    "asm": "09 OP_CHECKSEQUENCEVERIFY OP_DROP OP_DUP OP_HASH160 083b56fb8b320a6373d4738bb81496b096e8034c OP_EQUALVERIFY OP_CHECKSIG",
                    "hex": "0109b27576a914083b56fb8b320a6373d4738bb81496b096e8034c88ac",
                    "reqSigs": 1,
                    "type": "pubkeyhash",
                    "addresses": [
                        "mgGUnb6BhgxzrjWau4X4WD9Lfp9YS4kMy7 "
                    ]
                }
            }
        ]

Using this output script in the unsigned transaction hex you specified gives us:

Raw transaction before signing:
020000000140c96a4c43a5db3c57be3fd92f491a5d40ccf00afe349c596bc35fac7bbee59a000000001976a914a9156a64ea643e7c4db772c96c6a570712e0cc1988acfeffffff01a0f01900000000001d0109b27576a914083b56fb8b320a6373d4738bb81496b096e8034c88acaeea170001000000

When spending this CSV locked outputs, you will need to keep a few things in mind: (1) nSequence <= 0xEFFFFFFF; (2) nSequence's 22nd bit determines if the relative lock-time is time-based or block based. This bit should be set to 0 since your CSV is locked in blocks; (3) The value of the relative locktime, is then interpreted from the first 16 bits of the nSequence.

Although I have shown the locking scripts in its raw form (using CLTV/CSV) in scriptPubKey, it is recommended to create a P2SH locking script out of this raw script. This not only ensures that you pay lower fees for making this transaction, but also ensures your privacy (nobody will know that they transaction is timelocked) until you spend that transaction.


How to protect the early stages of a proof-of-work application? For a given cryptocurrency or other blockchain application, proof-of-work provides intrinsic security in the algorithm itself that makes it unlikely that someone can attack the network unless they have more than 50% of the computational power of the network under their control.

This makes sense and works once the network has a considerable size, but every network has to start somewhere, and when a new application is born and the number of miners is still very small, it would seem very easy to outpower the network to insert fraudulent transactions and still be the longest chain of blocks.

Is there a way to mitigate this risk?

... insert fraudulent transactions ...

No, fraudulent transactions and blocks containing them are rejected when nodes follow the consensus rules.

There is a greater risk of chain reorganisation, meaning miners who successfully mined a block may not eventually have the reward for that when their block is no longer part of the longest chain.

The great risk of a 51% attack is that the attacker could outpace the rest of the network to assert that the attacker's version of the blockchain is longer, re-writing history with valid transactions and claiming block rewards, or undoing their own transactions when re-writing history by spending the utxo's back to themselves first, making their previously valid transaction seem like a double spend, for example, and stealing from a merchant.

To protect a new proof-of-work application it is only necessary that the work is reasonably distributed. For example, in the case of a Bitcoin full clone the same ASIC miners would be valid, however, the cost-for-benefit would be very low initially and so an attacker must ask, what benefit do I derive?


Downloading of blockchain failed I’ve been attempting to set up my own wallet, but am having difficulties.  Last week I began installing the standard Bitcoin client.
When I first attempted I got to the process of downloading the blockchain.  My computer ran for about 36 hours until the process failed.  I asked on the message boards and they said there may have been some corrupted data.  I attempted to re download the blockchain, but when I reinstall Bitcoin, I now get a failed to initialize message.  I deleted the original files (except the wallet file) and still get a failed message when Bitcoin starts.  It's getting pretty frustrating.  I sent 1 bitcoin to the first address I created (though it had not yet and never did finish downloading the block chain).  Would deleting the wallet allow me to start over?

If you sent a coin there, of course you need to keep the wallet itself or you won't be able to claim that coin.

You may delete and re-download the blockchain, though.

Or you can try to open the wallet with another client.


Is bitcoin deflation a bad thing? I have read that bitcoins are relatively immune to inflation and will actually deflate in value:

  Once 21 million coins exist, they become deflationary since no new coins are issued and, as naturally occurs, money falls out of circulation as wallets are lost.

Deflationary currency sounds terrible as this would encourage people NOT to spend the bitcoins they have. Which is the opposite of what you want in a capitalist society dependent on transactions. Inflation exist for a reason, it encourages people to spend the money they have because holding on to it would mean losing value in the long run.

I would suspect that most Bitcoin advocates would disagree with you. The simplest counter-argument is this -- wouldn't that mean inflation discourages people from selling things? And you can't spend if nobody wants to sell to you, can you?

Another way to make the same counter-argument is this: Actually, no, deflation encourages people to spend the bitcoins they have. A deflationary currency should be very desirable to hold. So, if I have a deflationary currency, sellers should go out of the way to encourage me to give that currency to them (with low prices, easy transaction, stronger guarantees, whatever it takes). That will make me more likely to buy things.

Of course, all of these arguments are nonsense. The characteristics of the money affect the buyer and seller equally. So while they may change the price, they won't change the likelihood the transaction will occur.

But it won't even matter. Long-term predictable monetary deflation is impossible (for a low friction, demurrage-free currency) because it entails a direct contraction. If you assume long-term, predictable monetary deflation, you get the following paradox:

One unit of currency today must be worth less than one unit of currency tomorrow. Otherwise, you don't have long-term, predictable deflation.
One unit of currency today must be worth more than one unit of currency tomorrow. This is because one of the things you can do with a unit of currency today is hold it until tomorrow. But you can also spend it today if you want. So it has to be worth at least as much.

These two arguments directly contradict each other.

Yes, you have been lied to by economists who want to convince you that the economy will explode if the government doesn't enrich itself and favored bankers at the expense of everyone else. That's not to say deflation can't cause real problems, just not this kind of deflation and these kinds of problems.


Bitcoin -> prepaid VISA/Mastercard service (2014 edition)? I have read the answers in this question here... But it is incredibly outdated. OKPay no longer accepts Bitcoin to creditcard. bitcashretail.com is down. xmlgold.eu results into an error. Centregold results into a page not found. ecardone.com is seized by the "Global Illicit Financial Team"
Etc, etc, etc...

So I think it is time for a new edition of the bitcoin to virtual creditcard question.

There is not a single available solution to go to a general VISA/MC/AMEX card in the US today. Money Transmitter laws (and a host of other regulations) make this a very difficult proposition at the moment.

Some other countries don't have the same issues today, like Canada http://paymentweek.com/2013-11-4-canada-introduces-bitcoin-debit-card-services-238461/ but these solutions are also still in development.


If SHA256 and/or RIPEMD-160 were broken, would all bitcoin addresses be compromised? If not, what else would be needed to steal all funds from all people and completely break bitcoin?

I bet some will say ECSDA gives bitcoin an additional layer of protection. I counter this by saying ECSDA is dependent on a hash function such as SHA256. So I will ask this as well: What kind of ECSDA does bitcoin use and would it still be protected if SHA256 were broken?

Yes, I know I am illustrating an unlikely scenario but I still believe we should know what will happen.

If you want to mention other hash functions in relation to SHA256, you can. Feel free to explain how RIPEMD-160 would keep bitcoin safe in case of a SHA256 exploit.

Bitcoin uses SHA256 followed by RIPEMD-160, which I'll collectively call HASH160.

Good hashes have 4 properties:

it is easy to compute the hash value for any given message
it is infeasible to generate a message that has a given hash
it is infeasible to modify a message without changing the hash
it is infeasible to find two different messages with the same hash

Source: Wikipedia

We care about properties 1, 2, and 3. We know for a fact that property 1 is true about HASH160 - we can benchmark it. If properties 2 or 3 were false, then you could steal bitcoins. Not good.

It's a good thing that the scripting language is so flexible, and would allow people to switch to a different address type without forcing everyone to upgrade.

This is a current bitcoin transaction script:

 OP_DUP OP_HASH160 09432ab39083b5098b6f09432ab39083b5098b6f OP_EQUALVERIFY OP_CHECKSIG

Here's how that might change if HASH160 were broken:

OP_DUP OP_HASH256 09432ab39083b5098b6f09432ab39083b5098b6f09432ab39083b5098b6f826496 OP_EQUALVERIFY OP_CHECKSIG

Note that we've swapped HASH160 for HASH256. Or, assuming both were broken:

<pubKey> OP_CHECKSIG

Now we're forgoing hash functions entirely and putting in the ECDSA key explicitly. However, this would make bitcoin addresses about a hundred characters long.


Total number of hashes performed for bitcoin purposes? I would like to estimate the total number of hashes (double SHA-256) that have been performed for bitcoin purposes.

As an estimate, I downloaded mining stats, massaged the numbers (assuming the rate shown is for the period ending at the date indicated and starting at the date before), came to 201⋅1024 hashes (equivalently 287.38 or 288.38 SHA-256) on Oct 28, 2017.
[update: 517⋅1024 hashes that is 288.74 or 289.74 SHA-256 by May 4, 2018].

Did I goof badly in that estimation of the hashes used for mining?

What other comparably non-negligible number of hashes is performed for bitcoin purposes, and how can that be estimated?

Clarifying: I'm looking only for things that represent a sizable fraction of the number of hashes spent for mining, say at least 0.5%; I'm totally willing to ignore the rest.

Assuming the numbers in the link are correct, then I think this would be right.

I got the same result by multiplying every entry by (1,000,000,000,000 * 3600 * 24 * 2) and adding them up. Came out to 2.008E^26.

But the total number of hashes is much higher. Every block in the blockchain is hashed by every client, every transaction is created using several hashes, etc, etc.


Is there a platform where I can use Bitcoins to gamble online? And do I have to signup for these services and/or verify my identity?

There are several. One of the first and most established is Satoshi Dice.

As far as I read you need not verify your identity but I haven't used it myself.


can attacker and honest node in double spend ever tie? in bitcoin white paper there are only attacker and honest nodes.
you have p, and q for probabilities.

in double spend attack, in bitcoin whitepaper, can we talk about possible tie of attacker and honest nodes ? is a tie possible and what does it mean if it is possible ? in terms of block chain and blocks ?

Bitcoin consensus is never final, but instead just becomes increasingly stable as more blocks are added.

In the example in the whitepaper a successful attacker will spend some amount of time "tied" but this tie will eventually be resolved by additional blocks. If the additional blocks are on the attacker's fork then it will resolve in the attacker's favor.


How to make sure Electrum connects to my private Electrs server and to no other server? I want to connect my Electrum wallet app to my private Electrs server in my local LAN which is also reachable via onion. I want to just use this one server, no other server. My ~/.electrum/config is
{
    "alias": "",
    "auto_connect": false,
    "blockchain_preferred_block": {
        "hash": "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",
        "height": 0
    },
    "check_updates": true,
    "config_version": 3,
    "gui_last_wallet": "/Users/$USER/.electrum/wallets/default_wallet",
    "is_maximized": false,
    "oneserver": false,
    "proxy": "socks5:127.0.0.1:9050::",
    "recently_open": [
        "/Users/$USER/.electrum/wallets/default_wallet"
    ],
    "rpcpassword": "",
    "rpcuser": "",
    "server": "something.onion:50002:s",
    "show_channels_tab": true
}

This seems to work fine in the sense that I am connected. But I have a lot of nodes in my list under the "Network" settings in Electrum. And this is because the oneserver property is set to false. If I try to set it to true in the config manually, Electrum starts and works fine but the config file is reverted to its old state with false in it.
How can I make sure this works?

I don't know why this happened several times. But in the end the config worked with true and now my nodes show only one connection and this is the private server.


How can coinbase transactions be created? How can a coinbase transaction be created and what would happen if there was more than one coinbase transaction in a block?

The current bitcoin system does not allow to create a block with two coinbase transactions.
The rules are described here.
So a player against the system would need to craft such a block manually, which would get rejected, and eventually the node would get banned.

Hint: as his is a basic question of how bitcoin works, I recommend to read the technical articles on bitcoin.org, as well as the article on protocol specification in the link. And on top Andreas‘ book „Mastering Bitcoin“ gives a deep insight into the bitcoin world. It is also online available, in many languages. Highly recommended!


Can one node receive two transactions from the same user (doublespend)? I'm learning how the blockchain works. I've read that when someone (say Alice) send twice a transaction to two different peoples (Bob and Charlie) such that Alice has only enough to pay Bob or Charlie, not both, then the first validated block containing of the two transactions will be accepted and the other will be rejected.

My question is : What happens if the two transactions Alice -> Bob AND Alice -> Charlie are sent to the same node and that node validates its block ? Is it possible ? If not, why ?

No that would not be valid, the node would reject the second transaction it saw, because it would know the UTXO was already spent by the first one. If a miner tries to include both in a block, that block would be invalid too for the same reason.

The exception is if the first transaction signalled to opt in to Replace-by-fee and the second transaction had a high enough fee to replace the first one. (BIP 125)


What external systems is Bitcoin commerce dependent on? If there was a concerted effort to "shut it down", where are the vulnerabilities?

The potential for the Bitcoin client to communicate with other Bitcoin nodes has been discussed at length, but what about the other parts of the Bitcoin ecosystem that have we become dependent upon?  If they disappear (e.g., denial of service, or taken down), will Bitcoin continue to function as a currency and payment system?

What are the most important systems that we are dependent on and how are we affected as a result if services from these systems end?

For an example of one such service -- what would be the effect if BlockExplorer.com were to be forced offline.

Whereas Block Explorer might be a useful tool, Bitcoin could survive without it.

Most important parts of the Bitcoin ecosystem, asides the main client that is, are the exchanges. They give the currency its value and without them, Bitcoin would become a fringe technology (no merchants would deal in it, as they couldn't pay their taxes with it.

Then we have the mining software and to a lesser degree the hardware (FPGA boards and the like). Should those be gone or less available it would be easier to launch a 51% attack on the network.

After that there are the mining pools. If they would disappear the miners would have a harder time earning a predictable wage. This dependancy has been mitigated with P2Pool though, so the impact is smaller than it was earlier.

After that the services are less essential. Losing the Bitcoin Forum, Wiki, SE, WeUseCoins or the like might make it harder for new people to get into Bitcoin, but wouldn't make it less functional.


How exactly can I generate a transaction id? I'd like to create a transaction object from scratch. I've read that the tx id for a transaction is the double SHA-256 hash of a serialized transaction, but havent been able to find details on exactly how the data is formatted before its serialized or how it is serialized for that matter.

Could someone, perhaps, provide an example of how the data is organized before it's serialized and/or describe the manner of serialization taking place?

The serialized format is described here.


How to create a sending address with Bitcoin Core? I downloaded Bitcoin Core and I'm just having a look around and I can't for the life of me figure out how to create a sending address.

I'm using a site to buy stuff and to register I need to "Setup your payout addresses" which is "the address where centralised escrow is released to the seller, and where buyer refunds are sent".

So, what do I do?

You are not looking for a sending address but for a receiving address!

Coins always come from the address that you received them to, so one doesn't need special "sending addresses". Your purpose here is to enable the escrow to send you a refund in case something goes wrong with the purchase.

To find out your address, switch to the "Receive" tab:

The "Receive" tab will show you a list of all your addresses. The list will be empty at first, so you have to click "Request payment", which will open a new window showing your address:

You'll want to copy the alphanumeric string after "Address:" in the last line. To show the address again after closing the window, you can double-click the line in the list, or select it and click the "Show" button in the bottom left corner.


What are some other uses for blockchain instead of money? What has blockchain been used for aside from money in the 10 years its been around?

I know things like etherium exist, but They don't seem be going anywhere, most of its value seams to come from the hope that someday someone will fond a use for smart contracts.

So has someone found a n alternative use for blockchain yet?

Colored coins have used the blockchain to record the creation, ownership, and transfer of extrinsic assets other than bitcoin. Here's an excerpt from Mastering Bitcoin

  Colored coins are used to track digital assets as well as physical assets held by third parties and traded through colored coins certificates of ownership. Digital asset colored coins can represent intangible assets such as a stock certificate, license, virtual property (game items), or most any form of licensed intellectual property (trademarks, copyrights, etc.). Tangible asset colored coins can represent certificates of ownership of commodities (gold, silver, oil), land title, automobiles, boats, aircraft, etc.

This chapter mentions other use cases like Proof-of-Existence (Digital Notary), Kickstarter (Lighthouse), and Payment Channels (The Lightning Network). But I guess the later two still involve money.

Source: https://github.com/bitcoinbook/bitcoinbook/blob/develop/ch12.asciidoc


Will every message x reach all connected peers in time t? I've asked similar question here:
Is gossip protocol in Bitcoin perfect?
But I didn't get an answer to my question really. I am ideating a consensus algorithm and I need definitive answer.

Can we take for granted that if in time period t there were 10,000 connected peers (no new peers connecting, no peers disconnecting), all with good internet connection and hardware, then if every of those 10,000 peers originated one transaction (or any kind of message) to his peers, can we take for absolutely granted that eventually every single one of those 10,000 connected peers have in his mempool all 10,000 transactions, including his own and those of 9,999 other peers and absolutely no transaction will be missing in mempool of any of those nodes (they will all have same set of data)? If yes, and would could be estimated time (seconds, minutes, hours)?

And now: things like double-spends, transaction correctness, peers connecting and disconnecting from network, etc. that happens in real cryptocurrency systems are not relevant here - this is a theoretical question and a theoretical situation.

Can we take for granted that if in time period t there were 10,000 connected peers (no new peers connecting, no peers disconnecting), all with good internet connection and hardware, then if every of those 10,000 peers originated one transaction (or any kind of message) to his peers, can we take for absolutely granted that eventually every single one of those 10,000 connected peers have in his mempool all 10,000 transactions, including his own and those of 9,999 other peers and absolutely no transaction will be missing in mempool of any of those nodes (they will all have same set of data)?

If you also include that no one is acting maliciously, then yes, under these perfect conditions with no malicious actors, you take for granted that a transaction will reach all nodes within some unknown time t. However, if there are malicious actors, then no.

  If yes, and would could be estimated time (seconds, minutes, hours)?

This is impossible to know. It depends on the hardware, what the transactions consist of, the internet connection, etc. At best, it would probably take a few hundred milliseconds. At worst, likely a few minutes. Without more specific parameters, it is impossible to know.


Directory of Mining Hardware Companies Are there any well-curated directories of Bitcoin mining hardware manufacturers?

The current king of the hill is BitMain and their AntMiner S9. They provide 14 Th/s, but it's sold out at the moment.

Unfortunately, the industry changes so fast that it's hard to have anything current. Companies go bankrupt, new manufacturers appear out of nowhere and it's hard to keep up. The best directory of manufacturers and their wares is here:

https://en.bitcoin.it/wiki/Mining_hardware_comparison


How to handle return address Output field using bitcoin bip 70? More specifically, how do I derive the return address from the Output field in a protocol buffer Payment object?

I can convert the serialized byte string from the 'script' field of the Output into a 25 character scriptPubKey but I'm stuck as to where to go from here?

Any help greatly appreciated :)

I managed it with Petrer Todds python-bitcoinlib.

Link to payments_pb2 proto file here.

import bitcoin

## Uncomment for testnet
#bitcoin.SelectParams('testnet')

import payments_pb2

from bitcoin.wallet import CBitcoinAddress
from bitcoin.core.script import CScript

def protoresponse(httprequest):

    ## Object
    o = payments_pb2

    ## PaymentACK object
    pao = o.PaymentACK()
    pao.payment.ParseFromString(httprequest.body)

    refund_address = CBitcoinAddress.from_scriptPubKey(CScript(pao.payment.refund_to[0].script))

    return httpresponse


How to get sending address of a deposit using coinbase api I am trying to integrate the Coinbase API to my website. I need to communicate with Coinbase's wallets (bitcoin, bitcoin cash etc.) programmatically. Currently I can create different wallet addresses using the API and also I get notified when buy or sell transactions happen.

But I need to know is it possible to get incoming address when a deposit occur to one of my address from outside or another account of Coinbase.

No it is not possible because to get the "sending address" because such things do not exist in Bitcoin. There is not "send from" address in Bitcoin transactions. Furthermore many transactions will "send from" multiple addresses (i.e. they have multiple inputs).


What happens to my bitcoins if there's a permanent fork in the chain? Let's say the year is 2034 (optimistic?) and the New New World has adopted Bitcoin as its currency, and now there's a civil war, and naturally the two sides want to have their own version of Bitcoin ... hence a fork.

A permanent fork as far as anyone can tell.

What happens to my bitcoins in such an event?

If originally I owned BTC 1,000, do I now own BTC 1,000 and BTC2 1,000 separately after the fork, or is it just BTC 1,000, or do I have to choose between the two chains (i.e. I get either BTC 1,000 or BTC2 1,000 but not both), or do I lose all my BTC unless I redeem them for either BTC1 or BTC2 ... or what?

I understand that forking Bitcoin into two or more currencies might reduce its value more than proportionately against real goods and services, which is to say that BTC2 10,000 might not buy you what you could have got for BTC 1,000 before the fork event, and we could get into the economics of that, but that's not my question. My question is specifically about the nominal and not the real, i.e. how many bitcoins I now own as opposed to what my bitcoins can now buy.

The question is too speculative to answer. The groups could institute whatever rules they want.

If you assume there's a group that's willing to modify the software to create a permanent fork, presumably they are doing so for some reason. And whatever that reason is, that will affect what changes they make that cause the fork.

They could decide to allow people to transact on both chains. Or they could demand that you send the Bitcoins to a Bitcoin eater in the other chain before they allowed you to move them.


Bit coins disappeared I bought a bit of a bit coin some years ago and forgot about it the the other day had a look and converted a small amount into an ether wallet. I came back the next day and found the bitcoin wallet empty and transferred as per screen shot. Can anyone help. If any more info needed please say.

You have been robbed, sorry.

Use a strong password/better seed next time.


"Hidden Wallet" onion site I was assigned a wallet by "Hidden Wallet" onion site - my BTC never arrived cause its a scam. I have the wallet address and proof that it was assigned to me under username and password - Can I get my bitcoins back or send from that wallet to another ?

Based on a Bitcoin address you cannot get your money back. You also need a private key for that.

As the developer of the real HiddenWallet, which is a desktop application, not an online website I encountered this scam many times. Your money is lost, sorry about that.

One more thing to consider is, if you were using the same password at other places, then you probably want to change it.


Is the transaction database ever shortened? I just downloaded the bitcoin client and the full transaction database and did not fail to notice that it took me more than a day to download and check the transaction database and that it occupies more than 2 GB of diskspace.

What will happen when the number of transaction will grow to several millions a day?

Will the Database grow over a TB?
Is that even viable ?

Meni's answer is probably correct, but describes a very far future, in my opinion.

In the more near future, I believe we'll see fully-validating nodes that do not keep the entire block chain around. The current reference client implementation uses blockchain + transaction database for validation, which cannot easily support pruning. I'm working on modifying the validation code to use a separate database of just the unspent outputs instead, which is much more efficient and only requires a few hundred MB of storage, in addition to the blocks it wants to keep around.

I'm sure this will open possibilities, but somewhat further ahead, I believe this will lead to a separation between validation nodes and archive nodes. The former relay and can be queried for their memory pool, and check whether transactions are valid, but they cannot serve old transactions or blocks, and hence cannot be used to bootstrap a new node from. For these purposes, one will connect to an archive node (this could be via the P2P protocol, but may as well be HTTP or BitTorrent).

Disclaimer: these are my views/opinions, and may not reflect those of other (core) developers.


How is BID and ASK Calculated for crypto currencies? I am trying to create a graph to moniter order data, similar to:

http://www.cryptocoincharts.info/orderbook.php?pair=pc-btc&market=bittrex

I am using the cryptsy api (http://pubapi.cryptsy.com/api.php?method=orderdatav2) to fetch all the order data and for each coins it returns some thing like:

          "price": "395.00000000",
          "quantity": "0.00100000",
          "total": "0.39500000"

The question that I have is, is there any formula or some thing to calculate bid and ask, so that I can plot the graph?

Thanks.

Generally, the ask price displayed by the exchanges is the sell order at the lowest price. Ask is another way of saying sell. So Ask order = Sell order.

The same for bid orders. The bid price is the buy order at the highest price.

Speaking for the result of the below API call:

http://pubapi.cryptsy.com/api.php?method=orderdatav2

The order with lowest price among the "sellorders" is the Ask.

The order with the highest price among the "buyorders" is the Bid.

This is true for any trading pair.

There seems to be pairs where "buyorders" is null. That is either an error on their part or there are no bids for those pairs.


How do I Base58 Checked encode / decode an address in C#? What does "normalize leading zeros" mean? I am trying to encode and decode a Base58 address in C#.  The following function is a start, but it has a few issues:

This code does not normalize leading zeros (what does that look like?)
If this method is repeatedly called in rapid succession many string objects will be created, putting pressure on the GC

.NET 4.5 Code

Note add a reference to System.Numerics

BigInteger  bi =  System.Numerics.BigInteger.Parse("00010966776006953D5567439E5E39F86A0D273BEED61967F6", NumberStyles.HexNumber);

string b58 = EncodeBase58(bi);
Console.WriteLine(b58 + Environment.NewLine + "16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM");

   /// .... SNIP

   public static String sBase58Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
    public static String EncodeBase58(BigInteger numberToShorten)
    {
        // WARNING: Beware of bignumber implementations that clip leading 0x00 bytes, or prepend extra 0x00
        // bytes to indicate sign - your code must handle these cases properly or else you may generate valid-looking
        // addresses which can be sent to, but cannot be spent from - which would lead to the permanent loss of coins.)

        // Base58Check encoding is also used for encoding private keys in the Wallet Import Format. This is formed exactly
        // the same as a Bitcoin address, except that 0x80 is used for the version/application byte, and the payload is 32 bytes
        // instead of 20 (a private key in Bitcoin is a single 32-byte unsigned big-endian integer). Such encodings will always
        // yield a 51-character string that starts with '5', or more specifically, either '5H', '5J', or '5K'.   https://en.bitcoin.it/wiki/Base58Check_encoding
        const int sizeWalletImportFormat = 51;

        char[] result = new char[33];

        int i = 0;
        while (numberToShorten >= 0 && result.Length > i)
        {
            var lNumberRemainder = BigInteger.Remainder(numberToShorten, (BigInteger)sBase58Alphabet.Length);
            numberToShorten = numberToShorten / (BigInteger)sBase58Alphabet.Length;
           result[result.Length - 1- i] = sBase58Alphabet[(int)lNumberRemainder] ;
           i++;
        }

        return new string(result);
    }
    //public static long DecodeBase58(String base58StringToExpand)
    //{
    //    long lConverted = 0;
    //    long lTemporaryNumberConverter = 1;

    //    while (base58StringToExpand.Length > 0)
    //    {
    //        String sCurrentCharacter = base58StringToExpand.Substring(base58StringToExpand.Length - 1);
    //        lConverted = lConverted + (lTemporaryNumberConverter * sBase58Alphabet.IndexOf(sCurrentCharacter));
    //        lTemporaryNumberConverter = lTemporaryNumberConverter * sBase58Alphabet.Length;
    //        base58StringToExpand = base58StringToExpand.Substring(0, base58StringToExpand.Length - 1);
    //    }
    //}

To normalize leading zeros is documented in this link, namely this text at the bottom:

  In a standard base conversion, the 0x00 byte on the left would be
  irrelevant (like writing 052 instead of 52) but in the BTC network the
  left most zero chars are carried through the conversion. So for every
  0x00 byte on the left end of the binary address, we will attach one
  '1' character to the Base58 address.  This is why the main-network
  addresses all start with 1.

The following code will address the GC issue with over-allocation and discarding of the String type, however it  does not properly handle the leading zero bytes.  I either need to find a list of expected lengths per type or some other approach.

    public static String sBase58Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
    public static String EncodeBase58(BigInteger numberToShorten)
    {
        // WARNING: Beware of bignumber implementations that clip leading 0x00 bytes, or prepend extra 0x00
        // bytes to indicate sign - your code must handle these cases properly or else you may generate valid-looking
        // addresses which can be sent to, but cannot be spent from - which would lead to the permanent loss of coins.)

        // Base58Check encoding is also used for encoding private keys in the Wallet Import Format. This is formed exactly
        // the same as a Bitcoin address, except that 0x80 is used for the version/application byte, and the payload is 32 bytes
        // instead of 20 (a private key in Bitcoin is a single 32-byte unsigned big-endian integer). Such encodings will always
        // yield a 51-character string that starts with '5', or more specifically, either '5H', '5J', or '5K'.   https://en.bitcoin.it/wiki/Base58Check_encoding
        const int sizeWalletImportFormat = 51;

        char[] result = new char[33];

        Int32 iAlphabetLength = sBase58Alphabet.Length;
        BigInteger iAlphabetLength2 = BigInteger.Parse(iAlphabetLength.ToString());

        int i = 0;
        while (numberToShorten >= 0 && result.Length > i)
        {
            var lNumberRemainder = BigInteger.Remainder(numberToShorten, iAlphabetLength2);
            numberToShorten = numberToShorten / iAlphabetLength;
           result[result.Length - 1- i] = sBase58Alphabet[(int)lNumberRemainder] ;
           i++;
        }

        return new string(result);
    }