Why not use address in raw transaction instead of public key bytes In raw transaction, bitcoin using bytes of the public key, like:
042daa93315eebbe2cb9b5c3505df4c6fb6caca8b756786098567550d4820c09db988fe9997d049d687292f815ccd6e7fb5c1b1a91137999818d17c73d0f80aef9

It takes a lot of bytes.
Technically, can we use bitcoin addresses (e.g.1MBngSqZbMydscpzSoehjP8kznMaHAzh9y ) instead to make the blocks smaller?

In raw transaction, bitcoin using bytes of the public key, like:
042daa93315eebbe2cb9b5c3505df4c6fb6caca8b756786098567550d4820c09db988fe9997d049d687292f815ccd6e7fb5c1b1a91137999818d17c73d0f80aef9

Technically the raw transaction contains the Script, which usually is written with Bitcoin script that is a stack-based language. It can contain the PubKey in the old scripts, like P2PK but the community is making a big effort to move the bitcoin users to use the script that contains the hash of the public key. The script like Pay-to-Public-Key-Hash (P2PKH) or pay-to-witness-public-key-hash (P2WPKH).
from the script, it is possible to calculate the address but not vice versa.
In conclusion, all the addresses have a conversion like:

P2PK, P2PKH: Start with 1.
P2SH: start with 3.
P2WSH, P2WPKH: Start with bc or with 3.

At this point, the answer should contain a resume of all the types of script and how the script is built, and also an introduction to the not standard script that is used extensively from the lightning network protocol.
But I think a very good summary is inside these two chapters of the Bitcoin book 'Transactions' and 'Advanced Transactions and Scripting', I can't do better
Update
I'm not a fan of theory, maybe you can use also this code example to understand how the script is converted on a Bitcoin address.
Decompiler Bitcoin Script.
it is only an example of the conversion that could be done.
The usage of the example code is described inside the bash script run-decompiler.sh
An example with the following block is the following ./Decompiler 76a914536ffa992491508dca0354e52f32a3a7a679a53a88ac
With the following result
----------------------------------------| Results |-----------------------------------
                               ###  Script PAY TO PUBLIC KEY HASH  ###
  Raw Script PubKey: 76a914536ffa992491508dca0354e52f32a3a7a679a53a88ac

OP_DUP OP_HASH160 536ffa992491508dca0354e52f32a3a7a679a53a OP_EQUALVERIFY OP_CHECKSIG

 The address: 18cBEMRxXHqzWWCxZNtU91F5sbUNKhL5PX
 The Hash160 pubkey: 536ffa992491508dca0354e52f32a3a7a679a53a
 The P2PSH address: 39JC9tvQ5CANbfuPgUZ4Zdc227m5uQnMRB

 https://blockstream.info/address/18cBEMRxXHqzWWCxZNtU91F5sbUNKhL5PX
______________________________________________________________________________________

See the result here https://blockstream.info/address/18cBEMRxXHqzWWCxZNtU91F5sbUNKhL5PX
Please consider this example as an example of code, I developed this to understand how de script works. Can contains error. I will work to integrate this in my project and I will maintain this post update.
To answer at your comment that is

Thanks. I use you the code linked, the the result address codepad.org/nRJhvMC3 does not match the expected address blockchain.com/btc/block/1 So what's the usage of this Decompiler?

The decompiler takes the hex of the script and try to calculate the corresponding address if it is a standard script.


What is a likely solution to Bitcoin's energy consumption problem? If the price of Bitcoin continues to climb, the total energy consumption of the system will increase proportionally at least until 2020 when block reward halves. It is not unlikely that at this point the price of Bitcoin will have increased so much that energy consumption will be unsustainable in a way that Bitcoin will be opposed by a large proportion of global society (we are still below 1% of total electricity consumption but a 10-fold price increase could change that quickly).

I see the same options that are laid out in this article:

Bitcoin will be abandoned and people just use something else
the protocol is changed to reduce the block reward earlier than 2020
the protocol is changed to exchange Proof-of-Work for something else (maybe Delegated Proof-of-Stake?)

since 2 and 3 will almost certainly result in a fork, they are related to 1. I feel that a solution will have to be found, I'm just wondering if I missed another option and which of the options is most likely.

I feel that a solution will have to be found

I'm not sure I agree there is a 'problem' that needs to be explicitly fixed. The article you linked explains the relationship between price and electricity usage, now remember that price is a measure of the demand (since the supply is fixed and known).

So the market acts as a naturally regulating force: as people pay more and more to buy and use bitcoin, the network's power consumption will increase (and vice versa). So to say "bitcoin uses too much energy!" is to say "bitcoin is worth less than the current market value!". The article linked supports this point, but you kind of have to 'read between the lines' to realize it is true.

Consider gold mining: if the price of gold were to rise, then it would become profitable to start mining gold in places where a more expensive  processes will be needed to extract the gold from the earth. Is it a problem that companies will spend a lot of energy to get this extra supply that is now worth while?

Interestingly, consider what happens if the demand for bitcoin continues to increase, to the point that the network is in direct competition with all other use cases for power. In that case, for the btc price to increase, electricity prices would have to be increased, effectively spreading the cost of mining across all of the world's energy usage (because if the demand for bitcoin did not exist, everyone would be paying less to power their home appliances, etc).

I think it is easy to say "this is a problem!!", but the less obvious realization is "bitcoin is using this much energy because the market considers it useful enough to be worth the cost"

  I'm just wondering if I missed another option and which of the options is most likely.

I don't think any of the three options you listed are likely to happen.

Another 'option' to consider is this: once mining chips become commodity (more easily and readily available from multiple suppliers), I think the nature of the mining competition will change. If everyone has access to good ASIC chips, then there will be immense competition to develop and utilize the cheapest sources of power available. What if bitcoin miners must help fund the development of ultra-efficient solar panels in order to maintain a competitive advantage? This is how ASIC miners were developed, why can't the same happen for another variable in the mining industry?

If this occurs, rather than the energy consumption of the network being a problem, it becomes an incentive for finding a solution to the larger issue of 'needing to develop green sources of power'.


Are old rev*.dat file safely deletable? based on this answer rev files contains information for dealing with reorgs.
If I think reorg longer than let's say a month are highly unlikely, could I safely delete rev*.dat files older than a month?

No. You need the rev*.dat files as much as you need the blk*.dat files. If Bitcoin Core cannot find the rev*.dat, it will need to regenerate them by reindexing the databases. Removing them effectively corrupts the databases.

If you want to save disk space, you can use pruning instead. This will have Bitcoin Core properly remove blk*.dat and rev*.dat files to save disk space.


What is a cost-efficient, fast and easy method of transferring btc between own computers? I use a few computers and would like to perform bitcoin transactions from any of them. Thing is, I'm not very fond of the idea of paying the fee and waiting every time I want to transfer the coins from one computer to another. Is there any other simple, convenient, easy "out of band" method of transferring coins between computers?

(I realize an online wallet service would solve my problem but I really don't like the idea of trusting a 3rd party with my bitcoins)

[Edit: Read comment as to why this is not a good idea.]

You could just store the wallet.dat file on both computers, which contains your entire wallet. Then both computers will be able to spend from the same wallet.

Do make sure to copy the wallet to the other computer from time to time: if you don't synchronize regularly, the balances might start mismatching because the private keys are no longer the same.


CScript to CPubKey or derive CPubKey from CScript Please can someone advise if it is possible to derive the CPubKey from a CSript object? Provided i get it up with an address before hand,

I can use numerous functions to attain all the info from the CPubKey using functions, but can you make a CPubKey from a CSript?

Or are they too much chalk and cheese?

Thank you,

EDIT:
Following the first answer I've tried the below to no joy. The script returns totally empty:

CScript scriptPubKey1;
CBitcoinAddress address("L4VPgtoBtuxsYMgyrRvQRadSV1Y139TDfd");
scriptPubKey1.SetDestination(address.Get());

CScript::const_iterator it = scriptPubKey1.begin(); // or specifically, the location of the pubkey in the CScript object
opcodetype opcode;
std::vector<unsigned char> data;
scriptPubKey1.GetOp(it, opcode, data); // data now contains the byte vector

CPubKey pubkey3 = CPubKey(data);

If I understand the question, I believe you can construct a CPubKey from a byte vector extracted from the CScript script like:

CScript::const_iterator it = script.begin(); // or specifically, the location of the pubkey in the CScript object
opcodetype opcode;
valtype data;

script.GetOp(iterator, opcode, data); // data now contains the byte vector
CPubKey pubKey = CPubKey(data);


How to determine the peer/node that created a transaction? You're running your node and you receive a transaction from a peer, how do you determine if that peer created the transaction or if it is simply relaying the transaction. In other words, can you map transaction creation to a peer?

how do you determine if that peer created the transaction or if it is simply relaying the transaction

You cannot, at least not with absolute certainty. This is by design: it helps preserve the privacy of users on the network.

That said, if you decided to run a whole bunch of nodes, and positioned them carefully in the network graph, then you could start to infer where transactions are originating from, based on the timing of your nodes hearing about said new transactions. I think it should be expected that chain analysis firms are doing this today.

To counter this, it must be considered that there are many ways to publish a transaction to the network - the node that first publishes a transaction is not necessarily owned or operated by the user that actually crafted the transaction. For example, today there exists services within the tor network, which allow you to copy/paste a signed transaction into a website form, to be broadcast to the network anonymously. Since you must connect to this service over tor, not even the service provider will know the identity of the transaction's author.

Further work is being done to increase the privacy of transaction broadcast. For example see BIP 156.


What are good ways to storing backup of an encrypted wallet? What are good ways and places for storing backup of an encrypted wallet?

When somebody open encrypted wallet what all can he do when he does not have a key?
asuming that the key to the wallet is e.g. 73 trilion years far to cracking

You can back it up pretty much anywhere. USB drive, backup hard drive, Dropbox.

If your wallet is encrypted, all they can see is what addresses you own and how many bitcoins they have. They cannot send any bitcoins or get the private keys.


What is the bandwidth of the standard bitcoin client as at August 2013? A question about bandwidth was asked and answered in Nov 2011... we are now Aug 2013 and the usage of bitcoin has grown enormously since then.

So just as an update to that question I ask it again with the benefit of being here and now. I hope this is allowed.

Since we've already asked this question, let's try to re-answer it with some additional insights:

Without mining or relaying, in order to participate in the network, one would need enough time to download all transactions within a block before the next block is found in order to stay synced with the network. Considering that a block has a maximum size of 1 Megabyte and that the block time is about 10 minutes, this puts the theoretical minimum download speed at about 1 Megabyte per 10 minutes or 1.7kbps (according to Google)-- much slower than a dial up modem. Notice that this figure is constant -- so the size of network does not dictate how much bandwidth is required to participate in the network, so this was true in 2011 and will be true in the future.

In the original question, we wanted to run a wallet from work. If all we want to do is trade bitcoin, this should be fine (provided that you do download the initial values for the block chain outside of work), but to do more on the network...

If we're relaying transactions, not just downloading them, the calculations can vary wildly. Here our bandwidth should be proportional to the number of transactions posted per second (which should be predictable) as well as the number of node to which you are connected (which isn't easily predictable).

If we're mining, you're going to have to broadcast your mined blocks, which as mentioned before, can have a maximum size of 1 MB, and you're going to want to broadcast this as fast possible -- not just within the 10 minutes. You could put the theoretical minimum required upload speed at 1.7kbps, but it's simply not practical.

I realize that this doesn't the question about how much average-bandwidth clients us, but if you're only posting and reading transactions, we shouldn't need more than about 1.7kbps. If you begin mining and relaying, we're going to need more, but it's hard to predict how much.


Network admin blocks P2P, Bitcoin clients can't connect My university network admins seem to block P2P networks. So I can't download totally legit Linux distros via BitTorrent ;-)

Unfortunately, this also affects Bitcoin wallets such as MultiBit or Bitcoin Wallet on Android.

How can they block all the P2P while leaving other services working? How do I make the client connect?

You can use a proxy with -proxy, a VPN, or Tor.


Blockchain wallet Outgoing Payments I want to Send bitcoin from my wallet to another bitcoin address.
I have been working on their API.

  http://localhost:3000/merchant/$guid/payment?password=$main_password&second_password=$second_password&to=$address&amount=$amount&from=$from&fee=$fee

This is what i tried to do.

But here the amount is bit confusing to me. My product price is  0.03000000 BTC.
So what will be the value of $amount ?

Official documentation says: $amount Amount to send in satoshi.

And what will be the value of $fee ?

Documentation: https://blockchain.info/api/blockchain_wallet_api

A Satoshi is the smallest fraction of a Bitcoin that can currently be sent: 0.00000001 BTC, that is, a hundredth of a millionth BTC. In the future, however, the protocol may be updated to allow further subdivisions, should they be needed.

Further examples of units

1 BTC = 1,000 mBTC (millibitcoin)
1 BTC = 1,000,000 μBTC (microbitcoin)
1 BTC = 100,000,000 Satoshis
1 mBTC = 100,000 Satoshis
1 μBTC (microbitcoin) = 100 Satoshis

So $amount will be 100000000*0.03 = 3000000

and $fee will be Transaction fee value in satoshi (Must be greater than default fee) (Optional)


Explain how unused addresses in wallet.dat have no balance when mining occurred for many months I have a wallet.dat file with many zero transaction/(unused) addresses in it with keys assigned to each address.  I’ve done research and there’s quite a bit of info about mining back in the day (2013-2015) say but what people don’t explain is when someone solved a block and thus got rewarded 12.5 bitcoins, and when the bitcoins are saved in a wallet, how can the unused addresses in a wallet.dat file have no balance when checked with blockchain.info?  Where are the bitcoins that were mined and why do the addresses have no balances? Why were all these addresses created in the wallet.dat file?
There is a disconnect between a miner’s reward of bitcoin he earned while mining and what is in his wallet and unused addresses showing zero balances. I am having trouble understanding the relationship with mined bitcoin, unused addresses with assigned keys in a wallet.dat file, and having zero balances when checked with blockchain.info

Unused addresses are unrelated to mining activity. Even if you were mining, you will still see many unused addresses. The Bitcoin earned from mining would be associated with a used address.
Bitcoin Core by default will generate 1000 (previously 100) unused keys to be used in the "keypool". The keypool is the pool of unused keys and is used as a lookahead. This is useful when you restore a backup. The unused keys you are seeing are this keypool.


How to know earning LN routing fees I am using c-lightning version:v0.6-182-g1851ebb. Is there a way to know how much I have earned routing fees? I found that lnd has lncli feereport command that shows earned fees. Does c-lightning have same functionality? If not, is there a way to know earned routing fees?

I created a query for calculating earned routing fees. However, this doesn't work because HTLCs info is removed when a channel forwarded HTLCs closed.

sqlite3 $HOME/.lightning/lightningd.sqlite3 "select sum(a.msatoshi - b.msatoshi) from channel_htlcs a inner join channel_htlcs b on a.id = b.origin_htlc"

Any ideas?

lightning-cli listforwards

  List all forwarded payments and their information


How to transfer btc from multiple btc addresses to a single btc address? I have 3 btc addresses and let's say each btc address has 1 bitcoin. If I want to transfer to my address from 3 btc addresses, I have to create 3 transactions and every time I have to pay a mining fee. Instead of that Can I transfer all the amount from 3 btc addresses to my btc address in a single transaction? How to manually create a transaction? I am using "pybitcointools" library. But It supports only to send coins to multiple addresses. Could anyone help me out in creating a single transaction manually using any library?

A very generic question, so only a generic answer. I think, what you are looking for is how to create a transaction with multiple inputs, to a single output. There are many bitcoin tools out there, I for myself use some shell scripts on unixoide systems. There is also bx and tx tools, as described in Andreas‘ book „Mastering Bitcoin“ (book is online readable). Then there are libraries for php, Java, python - each with its own learning curve. Generally: you need the previous tx ID, the outpoint, and the target address and amount. This all needs to go into a serialized set of data, then a hash is generated over it, and signed. Once you have the signed tx, you can send it from a wallet or from many Online services (like blockchain.info) to the network.

I recommend to start playing on testnet or regtest, assemble a tx, and run through the possibilities. Then you can search specifically here in the forum, or raise a question based on the experience.
Again: it can be done manually, but requires some effort to get into the logic of correct assembly. Andreas‘ book is a good starting point.


How many times a single transaction can be included into different blocks? I would like  to know is there a limit after which a miner cannot include a transaction into his block.

Each transaction can only be included into one block since it spends the coins (outputs) of the origin address. Including it in a second block would be invalid because the coins are already spent.


How to make concurrent calls to bitcoin core rpc? I am trying to call getBlock for 100k blocks, but it is too slow to call them sequentially. This is what I am trying. I have a full node of bitcoin core running. I set the -rpcthreads=100 and -rpcworkqueue=100, and I use js to make Promise.all([multiple rpc calls]). To my understanding, rpcthreads allows concurrent calls, but maybe I misunderstood it. I expected the time it takes to run 2 getblock to be similar of running 1. However, I am not seeing a huge performance increase (running 2 roughly takes double the time). What is the correct way to make bitcoin core accept concurrent rpc requests? Thanks!

my bitcoin core config: -server -rpcuser=un -rpcpassword=pw -txindex=1 -rpcthreads=100 -rpcworkqueue=100

my attempt to make it concurrent (client being a wrapper class around the rpc api.):

const before = Date.now();
await Promise.all([
  client.getBlock('0000000000000000000119e179a3169afe7e1dbd867cb9070a6f75a583b98fb3'),
  client.getBlock('0000000000000000000119e179a3169afe7e1dbd867cb9070a6f75a583b98fb3')
]);
const afterAll = Date.now();

console.log('time for all');
console.log(afterAll - before);

I would assume the issue is not Bitcoin Core, even with default RPC settings I do see noticeable increase in client performance when using async/await (C# library). My suggestion is to investigate how the client code handles the RPC request/response + block parsing.


Is it possible to know the total hashpower backing a currency? Is it possible to know the total hashpower backing a currency?

My goal is to know how much hashpower is backing each currency.  I don't know if it's possible, if so, how?

Yes.

Generally cryptocurrency network mining difficulty is dynamically adjusted by the current available hashing power. Thus, the hashing power must be known. This information is usually disseminated on raw protocol level and through different blockchain explorer web sites.

Hashing powers of different Ethereum forks.


Could the EC2 infrastructure be used to efficiently launch a 51% attack? This excellent answer from Serith states that one would need 31150 ATI 5870 graphics cards to launch a 51% attack. Amazon EC2 offers computers for rent for 2.10$ per hour. These instances have 2 x NVIDIA Tesla “Fermi” M2050 GPUs. Given that these are as fast as the ATI 5870 (I have absolutely no idea whether this is the case), and that Amazon has enough of these instances available, one should be able to launch a 51% attack for one hour for a mere 65415$. If the hash rate of the Bitcoin network varies over the time of the day or under such events as a power cut, then it could be cheaper.

Is this a potential threat to the Bitcoin network?

An NVIDIA Tesla “Fermi” M2050 is not as fast as an ATI 5870. According to the wiki, the NVIDIA card makes around 70Mh/s and the 5870 makes around 400Mh/s.

If they were similar and if Amazon had that amount of cards available for rent, then it would be possible. Just don't forget that you would be paying $65415 per hour to sustain an attack that will not give you that much power over the network. See this question for an explanation of what the attacker could do.


What is the SPV Mining Exploit? Can anyone explain this simply? I am not finding enough explanation exactly on this type of attack. If possible, add some additional reading to your answer so that I can understand more.

"SPV mining" refers to a bad practice where a miner starts hashing a new block on top of an unverified parent block. If the parent block turns out to be invalid due to a double spend or newly activated soft fork, the new block will also be invalid.

The term SPV in this case is used because the miner only verifies the headers of the incoming block and then immediately starts mining the next block.

This has happened on main net before: when BIP66 activated in 2015, a short chain of blocks was mined on top of an invalid block that did not enforce the new rules.

This question may be a duplicate:

What is SPV mining, and how did it (inadvertently) cause the fork after BIP66 was activated?


What happens to .blk files on disk when the Bitcoin daemon switches to a longer chain? I’m interested in writing a program that will (1) parse the .blk files that my full-node Bitcoin daemon writes to disk and (2) write them to a relational database in an incremental fashion (i.e., keeping tracking of which .blk files I’ve already seen to avoid duplicating work). But it seems that this approach could lead to problems when my Bitcoin daemon says “uh-oh, another chain is bigger than the chain we currently have, let’s switch to it.” Specifically, I could imagine two possibilities:

The Bitcoin daemon goes back into an existing .blk file and deletes the blocks from the old chain. If that’s what happens, my program would need to keep track of the mtime of the .blk files on disk and overwrite the parsed data that was sourced from those .blk files when the mtime changes.
The Bitcoin daemon never modifies “finished” .blk files (i.e., block files other than the latest one that’s currently being written to), but rather knows that some of the blocks inside the .blk files could correspond to rejected blockchains. If this is the case, my program would need to query the daemon for this information and update the destination database appropriately.

Which (if either) of those possibilities is correct?

The second is correct. The blk*.dat files are append only. Once a block is downloaded and written to disk, it is never deleted (except when pruning). A block index (database) is maintained in blocks/index to keep track of block locations on disk and statuses (valid, invalid, etc.).


how can i coding wallet to build exchange to client withdraw i want to build a cryptocurrency exchange so my question how is best way and secure way to depositing and withdrawing clients ?

should i use api like https://cryptoapis.io or https://www.blockcypher.com/ ?

and this api dont support tether too !!?

The most secure way is running your own full nodes per Blockchain.

Using third-party services such as blockcypher will put you & your business at high risk because of:

You're giving the keys to your home & revealing the password of your bank account to someone else! Because in order to use such services, they are the one who make the public & corresponding private keys for you. Even though particularly Blockcypher claims that they will never store your keys, relying on it (I'm not blaming them!) is a risky approach by design!
You won't be able to participate in verifying transactions on your own & maybe you're part of some attack (e.g. 51% attack even though its very unlikely).
You're centralizing the technology that has come into existence for the sake of decentralization!

If there was high costs or too steep learning curve on running your own full nodes & connecting to, Maybe using provided interfaces (e.g. JSON/RPC for bitcoincore) was a reasonable way to start with, & switch to your own nodes during next steps, But as there is no such barrier, you'd better launching your own nodes.


Multiple pool options in Antminer S9 Settings I have purchased and got running Antminer S9. While setting it up I notices that I can specify three pool connections

I was unable to find the purpose for this.

Are those backup options just in case one or two pool connections are down or should I could actually mine for three pools at the same time?

The AntMiner S9 manual is available at https://shop.bitmain.com/files/download/AntMiner%20S9%20Installation%20Guide.pdf

The manual says:

  The AntMiner S9 can be set up with three mining pools, with decreasing
  priority from the first pool (pool 1) to the third pool (pool 3).

  The pools with low priority will only be used if all higher priority
  pools are offline.

On older S-series models there used to be a "Pool Balance" setting on the pool screen, below the "pool 1", "pool 2", "pool 3" in your screenshot. From the manual for the old S3:

  AntMiner can set up three mine pools, the priority decreases from
  first pool (pool 1) to third pool (pool 3). There are three Pool
  Balance option:

  Failover: Automatic backup when Miner faults;
  ‘Failover’ is by default. The low priority pool will start to work,
  only when the high priority pool encounter fault.

  Balance: Change
  multipool strategy from failover to even share balance.

  Load Balance:
  Change multipool strategy from failover to quota based balance.

I do not know why this feature was removed in later models.


How fast is the NXT blockchain growing in 2014? Is there a place that where I can find out how fast the NXT blockchian is growing? I'm curious because its this year (2014) where a bunch of nxt features came into the scene and was wondering how one would monitor the growth size of the blockchain from month to month. This can give me a good idea of nxt usage and adoption.

NXT blockchain size is now around 1.5GB in 18 month that's roughly 83MB increase per month.


What was the first BIP9 block? Block 370,434 (0x20000007) or Block 398,364 (0x30000000)? Block 370,434 (00100000000000000000000000000111) and (0x20000007)

Yes: BIP9 says set top 3 bits to 001.
No: BIP101 explicitly says set first, second, third and 30th bits to 1.
No: No mention of BIP9 anywhere in BIP101.
No: BIP9 was published after this block.

Block 398,364 (00110000000000000000000000000000) and (0x30000000)

Yes: This is definitely compatible with BIP9, but not explicitly BIP9. It is mentioned in BIP109.

In my opinion block 398364 is the first BIP9 block.
Block 370434 was signaling BIP101. As you say, BIP9 was not created at the moment and even if is was meant to signal BIP9, it would also signal csv and segwit which where not active at the time: https://github.com/bitcoin/bips/blob/master/bip-0009/assignments.mediawiki
Block 398364 uses a BIP9 format to signal BIP109. The 4th bit is used to indicate the block version, 0b00110000000000000000000000000000 (0x30000000) which is within the defined version range of BIP9. But other proposals used the last bits in the version number.
Block 407021 is the first block with version number 0b00100000000000000000000000000000 (0x20000000) so a clear vote for only BIP9.
The green line below shows the BIP109 blocks and blue line BIP9.


GetBlockChecked always returning genesis block? currently I'm exploring Bitcoin source code and I tried to add custom function getblockvalue inside of blockchain.cpp.
Purpose of function is to return sum of all transaction outputs inside of a block based on given height as an argument.
static UniValue getblockvalue(const JSONRPCRequest& request)
{
    int blockHeight = request.params[0].get_int();
    if (blockHeight < 0 || blockHeight > ::ChainActive().Height())
    {
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
    }

    CBlockIndex* pBlockIndex = ::ChainActive()[blockHeight];
    if(pBlockIndex == nullptr)
    {
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Block index is NULL");

    }
    const CBlock block = GetBlockChecked(pBlockIndex);
    UniValue resultObject(UniValue::VOBJ);
    double blockValue = 0;
    int numberOfTransactions = 0;

    for(const auto &transaction : block.vtx)
    {
        for (unsigned int i = 0; i < transaction->vout.size(); ++i)
        {
            blockValue+= transaction->vout[i].nValue;
        }
        ++numberOfTransactions;
    }

    resultObject.pushKV("blockHeight",          (int)blockHeight);
    resultObject.pushKV("numberOfTransactions", (int)numberOfTransactions);
    resultObject.pushKV("blockValue",           ValueFromAmount(blockValue));

    return resultObject;
}

I did all necessary changes: I added argument to vRPCConvertParams[] and extended CRPCCommand commands[].
So, I tried calling bitcoin-cli -testnet getblockvalue 25; result is:
{
"blockHeight" : 25,
"numberOfTransactions" : 1,
"blockValue" : 50.00000000
}

The result is the same for every given block height. It always gives me information about genesis block. Can you help me what did I do wrong here?

Ok, so the code is just fine as Andrew assumed.
It was odd to me that first several blocks are the same. They all have one transaction and the same output value of 50BTC, but according to site https://blockstream.info/testnet/, where you just type a block height in search bar and you can see all transactions inside of resulting block, this is correct.


Transfer from Bitcoin Core to Electrum expired before full synchronization. Where are the bitcoins? I started using Bitcoin Core and transferred coins to this wallet. When synchronization got to the point where the coins showed up in the wallet I sent them on to an Electrum wallet, although Core had still not fully synchronized.

The Electrum incoming transaction then expired before the Core wallet had fully synchronized. Now Bitcoin Core has finished synchronization and shows the outgoing transaction and empty balance although the Electrum wallet never received the transaction.

Are these bitcoins lost or is then anyway to reclaim them?

Thanks.

If you broadcasted the transaction, it will appear on the other end, eventually.

I suggest you to first go to https://blockchain.info/ and look-up your electrum address or the transaction ID. There, you should see if the transaction is still unconfirmed or has already been confirmed.
In both cases, you should see it in electrum. If you don't see it, try exiting electrum, deleting blockchain_headers file in %appdata%\Electrum, and running it again. This will force it to re-scan everything.


Bitcoin core wallet backup corrupted by an external tool Do you know if my wallet.dat which has become wallet.axx due to incorrect handling of an external program
(I do not know the name of the program, but it is used to encrypt Windows files)
has the possibility of reverting to initial format ".dat"
by myself ?
And above all without damaging the backup "Core" that it is ?

According to a random website coughed up by Google:

A file with the AXX file extension is an AxCrypt Encrypted file. AxCrypt is a file encryption program that scrambles (encrypts) a file to the point that it's unusable without first being decrypted with a specific password/passphrase.
When an AXX file is created, it's automatically assigned the exact same name as the unencrypted file but with the .AXX file extension appended to the end. For example, encrypting vacation.jpg results in a file called vacation.jpg.axx.
You can double-click an AXX file to open it with the AxCrypt software. However, note that if you're signed in to your AxCrypt account, double-clicking the AXX file will open the true file and not actually decrypt the AXX file.
Use the program's File > Open Secured menu to open the AXX file but not actually decrypt it. To decrypt the AXX file requires that you either right-click it and choose AxCrypt > Decrypt or use the File > Stop Securing option


Why are blk*.dat files ~134200000 bytes? I understand that blocks are stored on disk across multiple blk*.dat files, but why is the maximum file size roughly 134,200,000 bytes?

What's the reason behind this file size?
Where can I find this setting in the source code?
What's the exact maximum size?

The constant is called MAX_BLOCKFILE_SIZE and is set in src/validation.h.  It is currently set to 0x8000000 which is 128 MiB (134,217,728 bytes).

You can see where it is checked in FindBlockPos() in src/validation.cpp.

There isn't any indication of why this specific size was chosen and it may be arbitrary.  It is desirable to have some limit because some operating systems (or specific filesystems) have limits on maximum file size, usually above 2 GB or so.  So at least this limit ensures we never get anywhere close to an OS limit.


cryptocurrency tax question I have a buddy who I sent money to to buy a certain amount of Ripple. For one reason or another, I couldn't do this on my own at the time. In any case, the currency has tripled and I want him to send the ripple to my wallet. Does this transaction require me to pay taxes on the capital gain that has occurred? Or can I simple put this ripple into my wallet.

Any help here would be great. I have called around to no avail.

Not regulated by a government does not mean that there are no tax regulations concerning cryptos. There are countries where the law requires that you pay taxes for capital gains even when you only trade one crypto into another crypto (without fiat involved) supposed the time difference between buying and selling the crypto is less than one year.


How can I tell if someone is trying to hack port 8333? I am experimenting with leaving a public replica of the Bitcoin chain on the internet.  In doing so I'm actively monitoring the debug output so I can get a sense of what is happening with the inbound connections.

How can I tell what the clients are doing and respond appropriately?

Under what criteria should I block a port to an IP address, subnet, etc?

You are looking for ways to improve the client's protections against flaws?

Here's a list of its current protections:

http://en.bitcoin.it/wiki/Weaknesses#Denial_of_Service_.28DoS.29_attacks


Remote node signature for HTLC-success and HTLC-timeout transactions According to BOLT #3, when constructing a HTLC output in the version of the local node (both received and offered HTLC), it requires that the payment to the local node is locked with CHECKMULTISIG opcode that requires both localhtlcsig and remotehtlcsig in order to spend it.

As far as what I have seen, nodes do not exchange their htlcsignatures (although we can derive the htlc public keys through basepoint).

So the question: suppose after I receive an HTLC from a node and I successfully pass it to the other nodes, the node that sent the HTLC to me became unresponsive. Now I will need to broadcast my version of the commitment transaction to the Bitcoin blockchain so that I can claim the funds that are locked with the payment_hash (when I receive one). But, in order to spend that output, my witness stack will need to have 0 <remotehtlcsig> <localhtlcsig> <payment_preimage>. Now, if the remote node is offline, how will I get my hands on the remotehtlcsig in order to get back the funds locked in the HTLC?

Just to provide additional details, below is a local node version of the received HTLC output according to BOLT #3

# To remote node with revocation key
OP_DUP OP_HASH160 <RIPEMD160(SHA256(revocationpubkey))> OP_EQUAL
OP_IF
    OP_CHECKSIG
OP_ELSE
    <remote_htlcpubkey> OP_SWAP OP_SIZE 32 OP_EQUAL
    OP_IF
        # To local node via HTLC-success transaction.
        OP_HASH160 <RIPEMD160(payment_hash)> OP_EQUALVERIFY
        2 OP_SWAP <local_htlcpubkey> 2 OP_CHECKMULTISIG
    OP_ELSE
        # To remote node after timeout.
        OP_DROP <cltv_expiry> OP_CHECKLOCKTIMEVERIFY OP_DROP
        OP_CHECKSIG
    OP_ENDIF
OP_ENDIF

As far as what I have seen, nodes do not exchange their htlcsignatures (although we can derive the htlc public keys through basepoint).

I believe you have overlooked the commitment signed message from bolt 02. From there I quote:

  When a node has changes for the remote commitment, it can apply them, sign the resulting transaction (as defined in BOLT #3), and send a commitment_signed message.

type: 132 (commitment_signed)
data:
[32:channel_id]
[64:signature]
[2:num_htlcs]
[num_htlcs*64:htlc_signature]

While we already see that signatures for all htlcs are transferred we can find the requirements further down :

  A sending node:
  ...
  MUST include one htlc_signature for every HTLC transaction corresponding to the ordering of the commitment transaction (see BOLT #3).

I believe a node SHOULD NOT  forward the htlc before it validated the signatures from all the htlcs of the received commitment signed.


Does Bitcoin have a built-in life expectancy? I understand that the supply of Bitcoins, by design, will not continue to grow to infinity, but is "capped" at 21,000,000. This amount is not in circulation, however, because there are coins that have yet to be mined. I also understand that the reward for a successful miner is 25 coins, but that the reward will be reduced by a factor of 0.5 at certain points. It seems like the supply of coins will always approach 21,000,000 but never actually get there - a limit. If this is all accurate (please correct me if it isn't), does this imply that the incentives for miners will also be reduced? As time goes on, following this logic, miners should stop working altogether, at which point, new transactions can no longer be added.

Assuming this all plays out, would people simply "roll" into a new blockchain at that time?

but never actually get there

Except at some point there will be a rounding error (as numbers are integers in the code) to zero new coins being mined.

  does this imply that the incentives for miners will also be reduced?

Not really. First of all the miners also collect all the fees from all transactions. That should compensate for the reduction in new coins being mined. Another factor is the price of Bitcoin, either in USD or by the time USD doesn't exist anymore, the number of aircraft carriers you can buy for 1 Bitcoin.

Rolling out a new chain will actually probably become harder and harder over time as the network effect causes people to use the chain that is most useful. The number of other people that use it is a big part of its usefulness.


Popularity based mining (variable block reward) I am thinking of an alternative mining scheme where block reward would grow (or decrease) with popularity of the coin. The rationale behind this idea is to make an exchange rate more stable since greater interest will not result in higher coin price.

The biggest question is probably how to technically solve such variable block reward because there seems to be no easy way of how to collectively decide on reward height.

How would you define popularity? Any measure you make must be decentralised, and whatever you decide on can be arbitrarily faked. It's completely impossible in the terms of a trustless currency like Bitcoin.


How to earn my first bitcoin in baby steps? I don't know any thing about bit coin , what I know that it digital currency maintained by people and not banks.

How do I start earning my bitcoins ? OK After earning this bitcoins ? What all things I can buy in real world or it just to pay for only services to service provider?

HOW TO BUY BITCOINS

1) From exchanges. Exchanges are many based on countries. UNOCOIN is a popular one for India. Alternatively, if your nationality is different from what I presumed, you can have a look at this site for many exchanges and wallets: COINDESK. You can create a bitcoin wallet here: BLOCKCHAIN

2) Have a look at this link for more detailed explanation: How do you obtain bitcoins?

WHERE CAN I SPEND THEM

You can spend them on websites/services which ACCEPT bitcoins as a mode of payment just like Paypal, Credit Card or Debit Card.


How are transactions in forks verified efficiently? In this answer here, it's stated that Bitcoin uses a hashtable of all currently unspent outputs, in order to verify that the inputs of transactions haven't already been spent.

How does this interact with forks? If the Bitcoin client receives some blocks that go at the end of a fork that isn't the longest fork (perhaps, once they have all been verified, the new fork will be longer), how does it know what outputs are unspent in the fork that the blocks are being added to? A hashtable of unspent outputs in the current longest fork won't cut it.

Transactions in forks are not verified completely until the node attempts to switch to that fork. Before that, only those checks are performed that don't depend on previous transactions. In the source code, there is a function CheckBlock, which does only some of the checks, and ConnectBlock, which checks everything. The latter function is called only when the block is about to be accepted into the longest chain, so the hash table of unspent outputs is available.


how does merkle root building work for empty array? It's known that even if no transactions get created, bitcoin still creates a block with empty array of transactions.
In this way, I am curious what the merkle root would be. How does bitcoin figure out merkle root for empty array ? if there're even 1 transaction in it, I understand completely what it does, but what about empty array ?

This cannot happen. Every block contains at least a "coinbase" transaction that distributes the subsidy and fees to the block's miners.
Blocks without coinbase are invalid, even if the subsidy were 0.


How do USB ASIC Miners Work? How do the USB ASIC miners work?  Do you just plug them into a power source and they start mining?  Do you have to set them up for a first time?  Do you need to use a mining program still?

USB ASIC miners require some sort of control program that sends work to the miners and collects the results. You set them up in that control program. BFGMiner is one such program.


How to see download sync speed when syncing the Bitcoin 0.17.1 Blockchain on Ubuntu 18? I'm syncing the bitcoin 0.17.1 blockchain from the beginning on Ubuntu 18 using Bitcoin Core Qt gui client. Is there a way to see the download speed of the Bitcoin Blockchain and how much time I have left to get it fully synced?

If you care about overall sync performance, the download speed is usually not the bottleneck.

If you want to calculate your pure download speed, you can use getnettotals. There is a value totalbytesrecv (amount of bytes received since the Bitcoin Core instance has been started).

You can calculate the speed by reading the sync start time out of your debug.log (or you eventually wrote down the sync start time manually).

But be aware that the CPU intense validation of blocks may have (very likely) throttle your download.


Are the Thin clients Electrum and Multibit safe and secure? How do Electrum and Multibit compare for being safe and secure. Both are open source. Are there any advantages, security wise, to use one or the other?

I'm new to bitcoin and the only reason for considering these thin clients is to not having to maintain a 5gb database file.

Currently, Electrum is more secure than MultiBit as the MultiBit wallets are not encrypted. The next version of MultiBit, version 0.5.9, supports encrypted wallets. (Disclaimer: I am the lead MultiBit dev)

Security in Bitcoin is related to many things. Here are some of them:

1) Is the code open source and do the developers have a track record ?
Both Electrum and MultiBit are open source so you can inspect the code. They have both been developed by pretty much the same people for over a year now.

2) Can you verify that the download you get is the correct one ?
The attack vector here is that an attacker substitutes a trojan instead of the real installer.
The MultiBit installers are all downloaded from a dedicated server via HTTPS and are signed with my PGP key. You can verify this after you download the installer (but before you run it). As long as my private key is not compromised this means only I could have signed it.

I am not exactly sure what Electrum does about signing its builds but I know Thomas (the lead Electrum dev) is very conscious of this area/ attack vector.

3) Are there any servers that can steal your bitcoin ?
MultiBit uses the regular Bitcoin network and they don't have your private keys. Electrum uses (many) of its own custom servers but again these do not have access to your private keys.

4) Both clients are theorectically open to an attack if their network connection is owned and the attacker can feed them completely false information.

5) Both clients (well every client in fact) would be vulnerable to keyloggers capturing passwords which (in combination with the encrypted wallet in MultiBit's case) would give an attacker access to your private keys.

tl;dr At the moment Electrum is more secure. When MultiBit supports encrypted wallets they will be comparable. Good security practices on your machine are also important to keep your bitcoin safe.


How to retrieve unspent outputs on mSigna Due to an upgrade, I had to recreate my wallet (vault) file from scratch - a process that took over a week. During this time, I was able to spend one coin (sending it to blockchain.info) because I somehow managed to find an old copy of the software and it worked for one transaction only and then fell over. That appeared to work fine. When looking at the 'watch only' address imported into my blockchain.info wallet, it showed the spend plus the remainder at that address being sent to another address starting with '3'. I was comfortable with this because mSigna wallet addresses start with '3' because they can be multi-sig wallets. However, when mSigna finally completed syncing my new vault file, the unspent coin actually shows up in my list of wallet transactions as 'spent'. Obviously this is a shock to the system - it's quite a bit of coin.

However, I think what happened is that the address of the unspent output is somehow not in sync with my wallet and that's why I'm showing a balance below that which I should truly have.

I can think of two possible paths forward:

If I can get the private key from mSigna, I can move the funds manually through a site like blockchain.info, or
I try to re-sync the entire wallet again - and wait a week or more

Are there any other ideas worth considering? Thanks in advance for your help.

Jim

Can you please send the sharedacct file to support@ciphrex.com? Thank you!


Bitcoind doesn't find transactions / synchronize / update until last block from Testnet I set up bitcoind as server. It downloads the testnet blockchain but it is inconsistent with public data:

http://blockexplorer.com/testnet/q/getblockcount

182951 (As of 18/02/14)

And

bitcoind getblockcount

53317

My testnet accounts receive bitcoins from public faucets:

http://blockexplorer.com/testnet/address/mjDutNstJpZo929nLdZGKPh75fWKuTQNi1  (form 2 different faucets)

But

bitcoind listreceivedbyaddress 0 true
[
...
{
        "address" : "mjDutNstJpZo929nLdZGKPh75fWKuTQNi1",
        "account" : "3",
        "label" : "3",
        "amount" : 0.00000000,
        "confirmations" : 0
    }
]

Any help?

bitcoind getinfo
{
    "version" : 32400,
    "balance" : 0.00000000,
    "blocks" : 53317,
    "connections" : 2,
    "proxy" : "",
    "generate" : false,
    "genproclimit" : -1,
    "difficulty" : 0.55300531,
    "hashespersec" : 0,
    "testnet" : true,
    "keypoololdest" : 1392632512,
    "paytxfee" : 0.00000000,
    "errors" : ""
}

Solution

Please read the accepted answer.

Dont do apt-get update and install (at least in Ubuntu 12.04.4 LTS)

Instead:

sudo aptitude install python-software-properties
sudo add-apt-repository ppa:bitcoin/bitcoin
sudo aptitude update
sudo aptitude install bitcoind

It looks like you are using version 0.3.24 of the bitcoin client, which is extremely old (released July of 2011).  The latest version is 0.8.6.

Versions prior to 0.7.0 (released April of 2012) used a different testnet blockchain (called testnet2), which is no longer in general use.  Since 0.7.0, everyone uses testnet3, which has a new genesis block and a separate block chain.  So the coins you received are waiting in that new chain, but you're looking at the old one.

Upgrade to the latest version of bitcoind.  Then copy your wallet.dat from .bitcoin/testnet2 to .bitcoin/testnet3.  After synchronization, you should see your coins (and avoid a lot of other issues too).

I'm actually pretty surprised your client found enough testnet2 peers to get a complete copy of the testnet2 block chain!


What are Green Addresses? What are Green Addresses? Is it true that they can solve the "confirmation delay" problem, and how does that work? Are there any drawbacks?

The green address is a third party trust trick and can help resolve most problems related to the need to wait for confirmations (slow transactions).
To make it very simple :
Service A publishes its green address, service B decides to trust service A.
When someone send bitcoins from service A to service B, he will send from the service A green address.
The service B knows he can trust the service A, he knows A won't double spend, so B can credit the sent bitcoins immediately, without waiting for confirmations ( or waiting for just one confirmation, which is probably wiser ).
This is mostly useful for transferring bitcoins b2b (business to business), typically it would help making arbitrage easier and faster between 2 bitcoin exchanges, if both decide to trust each other's green address.
This can also be useful to allow for POS (Point of sales) with instant transactions if the POS can trust the green address of your bitcoin bank (or online wallet)
As an individual, I could also negotiate with my local supermarket to trust my green address (providing them my IRL address, ID number and more if needed).  Once they decide to trust my green address, I can pay immediately with bitcoins at my local supermarket (they trust me and won't need to wait for confirmations).
The green address is just a bitcoin address, but it's a "from" address people decide to trust and accept transactions from this address without waiting for confirmations.
Possible drawbacks are :

Less anonymity, or even no anonimity at all ( always using the same public from address), which is not a problem for a business, and its even great for public accounting/auditing ( yes bitcoin can also help fighting corruption ! )

Blockchain spam (more transactions for the bitcoin network), which is a good thing if the blockchain can scale.

Encourages people to use trusted wallet providers (some kind of bitcoin banks). Here too, this have good and bad sides.

It's not enough to create a green address, you still need to be trusted so that your green address is useful

For now, afaik, only mtgox.com, btcpak.com and instawallet.org support the idea.  To be useful, green address system needs to be widely adopted by bitcoin pools, exchanges, online wallets, businesses, etc.
See also https://en.bitcoin.it/wiki/Green_address
( edit 11 years ago, october 2020 , this reference is no more very relevant, some people completely rewrote the wiki page years later,for obscure reasons . . . they even replaced the first line with a blockstream ad . . . but you can still go and check the earliest versions of this page, around 2011-2012 , by clicking the "history" tab of the wiki page )


How to receive newly broadcasted transactions immediately with bitcoin-core RPC? With getrawmempool it gets me txids, however it just dumps the whole mempool on me. This isn't convenient if I want to quickly detect new transactions. Is it possible to only get newly broadcasted transactions?

Is there another way to sort of stream them from bitcoin-core into my program?

You can use the ZMQ interface to receive a ZMQ notification when a new transaction is received. You can have it give you the txid, the raw transaction, or both.


ripple-lib is not returning transactions with the getTransactions method My code is

const api = new RippleAPI({
  server: 'wss://s1.ripple.com'
});

api.connect();

    let isConnected = false;
    api.on('connected', () => {
      isConnected = true;
    });
      return api.getTransactions(address)
        .then((transactions) => {
          console.log(transactions);
        })
        .catch((err) => {
          console.log(err);
        })

But it doesn't actually return anything. It has an empty array [] for transactions.

If you look at the address I'm looking at: https://xrpcharts.ripple.com/#/graph/rqnfXCcsZRadjoj8tDQWYsP1pVyv3Ro7X

You'll see there are some transactions. So why doesn't the API return anything?

You can use chain of promises like this:

const RippleAPI = require('ripple-lib').RippleAPI;
var test_server = 'wss://s2.ripple.com';
const api = new RippleAPI({
    server: test_server // Public rippled server
});
api.connect().then(() => {
    /* begin custom code ------------------------------------ */
    const myAddress = 'rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn';
    console.log('getting account info for', myAddress);
    return api.getTransactions(myAddress);
}).then(info => {
    console.log(info);
    /* end custom code -------------------------------------- */
}).then(() => {
    return api.disconnect();
}).then(() => {
    console.log('done and disconnected.');
}).catch(console.error);

Good luck)


JSON RPC library unable to connect to bitcoind? I'm able to connect to bitcoind using my command line and the process is running with the appropriate port but when I try to run it through XAMPP after using the JSON-RPC library (I used the PHP developer intro for the code) it's giving me the following error, and I don't know why:

Warning:  fopen(): Failed to enable crypto in /opt/lampp/htdocs/bitcoins/jsonRPCClient.php on line 132

Warning:  fopen(https://...@127.0.0.1:8332/): failed to open stream: operation failed in /opt/lampp/htdocs/bitcoins/jsonRPCClient.php on line 132
Fatal error:  Uncaught exception 'Exception' with message 'Unable to connect to https://user:password
@127.0.0.1:8332/' in /opt/lampp/htdocs/bitcoins/jsonRPCClient.php:140
Stack trace:
#0 /opt/lampp/htdocs/bitcoins/testServer.php(7): jsonRPCClient->__call('getinfo', Array)
#1 /opt/lampp/htdocs/bitcoins/testServer.php(7): jsonRPCClient->getinfo()
#2 {main}
  thrown in /opt/lampp/htdocs/bitcoins/jsonRPCClient.php on line 140

The code is the following: (we tried toggling between http and https and it's still not working)

require_once 'jsonRPCClient.php';

$bitcoin = new jsonRPCClient('https://user:password@127.0.0.1:8332/');

echo "<pre>\n";
print_r($bitcoin->getinfo());
echo "</pre>";

As @Bittylicious mentioned the JSON-RPC is a little bit buggy

https://en.bitcoin.it/wiki/API_reference_(JSON-RPC)#PHP

Note: The jsonRPCClient library uses fopen() and will throw an exception saying "Unable to connect" if it receives a 404 or 500 error from bitcoind. This prevents you from being able to see error messages generated by bitcoind (as they are sent with status 404 or 500).

You have an option use EasyBitcoin instead, that will throw more accurate error messages and its pretty much the same than JSON-RPC

<?php
 require_once 'YOUR_FOLDER/easybitcoin.php';
 $rpc_host = 'YOUR_IP';
 $rpc_port = 'YOUR_PORT';
 $rpc_user = 'YOUR_USER';
 $rpc_pass = 'YOUR_KEY';
 $bitcoin = new Bitcoin($rpc_user, $rpc_pass, $rpc_host, $rpc_port);
 print_r($bitcoin->getinfo());
 print_r($bitcoin->listaccounts());
 print_r($bitcoin->listreceivedbyaddress(0, true));
?>

Hope this helps!


What is Valgrind? When should I use it for debugging Bitcoin Core over using gdb, lldb, pdb etc? I was watching Fabian Jahr's presentation on debugging Bitcoin Core at Bitcoin Edge Dev++ 2019. He mentioned Valgrind briefly at the end. What is it and when should I use it over gdb, lldb, pdb etc?

If you watched Fabian's presentation (or read the transcript) you'll have seen that he said you can use Valgrind for memory leak checks and that it can be used similarly to lldb.
valgrind --leak-check=yes src/bitcoind -regtest

There is a section in Fabian's doc on debugging Bitcoin with instructions on how to install Valgrind on MacOS and run it.
Install Valgrind:
brew install --HEAD https://raw.githubusercontent.com/sowson/valgrind/master/valgrind.rb

Run bitcoind with Valgrind:
sudo valgrind src/bitcoind -regtest

Valgrind has also been added as flag to the functional tests in Core in PR #17633 so you can run:
test/functional/test_runner.py --valgrind

The --valgrind flag is documented as a Valgrind memory error detector and that you should expect at least a ~10x slowdown with Valgrind 3.14 or later required.
In that PR practicalswift states:

Regular functional testing under Valgrind would have caught many of the uninitialized reads we've seen historically.

Another great resource is a Bitcoin Core PR review club session (hosted by Jon Atack) on running the unit tests under Valgrind. In the notes for that session it describes:

Valgrind is a debugging and profiling tool suite to make programs faster and more correct. Its most popular tool, Memcheck, can detect memory-related errors common in C and C++ programs that can lead to crashes and unpredictable behavior. Here is a tutorial. Memcheck is not perfect: typical slowdown is 3-10x, memory usage is 2x, it can produce false positives (there are mechanisms for suppressing these; see the valgrind.supp file in Bitcoin Core), and it doesn’t currently detect out-of-range reads or writes to arrays allocated statically or on the stack.


Can someone explain how to read blockchain.info? 1.What is the public key of address 3P9dyU9ga3aJorHAUqKBFCX2NdyuHEVgx1
(usually placed under input.. not in this case)

2.What type of Script (P2PK, P2PKH, P2SH, P2WPKH, P2WSH) is used to make this Tx, also how you discovered?

https://blockchain.info/tx/9d710be07bed7699055ed4c27868ee50fcb91f8d738bebfdbf4145cdbaeb15a2

A Bitcoin address starting with 3 is always P2SH (pay to script hash).
It's not P2PK (in that case you would see a public key instead of an address) nor P2PKH (you would see an address starting with 1).  It could be P2WPKH or P2WSH since these are simply implemented as special types of scripts via P2SH.  The address is only the hash of the script, not the script itself, and hash functions are one-way.  So we won't know what the script actually is, nor whether it happens to be a WPKH or WSH script, until after that transaction output is spent.
See https://bitcoincore.org/en/segwit_wallet_dev/ for more info about segwit.  In particular note the following:

Until a P2SH-P2WPKH UTXO is spent and the redeemScript is exposed, a P2SH-P2WPKH address is indistinguishable from a non-segwit P2SH address (such as a non-segwit multi-signature address)
Like any other P2SH and P2SH-P2WPKH address, P2SH-P2WSH address has prefix 3. They are indistinguishable until the UTXO is spent


Can't buy bitcoins from Greece via prepaid card I have an account at National Bank of Greece and would like to buy bitcoins in Greece using a pre-paid Visa Card. Can someone point out how I could do that? I could also get one from another bank if that's necessary. I have heard about a Bitcoin ATM somewhere, but I'm unsure if that would work in my case.

I also tried blockchain, but the bank didn't send the cash.

You can buy Bitcoin via credit card / paypal via https://xcoins.io

Disclaimer: I do work for them as an Software Engineer in our Santa Monica office.


Transaction taking a long time to confirm, now it doesn't even show up on Bitcoin Explorer UPDATE: Electrum now says the transaction is "Local" and now I have an option to "broadcast", should I do that?
OP:
So, I'm trying to spend a small amount of bitcoin on a website (not relevant) and I send over 0.0010346 BTC with a fee of 0.0000543 BTC  ( 30.2 sat/byte ) and it's been almost 24 hours, and it still hasn't confirmed. The website stated it saw my payment, and will convert my BTC into balance once the BTC gets confirmed, and it's stressing me out because I'm afraid my BTC was lost somehow... I'm generally new to BTC so any help is appreciated.
The transaction used to show up on Bitcoin Explorer (blockstream.info) which is what my wallet (electrum) directs me do, and now it doesn't?!? Really stressing me. Transaction id is c4bea179e5e772b131c475f9030088b67dea5054a545713dc32458829fa61598

I can see the transaction here: https://blockchair.com/bitcoin/transaction/c4bea179e5e772b131c475f9030088b67dea5054a545713dc32458829fa61598
This is how you can visualize your transaction in a pool of other unconfirmed transactions with different fee rates:

Miners prioritize transactions with higher fee rates from this pool to add in the blocks and thats how transactions are confirmed. Your transaction will stay lower in the pool and less likely to get confirmed until others keep using higher fee rate.
Also there is a limit of 300 MB used by most of the full nodes which might result in lot of low fee rate transactions being dropped from their mempool. Not sure if this will affect your transaction with fee rate: 30 sat/vByte.

RBF was not enabled for this transaction. Ensure that you are using a wallet that supports RBF and enable it for most of the transactions. It allows you to add more fees later.

CPFP cannot be done in this case as it has only one output which I am assuming owned by the website.

Be patient and wait for couple of days. Email the website support about this issue.


Assumed, I hash the next bitcoin block. Whom do I tell if it's decentralized? The bitcoin network is decentralized, right?

Assumed, I do hash a little bit and get a hash that starts with 20 Zeros..

What do I do than? I need to send the block to someone but who is that? It's decentralized... Do I send it to all the other miners?

You don't tell a specific node on the network, but rather broadcast your block to the entire network.  You essentially scream it from the rooftop.

If it's valid, it will be in the best interest of everyone to recognize your block and start mining on top of it.


How to calculate bitcoin days destroyed percentage I understand the concept of bitcoin days destroyed but on the wiki

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

And the site calculating it

http://abe.bitcoinstats.org:2750/

They give a percentage which is the coin days vs block number. Can someone run me through this calculation.

Block  | Age (days) | Coins Created | Avg Coin Age | %CoinDD
210842 | 1430.57    | 10521062.02   | 420.84       | 37.2271%

This was a recent sample from abe and I can't arrive at 37.2271%

The graph is a histogram showing the percentage of total Days Destroyed from the measured period for each block. Thus it is a distribution of dormancy over the period, since block numbers are ascending forward in time.

To arrive at the percentage in your example, you need to divide the Days Destroyed for that example block by the total of the Days Destroyed for the period being graphed.


Simplest way of obtaining MtGox exchange rate via an API? I want to do a simple app that refreshes every minute to tell me the current exchange rate by Mtgox but I have a problem interpreting the JSON that some APIs return:

Mtgox's fast ticker returns this JSON. The question is, what's the value that I have to retrieve? There are a lot and I don't understand them, and I don't find proper docs.
Bitcoincharts' API has the Markets Data endpoint, and it returns the market I want under the symbol "mtgoxUSD", however it tells me the date time of latest trade, the last buy/ask, but doesn't tell me the exchange rate of the latest trade.

Am I missing something?

JSON can be a little hard to read because it's generally meant to be served without characters such as spaces and newlines that would make it human-readable.

Here's output from the fast ticker:

{
  "result":"success",
  "data":{
    "last_local":{
      "value":"136.87303",
      "value_int":"13687303",
      "display":"$136.87",
      "display_short":"$136.87",
      "currency":"USD"
    },
    "last":{
      "value":"136.87303",
      "value_int":"13687303",
      "display":"$136.87",
      "display_short":"$136.87",
      "currency":"USD"
    },
    "last_orig":{
      "value":"136.87303",
      "value_int":"13687303",
      "display":"$136.87",
      "display_short":"$136.87",
      "currency":"USD"
    },
    "last_all":{
      "value":"136.87303",
      "value_int":"13687303",
      "display":"$136.87",
      "display_short":"$136.87",
      "currency":"USD"
    },
    "buy":{
      "value":"136.10500",
      "value_int":"13610500",
      "display":"$136.11",
      "display_short":"$136.11",
      "currency":"USD"
    },
    "sell":{
      "value":"136.87250",
      "value_int":"13687250",
      "display":"$136.87",
      "display_short":"$136.87",
      "currency":"USD"
    },
    "now":"1381085718504609"
  }
}

The "result" item is always guaranteed to be there, but has of course varying content based on whether or not the call was successful. The "data" element contains a series of prices, with each name indicating its price.

Most JSON parsers in interpreted languages such as Ruby, PHP, and Python parse JSON into a hash or dictionary. You'd want the value of the "value" key of the "last" key of the "data" key.

Here's a one-liner version in Ruby for the v2 ticker:

ruby -e '%w(open-uri json).each{|b| require b}; open("http://data.mtgox.com/api/2/BTCUSD/money/ticker_fast") {|d| puts JSON.parse(d.read)["data"]["last"]["value"]}'

Or something a little more readable:

require "open-uri"
require "json"

open("http://data.mtgox.com/api/2/BTCUSD/money/ticker_fast") do |d|
  json = JSON.parse(d.read)
  puts json["data"]["last"]["value"]
end

Here's a one-liner version in Ruby for the old ticker:

ruby -e '%w(open-uri json).each{|b| require b}; open("https://mtgox.com/api/1/BTCUSD/ticker") {|d| puts JSON.parse(d.read)["return"]["last"]["value"]}'

Or something a little more readable:

require "open-uri"
require "json"

open("https://mtgox.com/api/1/BTCUSD/ticker") do |d|
  json = JSON.parse(d.read)
  puts json["return"]["last"]["value"]
end


How do we check the time when a transaction hits x confirmations? Consider the transaction 948a427.. which has 3341 confirmations as of now:

We can see that the time the relay is received at 8:36:30 and it has one confirmation at 08:50:04 (after 14 minutes).

How do we find out the exact time when it has 3 confirmations?

The first confirmation was in block 298902, so the third confirmation was with block 298904, which is timestamped as 2014-05-03 09:42:49 (66 minutes after it was first received).

However, this timestamp is later than the one in the block after it, suggesting that a timestamp was pretty far off. As Matthieu's answer shows, blockcypher.com's API includes the time that they first saw the transaction. This suggests that the actual time three confirmations was reached was around 2014-05-03T09:31:55.867Z, approximately 59 minutes after the transaction was created (since it was relayed by Blockchain.info, I'm assuming the transaction timestamp there is accurate).


What is proofOfWorkLimit? Look at the code below from android bitcoin wallet:

proofOfWorkLimit = Utils.decodeCompactBits(0x1d00ffffL);

And look at the code from bitcoin qt wallet:

static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);

I assume that in second case ProofOfWorkLimit is 32 "0" and 224 "1" (000000...000111111111....11111111)?

So I don't have an idea how to get first case "0x1d00ffffL" from second case?
In binary "0x1d00ffffL" is 11101000000001111111111111111.

P.S. I have looked in uint256.h. It wasn't helpful.

The first byte, 1D, is the length. The next three bytes are the high bytes of the hash. So we have 00ffff, then we add ff bytes onto the end to get to 29 bytes. Then we're done.

We wind up with 3 bytes of leading zeroes because 32-29 is 3. And we get one byte of zeroes from the second byte of the compact bits. So the final result is 00,00,00,00,ff,ff,ff...


Is it ok just to save wallet.dat from multiple altcoin clients and remove the client? I have the following situation: I have mined few coins from different alt crypto-currencies and I do not want to run them any more on my machine. As far as I understood from this question, I can just copy wallet.dat from each of these altcoins, encrypt them, remove the clients and this is it.

If then someone will send me some coins and after some time I would like to use them, I can just download the client, wait for synchronization, change wallet.dat with my stored wallet and continue using coins? Am I correct?

Yes, just make certain you do not make any more transactions with that wallet or you could lose coins going to a change address (an address that is used to send back extra coins. it is not the address you sent coins from).

also make certain that you remember your password and the most imperative part: shutdown your coin client before you copy the wallet

also id suggest you back up the wallet and then remove the wallet, and finally try to copy the wallet back over, if you see it load up and your coins are there you are golden.

another way would be do dump the privkeys and encrypt a file with just those keys in it.

source: Me, I'm an altcoin pool op


Have I lost all my Bitcoin, having sent them to a Bitcoin Cash wallet? I made a pretty big mistake of sending my Bitcoin that I had on Coinbase to a Bitcoin Cash wallet that I own on my Exodus wallet instead of the Bitcoin wallet. I can see on Coinbase that the address it went to is the Coinbase Cash wallet that I have on Exodus and the transaction has now been completed, but nothing appears in Exodus.

I understand that sometimes this can be ok depending on the address format and I'm not entirely sure how long it is supposed to take until you see it. Do I take it that I've just lost all those coins since they haven't appeared at all? Also if so where do those coins go?

Keys are interchangeable on both chains. If you export the private key of the address you sent it to on the bitcoin cash wallet , and import it back into another wallet (Exodus for Bitcoin?) , you should see your bitcoins.


Where can I buy Litecoin? I know Litecoin is sold on Coinbase, but I'm wondering if anyone has compiled a list or knows of other exchanges selling the currency?

The most current list of Litecoin exchanges, originally from the Litecoin wiki, updated in December 2017 to remove nonfunctional exchanges:

  Market exchanges

 Kraken
 The Rock Trading
 UpBit - Korean exchange
 Bithumb - Korean exchange
 BTCTrade - Chinese exchange
 OkCoin - Chinese exchange

  Fixed rate exchanges  Okpay
 Litecoinlocal
 BitBargain
 24change
 ALFAcashier
 GOLDUX


Sending from Bitcoin-Qt to Coinbase I had the idea to move all of my existing bitcoins (10 BTC) from Bitcoin-Qt/paper wallet to Coinbase.

I had imported the paper wallet to Bitcoin-Qt and the balance there was 10 BTC total. For some reason, I then went and imported the paper wallet to Coinbase, and ~5 BTC was added.

At this point, Bitcoin-Qt still showed the balance as 10 BTC. I went ahead and made a transaction of 10 BTC from Bitcoin-Qt to my Coinbase address.

The result is that the transaction keeps having 0 confirmations, Bitcoin-Qt shows balance to be 0 BTC and the transaction never showed up in Blockchain. I have no idea where the "missing" 5 BTC are and what to do. I realize that a double spend might have occurred as 5 BTC was already imported to Coinbase from the paper wallet and I tried to send 10 BTC from the Bitcoin-QT.

Here's the Coinbase address https://blockchain.info/address/1GeQeHnJEnKfcfWonGCrj52kChyXqib5sC, and you can see the that the 5 BTC import from the paper wallet went through.

What's the solution here?

Here's how Bitcoin-Qt's transaction history looks like:

Addendum: It looks like the coins have been found; just quoting the relevant solution from the external thread so we have a complete answer on record. Long story short, the problem was as we suspected: the paper wallet did not contain all of the change addresses from the 5btc of transactions that had occured since tge import. Simple fix:

  I started the client with /Applications/Bitcoin-Qt.app/Contents/MacOS/Bitcoin-Qt -salvagewallet. It's still syncing with the network, but it looks promising as it's now showing a +4.9315 balance!

Ok, I'm beginning to piece together what happened now.

At least according to your blockchain links, you initially received 10 BTC via 3 transactions, at the 1Fr3p address then spent 5 on 17 april. So that particular address only had 5 remaining at the time of the import to coinbase.
When you import rather than send, the coins will still show in both wallets;  if you send them from the old one after that this will not update in the new wallet because of change addresses.  Importing != spending.
You will additionally need to import the change addresses that have been created since using bitcoin-qt to coinbase for everything to sync correctly.  Check out this thread.
As far as fixing the crazy transaction, I'm not sure what to do there.  Hopefully when you finish importing everything it will manage to work itself out in the client?  Don't send anything else from the old wallet again--once you can use  the coins  available in the coinbase wallet, send from there only.
If you want to use qt client again, create a new wallet for all transactions moving forward.

update
What do you know about these transactions from your link in the comments?  Your client is only showing the -.01 portion of those tx but the remainder seems to be what's missing...


Where does one obtain the most widely accepted Bitcoin/Euro exchange rate? I want use Bitcoin to make a purchase from a private seller in another country. The good which I want to purchase is priced in Euros, so I need a Bitcoin/Euro conversion rate which both of us must accept for the moment when the Bitcoin is transferred.

Bitstamp is reputable and generally accepted in the context you've mentioned.


How to develop an ownership tracking service based on bitcoin blockchain Now I expect to develop an ownership tracking service like Ascribe. I'm planning to develop it as following, however I am not sure whether my plan is correct. Therefore, please let me ask two questions.

Whether the following plan is correct or not.
Do I need to use bitcoind? Is is not enough to only use bitcoin-library(bitcoinjs-lib)?

My plan is following.
 1. Provide a user address and private_key made by bitcoinjs-lib.
 2. When the user upload an item, the item gets a specific ID.
 3. When the user transfer the item to another, the user put the ID of the item into OP_RETURN area(40byte area)
 4. Track the ownership of the item by tracking the specific ID.

There are a lot of different projects that are looking to solve this problem. Almost all of them use something like colored coins to track an asset on the blockchain. Essentially, what your plan is missing are clear rules that prevent double spending.

Check out coinprism.com, colu.co and chromawallet.com for just a few different implementations of what you're trying to do.


What is wrong with using hmac_sha512(block_hash, trans_id) as the resulting hash for a provably fair game? Let's assume someone wants to make their own version of Satoshi Dice.  Satoshi Dice states that the winning output of the game is determined in the following manner.

  The lucky number used to determine the winner of games is simple. It
  is simply the first bytes of hmac_sha512(secret,txid:out_idx). That
  would be the secret string as the key and the transaction ID of your
  bet transaction as the data.

I've done a little bit of research, and most provably fair gaming sites use a secret key for their result hashing.

My question is, what is wrong with using the block hash as the the key for the hashing algorithm when determining the win results, instead of a secret key that's periodically updated?

I cannot see how this method could benefit the player since he has no way of knowing what the hash of the block will be until after they've submitted the transaction and the containing block is confirmed at least once.

What is the exploit that prevents sites from using such a simple means of calculating the win/loss conditions?

Miners could cheat this game, by withholding blocks that would cause them to lose.

For simplicity, let's assume the game is designed for approximately 50/50 odds (say, players are betting on the first bit of hmac_sha512(block_hash, trans_id)).

A mining cartel could do the following.  The cartel members pool their coins and place a single large bet at your casino (say BTC 1000).  If they solve the next block before anyone else on the network, they compute the hash of the block hash and transaction id, and determine whether this block hash would win their bet.  If it would, they post it, and collect their winnings (and their BTC 25 block reward).  If it wouldn't, they throw it away and keep mining (and forfeit BTC 25).  This cuts their effective hashing rate in half, but means that every time they do find a good block, they have a guaranteed win of BTC 1000.

This introduces a bias into the game, proportional to the fraction of the network's hashing power that the cartel controls.  But even a slight bias, over large bets and a long time, could let the cartel clean up at the casino's expense.

Worse, since the cartel's activities are profitable for all its members, there'd be an incentive for more miners to join the cartel, which makes the bias stronger.  In the limit, every miner on the network joins the cartel, and the cartel wins 100% of its bets.

A solo miner could mount a similar attack.  Alice creates a transaction that bets BTC 1000 at the casino, but doesn't publish it to the p2p network.  Instead, she includes it in the blocks that she hashes.  When she solves a block, she checks its hash to determine if it would win her bet.  If so, she publishes it.  (Maybe, to be a little less obvious, she will post her bet transaction on the p2p network and wait a few seconds before publishing the block, and hope that nobody solves another block in the meantime.)  If the block doesn't win her bet, she discards it.  As in the previous case, her effective hashing rate drops by half, but she wins every single bet that she makes.

"Provably fair" can be counterintuitive.  The way to make a provably fair game is not to bet on some external phenomenon that you think neither party can predict or influence; often the parties will surprise you, and in any case it's not usually easy to prove that they can't.  Provably fair systems instead bet on something that's determined by the inputs of both parties (with no external input), but determined in such a way that either party can assure a fair result by choosing their input to be truly random.


structure of communicating with bitcoin DNSs to get list of nodes I want to communicate with bitcoin DNSs to get list of bitcoin nodes.

for now I want some example and structure of messages between I and bitcoin DNS.

I found two DNS names:

dnsseed.bluematt.me
dnsseed.bitcoin.bit

and want communicate with them.

please help me

"Bitcoin DNS" is a bit of a misnomer.

It appears that hostnames such as dnsseed.bluematt.me are not actual DNS servers - you cannot communicate with them using DNS protocols. However they are valid domain names in the normal public Internet DNS system and have multiple "A" records associated with them. You can therefore query the DNS seed hostnames in the normal way (i.e. send DNS queries to your local DNS servers) to get a list of IP addresses that are presumably Bitcoin full-nodes.

You can then, I guess, communicate with any of those IP-addresses using the appropriate Bitcoin peer-to-peer protocols.

Note that some of the returned addresses are IPv6 and some IPv4.

C:\> nslookup dnsseed.bluematt.me
Server:  xxxxxxxxxxxx
Address:  192.168.1.nnn

Non-authoritative answer:
Name:    dnsseed.bluematt.me
Addresses:  2607:fea8:80a0:a1f:b1dc:86a4:62a1:ff7d
          2001:0:9d38:6ab8:1c01:270:bff9:f75a
          2a01:4f8:c0:1328::2
          2a01:4f8:171:d4a::2
          2002:bc7c:110::bc7c:110
          2001:41d0:d:221d::
          2a02:a441:7147:1:70dc:dbc7:fcfe:c605
          240d:1a:124:5300:2cb0:2c4d:b748:3853
          2001:13d8:1c01:2000:2470::1
          2a03:4000:6:416c::43
          2600:1f14:6ae:d900:6550:3fc5:e074:a72c
          2a02:8106:22e:9d50::227
          123.5.48.235
          80.61.148.155
          159.65.33.252
          138.68.93.0
          13.78.125.30
          138.68.174.249
          171.124.53.172
          159.89.25.106
          148.251.83.196
          24.99.150.25
          192.3.11.24
          111.206.188.112
          88.198.39.205
          87.122.81.82
          96.27.129.94
          218.75.140.43
          218.75.158.185
          46.167.117.12
          195.43.141.28
          13.209.0.41
          95.216.26.158

This is confirmed by Bitcoin.org's developer guide which says

  When started for the first time, programs don’t know the IP addresses of any active full nodes. In order to discover some IP addresses, they query one or more DNS names (called DNS seeds) hardcoded into Bitcoin Core and BitcoinJ. The response to the lookup should include one or more DNS A records with the IP addresses of full nodes that may accept new incoming connections.

It goes on to describe the protocols that can be used to communicate with these nodes.


How does the protocol prevent miners from building off of a fraudulent blockchain? Let's say someone creates a fraudulent block and finds a nonce that solves the hash puzzle. This block is broadcasted, its hash easily verified, and it's added to the blockchain. What prevents a miner from hearing this block and adding it to its blockchain such that it uses the hash of this fraudulent block as the previous hash field in the new block it is trying to solve? Couldn't this then create the longest blockchain at a fork and thus become accepted?

When do mining nodes give up on a certain block? Once a block with the correct nonce is found for a given previous block, don't all other nodes mining a block with the same previous node have to start over?

A miner could create a block with an incorrect transaction, but this wouldn't be accepted by the honest nodes in the network. The honest nodes would attempt to validate the transaction, fail and then not propagate the block to other nodes.


I received an email that says someone sent me bitcoin I was sent bitcoin through email, but I am being told to pay a fee first so that I can receive the funds. What should I do and I don't have the fees?

This sounds like a scam. Receiving bitcoins does not require paying fees.
If you are not otherwise expecting this payment, then you can safely just ignore the message. It is spam.


Import testnet address in bcoin I´m trying to import a watch-only address to my bcoin node using cli (testnet). My config looks as follows:

[....]
#
# Options
#

network: testnet

#
# Node
#

prefix: ~/.bcoin-testnet
db: leveldb
max-files: 64
cache-size: 100
[...]

entering the following command (just a random valid testnet address):

 bcoin wallet watch my7q4nhpuJ6TsevXdDnPRq1rvHcPKeGEaD

results with the following error in the debug.log:

[E:2017-08-03T08:43:02Z] (node) Network mismatch for address.
AssertionError [ERR_ASSERTION]: Network mismatch for address.
at Wallet.importAddress [as _importAddress] ([...]/.nvm/versions/node/v8.2.1/lib/node_modules/bcoin/lib/wallet/wallet.js:1310:3)
at Wallet.importAddress ([...]/.nvm/versions/node/v8.2.1/lib/node_modules/bcoin/lib/wallet/wallet.js:1284:23)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
[E:2017-08-03T08:43:02Z] (node) This socket is closed
Error: This socket is closed
at Socket._writeGeneric (net.js:721:18)
at Socket._write (net.js:781:8)
at doWrite (_stream_writable.js:371:12)
at clearBuffer (_stream_writable.js:497:7)
at Socket.Writable.uncork (_stream_writable.js:297:7)
at connectionCorkNT (_http_outgoing.js:695:8)
at _combinedTickCallback (internal/process/next_tick.js:135:11)
at process._tickCallback (internal/process/next_tick.js:180:9)

The error occurs, no matter what address I try to import. Does anyone have an idea on how to solve this?

You can use the http api to perform an import. Notably, you import a wallet with the create wallet command as the import command imports addresses into a wallet.

curl -X PUT \
  http://127.0.0.1:18332/wallet/$ID \
  -H 'authorization: Basic eDppYW1zYXRvc2hp' \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -d '{
    "masterKey":$MASTERKEY
}'

Link to docs


I want my money i used the recommended fees for my 3 transfers but we going on 36 hours and no confirmation i did use the suggested fee from block-chain and still nothing what do i do .........decentralized currency is awesome but who is responsible when shit hits the fan if my bank was to mess up and not get my transfer lost i could call the bank and be fixed right away now im out my funds for going to be 3 days and no end in sight b41a9804a2e131196717b550553804dad75baec2e43a4817e6b1ba7cb2a12895   8d5e0ebff08ffd3ce6c4c4224a56d4e2458623476a21cb3ab732e2817a278f0b            00afdc1da94fd08b79e084c0ce60c5c97647e55ec9e8cef9dcc85aa1a4f44532

No one is responsible if your account gets hacked , your funds stolen or your transaction is stuck. Your problem is caused as currently the network has a backlog of 200,000 unconfirmed transactions.


Forgot to add transaction fee, any way to add it now? Today I sent 1.5 BTC to an exchange but forgot to add a transaction fee, the Qt wallet didn't even prompt me with one and I just clicked on Yes. Now it's been over 2 hours and it's not confirmed (as you would have guessed).

I kinda needed it to reach the exchange quickly (I know, my fault), but now is there any way to speed this up or do I have to wait it out for days to arrive at the destination?

Thanks

You can wait it out. Both of your inputs are around 1BTC so your transaction will likely be bumped up to "high priority" status in the next 12-24 hours.


How are scriptless scripts and taproot different? I recently read Aaron van Wirdum's layman explanation of both scriptless scripts and taproot. I gather that both utilize the aggregation of Schnorr signatures to hide complex scripts (smart contracts) in a normal-looking transaction. What are the finer details that sets the two schemes apart?

One of the most common use of script in Bitcoin is to construct logically atomic operations, such as "Tx2 happens if and only if Tx1 happens".

Scriptless scripts tells us how to use the additive properties of schnorr-signatures to construct atomic transactions without using script. Doing so this way will make them more efficient and private.

Taproot is an idea which uses the additive property of ECC public keys to allow users to commit to a script which is only revealed if needed. If it isn't needed, it is never even revealed that a script existed at all.

This is useful because almost all sensible contract terms (both smart and otherwise) can be rewritten as a top level OR between "Everyone agrees" and the actual contract, and because (with schnorr) you can make a single signature work for the everyone agrees case.

Taproot itself doesn't depend on the specific properties of schnorr and could be implemented e.g. for ECDSA. Technically taproot works outside of the EC signature itself to allow you to spend either via a single plain signature OR some other conditions, with the existence of other conditions hidden if you spend via the signature. But with ECDSA it isn't easy to use a single public key to represent the "everyone agrees" case, so taproot would be much less useful.

So, for example, if you had an output that could be spent either by Alice or by Bob but only after a time limit then pattern would be more efficient with ECDSA taproot than without taproot: Alice's key would be used to generate the root, and bob's key and timeout would be in the hidden script.


What happens to transaction once all the blocks are mined? Once all the bitcoin blocks are mined(21 million limit has been reached) then would calculating the nonce still be so power intensive since the reward at this point of time would only be the transaction fee cost . What are the reasons miners will continue to operate their huge power hogging machines ? Also what would happen to the speed of block creation? Right now it is difficulty which governs it. but once all blocks have been mined how fast would newer blocks be created at the same rate or much faster?

Note that there are not 21 million blocks but 21 million bitcoins generated through mining.  As for your specific questions, the difficulty of a block is independent of its reward so that would continue to match the hashing power of the network.  And the reason that people will continue to mine is, as you state in the question, because they will receive the transaction fees for their effort.


how is the private/public keypair for spent bitcoins connected to the private/public keypair which corresponds to my address? Spending bitcoins costs me to sacrifice (i.e. can only be used once) a private/public keypair, am I right?

Receiving does not use up a private/public keypair, am I right?

Creating a new address also uses up a private/public keypair, right?

Question

When I spend bitcoins, how is this connected to my address, if it uses a new private/public keypair everytime, that has nothing to do with the original keypair of my address?

Spending bitcoins costs me to sacrifice (i.e. can only be used once) a private/public keypair, am I right?

No that's not correct. Key pairs can be reused but it is not recommended for privacy reasons. All transactions are public and reusing the same address over and over again make it easy for people to build a profile about you.

  Receiving does not use up a private/public keypair, am I right?

You need an address to receive bitcoins and behind that address is a key pair. But you can reuse it like I said above.

  Creating a new address also uses up a private/public keypair, right?

See above.

  When I spend bitcoins, how is this connected to my address, if it uses a new private/public keypair everytime, that has nothing to do with the original keypair of my address?

It doesn't use a new key pair everytime.

You need to read up on asymmetric cryptography. The gist of it is that the private key and public key are mathematically related. Bitcoin spend transactions are signed by your wallet using the private key and that signature can be verified by everyone using your public key. Private key does not have to be exposed in order to spend or receive bitcoins.

A bitcoin address is a hash of your public key and that hash operation is also repeated by nodes to verify that you indeed own the bitcoins and have the right to spend them.


Sync of bitcoin main-net does not finished yet. Are there any ways to speed up it? I'm downloading bitcoin main-net node to AWS instance. However it doesn't finished yet even though it has already passed four days.
My node's latest block is 321,744, and the latest block of Bitcoin main-net is 385,707.
Could you tell me how to hasten the speed of downloading?

It's probably using 100% CPU? Maybe you can add some CPU temporarily? Which version are you running? 0.12 is currently in beta and is about 5x faster with signature checking, which is the biggest CPU user. https://github.com/bitcoin/bitcoin/blob/master/doc/release-notes.md


Thin Client and OP_RETURN I'd like to better understand how a light client works. As far as I know, a light client stores locally only the block headers (80 bytes each) and it receives a new block header on average each 10 minutes.

I've essentially two questions:

1) How can a light client retrieve a transaction given its hash? I'd like to get back the complete transaction so to read out the data after the OP_RETURN code.

2) How can the light client be sure that the retrieved transaction is really the one in the longest blockchain? Does it simply check if there are 5 blocks already confirmed after the transaction's block?

Thank you very much

1) The easiest way within the protocol is probably to add that transaction hash to a bloom filter, send the bloom filter to a remote node with filterload, and request each filtered block. This will send you only the transaction you're interested in. (It will also send some extra transactions that match the bloom filter because they're false positives.) See BIP37 for more details about how this feature works. This is how BitcoinJ based light clients find transactions relevant to them.

Knowing the block height that this is included at would simplify this enormously, as you will only need to look at one block, instead of the entire chain.

2) No. They get the block headers for the entire best chain. This goes from the genesis block to the current tip. (This is currently 450000*80=36MB) They then check that the relevant block is somewhere in that chain.


Up to 4 Different Points within ECDSA/Public Key Recovery technique In the answer to this question, it is stated that:

  Rearranging this equation you get rP = sR - mG, or P = (s/r)R - (m/r)G. Thus, it seems we can just compute the public key from the message and the signature. Unfortunately, there can be up to 4 different points R for which R.x mod n = r (in practice, the number is almost always 2).

How is it possible that there could be up to 4 different points for R? And why would it most often be 2 different points?

Negating an elliptic curve point means negating its Y coordinate (modulo the field size p), so -(x,y) = (x,-y). This implies that if you have a point R for which R.x mod n = k (where n is the curve order), then the same will be true for -R.

Furthermore, and with negligable probability, it is possible that both R.x and R.x + n are valid X coordinates (only when R.x < p-n). In that case, there are 4 possible points ((r, y1), (r,-y1),(r+n,y2),(r+n,-y2)).