text:
lightning network dispute costs
I have some questions about Lightning Network.  I'm already banned from r/bitcoin so I'm posting here.  My first questions are about dispute costs:
Lets say I open a payment channel on the lightning network.  I need to have some balance in the channel, so lets say I have put in 1 bitcoin.  I make a purchase for .5 bitcoin.  There is then a dispute:  the seller is claiming my entire bitcoin from me.  Now what?
Per the whitepaper I can "dispute" this by broadcasting the transaction to the blockchain.  (Are there other options?)
1) Who pays for that, and how much?  Do I pay per bit whatever the market value is for block space at that time?
1a) With the claim on my entire bitcoin where do the transaction fees come from?
1b) What would prevent somebody from using this "pay to take it to court at auction prices" model as a denial of service or theft?  For example, a large actor opens many channels and funds them so they are used as hubs....then when well established he "outright disconnects" some large number of those channels.
Now there is very high demand for limited blockspace as everybody tries to dispute before the deadline.  What happens next?  What if there is so much congestion that disputes can not be made fast enough?
Either ELI5 or point me at the right page(s) and sections of the whitepaper.
Much appreciated,
Blade.

I'd imagine the other transacting party needs your signature on the updated transaction... But don't take my word for it; I watched this ELI5 video.

Who pays for that, and how much? Do I pay per bit whatever the market value is for block space at that time?

The fee for the commitment transactions is determined at the time of channel creation. It can also be updated. So when you broadcast the commitment transaction, the fee will already be set to whatever you two agreed to at channel creation.
The person who pays the fee is also negotiated at channel creation. The current specification says that the person funding the channel will be paying the transaction fees (currently only one party funds the channel).

With the claim on my entire bitcoin where do the transaction fees come from?

There is no "claim on your entire bitcoin". The other party cannot claim your money unless you agreed to it by signing a commitment transaction. The merchant can only say "you owe me one Bitcoin" but nothing actually happens to the Bitcoin itself.

What would prevent somebody from using this "pay to take it to court at auction prices" model as a denial of service or theft? For example, a large actor opens many channels and funds them so they are used as hubs....then when well established he "outright disconnects" some large number of those channels. Now there is very high demand for limited blockspace as everybody tries to dispute before the deadline. What happens next? What if there is so much congestion that disputes can not be made fast enough?

If the most recent commitment transaction is broadcast, there is no "dispute". It is just a normal unilateral channel closing and both parties will get their money eventually (the broadcaster must wait out the relative timelock).
If an old commitment is broadcast (and thus fraud is occuring), then there will be only two transactions for each channel closing ("disconnect") and revocation ("dispute"). The closing transactions need to be confirmed before the delay goes into effect. So if there is a shortage of block space, then not all of those closing transactions will be confirmed. When they do confirm, the other parties can then broadcast their revocation transactions and have those confirmed.
Furthermore, because the transaction fee for the closing transaction must be negotiated by both parties and the amounts can only be changed by both parties signing the transaction, the attacker cannot change the transaction fees. So the people broadcasting their revocation transactions have full control over their transaction fees, so they can increase the fee as necessary to have their transaction confirm faster.

How does the fee commitment get negotiated?  Does the wallet have a workflow for proposing and accepting terms?  As a sender do I need to negotiate with each node in the network that my transaction goes through?  To update it would I need to re-negotiate and get all parties to agree?

I see, so based on your previous answer, the counterparty cant claim the whole bitcoin because some of my bitcoin is already set-aside while openeing the channel.  But what if that reserved closing transaction fee is not enough to get it into a block?  What happens if the HTLCs start to expire while the dispute is stuck in the mempool?  What if the counterparty refuses to renegotiate or does not have the funds to contributte to paying higher fees?

If the fee the attacked would need to pay to dispute is large compared to the size of the transaction doesnt that effectively allow non-cooperation to be used as an attack?

The commitment transaction fees are negotiated in the channel creation message. You as the user are not involved in that except in configuring your LN node to accept channels of certain fees (of course there are defaults and they use fee estimation). Fee negotiation for transaction fees only occurs for parties you will have a direct channel open with. For routing payments, there is HTLC fee negotiation, which is different from transaction fee. Fee negotiation consists of "here is my feerate, do you accept it" and the response is a "yes" or "no". If "no", the channel or HTLC is not created.

It's not that the Bitcoin is set aside, but rather it is assigned to your output and that cannot be changed without you also signing the transaction. If the fee is not enough to get into a block, then it will just sit in the mempool. For the HTLCs if any fraud occurs with those, you can still use the revocation key to claim the money as there is also a relative time lock delay on the HTLC success and HTLC timeout transactions.

No, there isn't any non-cooperation attack that can steal money. When I was talking about the revocations, that is only for old commitments. If you or the other party just broadcasts the latest commitment transaction, then no money can be lost and the channel will just close. The only caveat is that the broadcaster will need to wait out the relative timelock in order to spend their money again. But the revocations are only for when an old commitment is broadcast.


text:
My Bitcoin.com wallet is asking for a password to confirm send that was never established. So im screwed or file a class action for this?

Wtf is this. Password was never established so i cant send this or get it back. So who is the dummy(besides me) that creates something with no way to retrieve your funds? This is ridiculous

If you really never set a PIN, and obvious things like "0000" don't work, then this might be a bug in the app software.  You could report the bug at https://github.com/bitcoin-com/wallet/issues, and include full details about what you did.  They might have suggestions about what to do, but there may or may not be a workaround.
I suggest that you avoid expressing anger, frustration, or legal threats in your bug report.  The developers probably want to fix the bug, and they would rather work with people who seem motivated and cooperative.  If you seem like a difficult person to work with, they won't want to, and you can't force or intimidate them into doing so.
You could try deleting or resetting the app and restoring it using the 12-word recovery phrase that you created when you first installed the wallet.  It should also be possible to use the recovery phrase to access your coins from different wallet software.
If you didn't save the recovery phrase, or you have lost it, then you may have just learned an expensive lesson about the importance of backups.  Software bugs are just one of the many things that can go wrong when using Bitcoin; you can also lose or break your device, get coins stolen by malware, etc, etc.  These are the risks you take, and backups are one of the prudent ways to reduce those risks.  (Actually setting a PIN is another.)
As to whether you can sue, you'd have to consult a lawyer who knows about consumer law in your jurisdiction.  Personally, I doubt that you would be successful.  It's likely that the app's terms of use were carefully written by Bitcoin.com's lawyers to shield them from legal liability in case of software bugs.  In general, when you use free software, you should assume that it's at your own risk, and that nobody will compensate you if things go wrong.

I do have the recovery phrase all 12 of them. Still can't seem to get it. CryptoDave is on the case.

Don,t worry at all. That's what happened to me. All I had to do was deleting the app and reinstalling it again. After entering my user name and password (I had already logged in) I was allowed to set my pin. No further problems.

source: Stack Exchange

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

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

sort: votes


text:
Bitcoin Core 0.13 -- jsonrpc interface -- conflicted transactions
I use bitcoind's Wallet feature to manage my bitcoins.
Using json-rpc interface, how can I check that a transaction is a conflicted one? And, how can I get txhash of a transaction, that spends those same outputs and is confirmed(malleability situation)?

If you call listtransaction, you should get a JSON array called walletconflicts.
If your transaction conflicts with another transaction in your mempool or with a transaction in a block, this walletconflicts array is filled with n transactions-id's that points to the tx that spends the same, conflicting inputs.
walletconflicts is also present in gettransaction

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


text:
How to create walletconflicts in regtest mode?
I play with Bitcoin Core 0.13 in regtest mode using python. Now I use bitcoin-testnet-box, I have two nodes connected to each other. I want to create a walletconflict. I want to get gettransaction <txid> result with non-empty walletconflicts field.
How can I achiev this?
I've tried to get two different addresses from one node and send money to them from another, using raw transactions api and -zapwallettxes restart, but the second txid is not visible in the recipient wallet.

Guys, any suggestions?


text:
BitcoinCore walletnotify before blocknotify?
I want to use bitcoind's walletnotify and blocknotify features. The question is:
Is blocknotify script always triggered after walletnotify script?
Imagine, I have an unconfirmed transaction in my wallet and I wait for a new block to arrive. When bitcoin node gets a new block, it has to fire both walletnotify for the first confirmation of my transaction and blocknotify for the block. Are all walletnotify events always fired before a blocknotify event?


text:
Is Bitcoin network truly distributed without central authority?
When a node joins the Bitcoin network it gets its info from either a preinstalled list, dns or irc. All of these 3 could potentially imply a central authority for who's on the network. Who exactly maintains them?

You can get your pre-installed lists from anyone you choose by any method you choose. There is absolutely no requirement to you get these lists in any particular way or from any particular authority.
If you wish, you can make your own list of bitcoin nodes you consider "valid". You can publish this list by a web page, by DNS, or by any other method you choose. Anyone who wants to can use your list, or not use your list, however they want. And Bitcoin will work just the same.
When someone follows an "authority" because that authority is convenient, I do not consider that centralization. As long as people are free to choose to follow a different authority, or just do it themselves, if at any time they no longer like what that authority is doing, that's not centralization in my view.
And, of course, none of this is relevant once you find a few bitcoin nodes to talk to. It only affects the initial bootstrapping process. You have the same issue with getting the bitcoin software in the first place. Is bitcoin not decentralized unless everyone writes their own implementation of the protocol? Or is it decentralized so long as people are free to if they wish?

I was hoping for something built into the software that would guarantee a list with integrity. The majority of miners will probably get the hard coded list, which unfortunately could sway the mining privileges a certain direction. That said, by no means I'm accusing Bitcoin Core dev of any malicious acts. It's just a fight towards perfect algorithmic software.

@RawadRifai I don't think the majority of miners get the hard coded list. I believe they exchange lists among themselves to ensure the fastest propagation of their blocks to each other for mutual benefit. See this as just one example.

Awesome, thanks David. This is helpful. I must admit I have been confused about the network operations behind the bitcoin network. For now I will trust that the list of participant miners is not being modified or tempered in anyone's advantage.

The seed nodes and DNS seeders provided in Bitcoin Core are maintained by the Bitcoin Core developers. They are only used for the first time that a node is started. The DNS seeders are operated by well known Bitcoin Core developers. The seed nodes are built from a list of nodes provided by Pieter Wuille's DNS seeder and that process is documented and scripted here: https://github.com/bitcoin/bitcoin/tree/master/contrib/seeds. Note that this process of generating the seed nodes can be done with any other DNS seeder and is not exclusive to Pieter's.
It is also important to note that the DNS seeders and seed nodes are only used on the first start of a node and are fallbacks. When a node has started, it will request a list of peers from each node that it connects to and build its own database of peers to connect to. It then uses this to connect to peers on later starts. Only if this fails will it fallback to using the DNS seeders and seed nodes.
Lastly, you can provide a specific list of nodes that you want your node to connect to at anytime. The list of seeders and seed nodes can be changed, and you can tell your node which other nodes to specifically connect to.

I was hoping for something built into the software that would guarantee a list with integrity. The majority of miners will probably get the hard coded list, which unfortunately could sway the mining privileges a certain direction. That said, by no means I'm accusing Bitcoin Core dev of any malicious acts. It's just a fight towards perfect algorithmic software.

What do you mean by "guarantee a list with integrity"? The majority of miners have probably had their nodes up for such a long time now that they are connecting to peers from their own peer databases and haven't checked with any of the DNS seeders since the first time the node went up and have never looked at the hard coded seed nodes. Peer discovery will inherently be some form of centralization. There is no way to discover peers without someone first telling you at least one peer to start with. The DNS seeders and seed nodes give that initial starting point; from there it is all algorithmic.


text:
What bitcoin wallets support bip32 extended public key export?
I'm looking for a bitcoin wallet, that can export an extended public key. I want to put that key on a server, generate a chain of addresses and receive bitcoins, and be sure, that my bitcoins are safe on the server.
Currently I know, that only Electrum can export extended public keys. Could someone suggest other wallets, that are capable of doing this?

Consider to use a hardware wallet: https://bitcoin.org/en/choose-your-wallet.
IMO all of the available hardware wallet do allow to export an xpub.
But watch out (regardless of what wallet you are going to use)!
Even if you private keys are safe when you use public child key derivation, what happens if an attacker compromises your server and replaces the xpub with a extended key controlled by the attacker?
Be careful and read about "Server Hardening".
Also, if you run a VPS or dedicated root server, your server-center operator may have full access to you file-storage.

Bitcoin Wallet can export the extended public key via Settings > Diagnostics > Show xpub.
The description of that option says:

View the extended public key of your wallet, so it can be imported into other apps and services. Be careful: doing so will disclose your monetary privacy to that app.

In copay, bitpay or bitcoin.com wallet you can go to settings > scroll down to bitcoin wallets and choose the wallet in question > scroll down to "more options" > wallet information and then at the bottom the xpub will be shown as copayer0.


text:
BitcoinCore 0.13 HD wallet chain structure
What are the "paths" of keys from BitcoinCore 0.13 HDWallet?
As is described in BIP32
, I consider a path to be the route from the root node to the key node. For example, m/0'/0'/1' stands for the second hardened child of the first hardened child of the first hardened child of the master root node.
I want to know that to be able to regenerate this chain myself using some bitcoin library in case gaps in my chain will exceed 20 keys (current default gap value of BitcoinCore 0.13).

You can just call getnewaddress to recreate you addresses after restoring a backup beyond what the keypool has, and possibly rescan to find old transactions to them. The Bitcoin Core HD wallet support does not currently have any gap detection.

It uses m/0'/0'/i' with i incrementing over time.
The dumpwallet RPC command will produce a text file with all private keys in it, including the BIP32 seed.

So the total key number is 2^31, right?

What does key number mean?

@Yevhen: right, maximal amount of keys (Bitcoin Core only use hardened keys) is 2^31.


text:
Bitcoin Core 0.13 -- SENDFROM rpc call
I want to use sendfrom bitcoind rpc method to transfer funds from my account to some address. Right after calling it, I want to get all the data about this transaction using gettransaction or listsinceblock. Does bitcoind's wallet system process a new transaction before or after responding with a "txid" to sendfrom? Is it safe to call sendfrom and gettransaction right after that from my python code for example?

Yes. It's save.
The current transaction submitting logic (CommitTransaction) do report the transaction ID after adding the tx to the local database and to the mempool.
On top, it holds the cs_main and the cs_wallet lock which makes sure not other thread can manipulate the relevant data-structured during the time of AddToWallet and AcceptToMempool.
https://github.com/bitcoin/bitcoin/blob/master/src/wallet/wallet.cpp#L2557
This means, when you call a send* RPC command, you will get response (the txid) after the transaction was submitted to the mempool and added to your local wallet database.
Immediately calling gettransaction is therefore save.


text:
Bitcoin Core 0.13 wallet encryption
Is it safe to encrypt bitcoind wallet if it holds funded addresses?

Not only is it safe to encrypt wallets with money in them, it is unsafe not to do so. Think of your wallet as a computer file serving as your safe, in which you put your savings. Would you leave your safe open? Probably not. You'd set a complex combination.
This is even more important in Bitcoin. Since your wallet is just a file on your hard disk, it can not only get physically stolen, but also digitally stolen over the Internet by viruses and other malware. Having your wallet setup to not require a password is asking for trouble. You could lose everything in an instant.
The only real risk of encryption is forgetting the password. Unlike a safe, encryption can't be bypassed by a locksmith. Lose the password, lose the money. If physical theft is not a problem for you, you may want to write down the password and put it in a safe deposit box. Viruses don't read paper. Regardless of encryption, you also want to make a backup of your wallet file onto external storage, in case your hard drive goes kaput. This should also be in a safe place.


text:
What if I don't send the complete amount from my paper wallet?
I have been trying to understand the concept of paper wallets. They seem to be secure in the sense of holding our bitcoins but no so much when we try to spend the bitcoins from the paper wallets. Now, I am supposed to transfer all the bitcoins from my paper wallet at once while importing the private key in blockchain.info. But what will happen if I spend a little bit from it?
From what I understand at this point, the rest of the amount won't be present in the paper wallet address. It will go to a "change" address. This is where it gets all confusing. How will I get access to the rest of the bitcoin amount then?

When you make a transaction, you will make a change output. This output can be to any address that you want, just as if you are sending Bitcoin to someone else. Depending on the software you are using, you can set the change address to whatever you want. You could send the coins back to your paper wallet address or you can create a new paper wallet and send the change there.
It is recommended that you do not reuse addresses, so you should create a new paper wallet and send the coins to that address.


text:
Generate Dogecoin Keys

Can I use the same method of generating Bitcoin private key and public key for Dogecoin?
After No.1 above is complete, does Dogecoin support compressed public key?
How do I generate Dogecoin address from the result of No.1 public key?
Can I use the same Bitcoin signing method on Dogecoin?

Thank you

Lets assume the private key is 0000111122223333444455556666777788889999aaaabbbbccccddddeeeeffff

Both Bitcoin and Doge can share a common private key and use the same Elliptic Curve algorithms to synthesize public keys.
Here is a working example for how one can synthesize an uncompressed public key for Bitcoin or Doge from a common 256-bit hexadecimal encoded integer private key.
% echo "0000111122223333444455556666777788889999aaaabbbbccccddddeeeeffff" | bx ec-to-public -u
040d47568a5e517067a2836c3823fbc58169a7662bfae934a4d41da3e23c98d816e7202dd702ffe038147f78aee4973a581972960a1460312ffb6f3f0f13d4a52c
Here is how a compressed public key can be calculated for either Bitcoin or Doge. Notice the public key is half the size.
% echo "0000111122223333444455556666777788889999aaaabbbbccccddddeeeeffff" | bx ec-to-public
020d47568a5e517067a2836c3823fbc58169a7662bfae934a4d41da3e23c98d816
Computation of compressed and uncompressed Bitcoin and Doge addresses. One must examine this table to understand the version values [-v flags] that must be different for Bitcoin-based altcoins used such as Doge. Unsure if Doge fully supports compressed addresses, but is very likely to do so if the Doge source code forks are updated when Bitcoin is updated. Compressed addresses have been supported by Bitcoin for over 4 years.
% echo "0000111122223333444455556666777788889999aaaabbbbccccddddeeeeffff" | bx ec-to-public | bx ec-to-address -v 0
1PbStXjfDNBU6FZA2iSeisVWwCFN9GK1eQ (is a compressed address)
% echo "0000111122223333444455556666777788889999aaaabbbbccccddddeeeeffff" | bx ec-to-public | bx ec-to-address -v 30
DTjYRngJWn5kdFjkmJSDGdf7pKyfUnVnGg (is a compressed address)
% echo "0000111122223333444455556666777788889999aaaabbbbccccddddeeeeffff" | bx ec-to-public -u | bx ec-to-address -v 0
1NGoV1EGZrwM7yvUYqRC7TMBMj7ftpjR2B (is an uncompressed address)
% echo "0000111122223333444455556666777788889999aaaabbbbccccddddeeeeffff" | bx ec-to-public -u | bx ec-to-address -v 30
DSQu2GAusGqdez75HRQkfDWnErqyEB4Bov (is an uncompressed address)
Believe the answer is yes.


text:
Unable to locate bitcoin.conf in linux
I am new to bitcoin network but I have spent significant time with ethereum.
For getting started with bitcoin I referred running a full node and Developer documentation- Regtest Mode. After installing bitcoin-qt and bitcoind, I was asked to change the password in bitcoin.conf. But I am unable to locate it in ~/<user>/.bitcoin.
pr.singh@GLTINTERN-W040:~/.bitcoin$ ls
bitcoind.pid  blocks  chainstate  database  db.log  debug.log  regtest  wallet.dat

And so whenever I run any command like bitcoin-cli -regtest generate 101, I get error stating:

error: Could not locate RPC credentials. No authentication cookie could be found, and no rpcpassword is set in the configuration file (/home/pr.singh/.bitcoin/bitcoin.conf)

Am I missing anything? Also if you guys can provide a good tutorial to start development and  testing in restest network, it will be quite helpful.

You showed a directory listig using "ls". Maybe that is the first issue. Try using "ls -la", which would also show hidden folders, beginning with a dot.
Otherwise here is a tutorial:
https://bitcoin.org/en/developer-examples#regtest-mode
and
https://bitcoin.org/en/full-node#linux-instructions
difficult to say, what happened, but if you just create a ".bitcoin" directory, and go ahead to create the bitcoin.conf file, you should be ok.

Thanks. I was following the exact same tutorials. I have created bitcoin.conf file myself, but I think it's a workaround. It should be generated automatically.


text:
How Bitcoin client handles DNS seeds?
Command

nslookup seed.bitcoin.sipa.be

gives a list of 40 nodes.
1) Does Bitcoin wallet take all nodes from that list?
or
2) Does Bitcoin wallet behave like normal application that resolves seed.bitcoin.sipa.be and take only one IP address to connect.

seed.bitcoin.sipa.be and the other DNS seeders listed here will return a list of IP addresses when given a DNS query. Bitcoin Core then takes all of those IP addresses and adds them to its internal address manager. It will then attempt connecting to the addresses stored in its address manager which, after the first start, will consist of more than just the nodes returned by the DNS seeders.

Thanks. So this means that even if DNS seed returns  a few invalid IP adresses it's not a problem because Bitcoin Core takes all IP adresses and finds the working ones.

Yes. And there are multiple DNS seeders so it will get nodes from other DNS seeders too.

If you define addnode=seed.xxxxxx.com or type addnode seed.xxxxxx.com add does Bitcoin Core add all IP addresses or just one IP address to it's address manager?

You cannot add DNS seeders via the command line or the RPC commands. addnode will add the one node that you enter to the address manager and then attempt to connect to it. There are no "all IP addresses" for it to even add; you are only giving it one IP address.

The bitcoin client will first try to scan for previous known IPs, once that fails, it will indeed fall back on DNS seeds.
It will resolve seed.bitcoin.sipa.be to a list of IP adresses and it will pick one of them.

What if there is multiple DNS seeds? Will client pick one IP address from each DNS seed?


text:
How to check confirmations number programmatically
How can I check confirmations number for some bitcoin address programmatically? (I have eCommerce shop where each order has separate address).
I want to use blockchain.info API.
Here is an example of the API call, but I can't figure out what numbers should I check in API response:
https://blockchain.info/rawaddr/1JbBiCzQqzE2dW9TCzA6w7N27jVDXxwreD

Confirmations for an address aren't really a thing.  Addresses are not confirmed; transactions are.  A single address is typically used in multiple transactions: one where the address is used as an output, and one where the first transaction was used as an input.  Although it's not a best practice, addresses can even be re-used multiple times.
It looks like this particular address has been used in two different transactions.  Once as an output in 00c83c7677d414053488d0b51067feee157a5b82d5acec5bfe8e9c540c11c624, and once as in input in 378f829160cb9c99cc7a8fb1152472b80f0e1ea9c9cc24118dbccc2da72dedcf.
Each of these two transactions returned in the API response has a block_height value (489353 and 489355).  That is the block at which the transaction was included.  To find how many confirmations each transaction has, subtract the block_height by the height of the most recently confirmed block, and add 1.  So if the current block is 489355, one transaction has 1 confirmation, and the other has 3.

If you are using php, then try this :
function response ($result) {
      header("Content-Type:application/json");
      $response['confirmation'] = $result;
      $json_response = json_encode($response);
      echo $json_response;
  }

$tx_hash  = '5e910a5b61e3ccdb7...'; // try to get a new tx hash from blockchain.info/.com

$bcinfo = json_decode(file_get_contents("https://blockchain.info/rawtx/".$tx_hash), true);
$latest = json_decode(file_get_contents("https://blockchain.info/latestblock"), true);

if(isset($bcinfo['block_height'])) {

   $block_height =  $bcinfo['block_height'];
   $height       =  $latest['height'];

   response($height - $block_height + 1);

}else{

   response(0); // not yet has any confirmations

}


text:
What part of the code is responsible for coinbase payouts?
Looking for the part of the code responsible for doling out coinbase to the miner who solves the puzzle. I'm guessing it's somewhere in src/rpc/mining.cpp, but it's tough to figure out from the code where the payout is happening. Can anyone clear this up?

You're really asking about two separate but related pieces of code. One piece of code claims the mining reward, and the other piece of code says that it is okay for miners to claim a mining reward.
The first is here: https://github.com/bitcoin/bitcoin/blob/1afc22a7667a7a5c66b4b5d7f50832356dd5ec12/src/miner.cpp#L161
The second is here: https://github.com/bitcoin/bitcoin/blob/470c730e3fa9d1120dda1de2d433304023c8aa78/src/validation.cpp#L1819

authors: Богдан Стриженов


text:
OP_ADD operation in bitcoin script for integers greater than 128 in java
I want to execute a simple series of instructions to implement a bitcoin script in java using bitcoinj API. All I am looking for is performing arithmetic operations for negative integers or integers greater than 128. An example bitcoin script for the task would look like this:
150 120 OP_ADD 270 OP_CHECKNUMEQUAL
This script should return True eventually. To implement this in java, to push integer values like 150, 270 etc i have to first convert them to byte arrays. I have followed answers given in https://stackoverflow.com/questions/1936857/convert-integer-into-byte-array-java but none of them works in here probably because of differently defined arithmetic operations in bitcoinj API script. Can anyone please help me in this.

Can you post the code you have so far?

you should use Litte-endian encoding. if the highest bit is set (range 128-255, 32768-65535 and so on) you should append the zero byte to mark these bytes as positive number.
So, 150(dec) will be encoded as 9600
270(dec) will be encoded as 0e01


text:
Where is my money
I am a newbie, pretty good on the computer. I received a email from coinbase that they have my deposit.
Where does it go.
Is there a easy step by step to find my funds, I want to buy something today.

So you spent real money in exchange for Bitcoins, gave it under management of a company Coinbase, and don't know what to do with it next. And instead of reading Coinbase's help resources (before sending them money), you ask us... Strange!

You got an email from Coinbase... did you already have an established customer relationship with them in any way? There are tons of scams going around where spammers send email "from coinbase" saying "we have your money", but there's actually nothing of the sort and they just want to scam you in some way.

Are you saying you signed up for an account at coinbase.com and deposited funds to purchase bitcoins? This seems like a reasonable assumption, but it pays to be sure!

It goes to your coinbase account. Just login to www.coinbase.com and click my account and you will see your funds.

Your deposit to coinbase will be credited to your "USD wallet" on your coinbase account when it clears. The USD wallet is where your USD is stored until you spend it, but you cant spend it until the bank transaction has cleared and coinbase knows that it's irreversable. This usually takes 1-2 weeks.
After the bank has cleared the transaction, coinbase will credit your USD wallet and you will be able to buy cryptos.


text:
What can be changed in signed bitcoin transaction?
What can be changed in signed bitcoin transaction?
I mean how is possible to modify transaction to change its hash, but keep transaction valid, without need to have sign private keys?

Here is the list of known sources of malleability from BIP62 (which has been withdrawn, and is no longer up to date, but does give some insight):

DER encoded ECDSA signatures Right now, the Bitcoin reference client uses OpenSSL to validate signatures. As OpenSSL accepts more than serializations that strictly adhere to the DER standard, this is a source of malleability. Since v0.8.0, non-DER signatures are no longer relayed already.
Non-push operations in scriptSig Any sequence of script operations in scriptSig that results in the intended data pushes, but is not just a push of that data, results in an alternative transaction with the same validity.
Push operations in scriptSig of non-standard size type The Bitcoin scripting language has several push operators (OP_0, single-byte pushes, data pushes of up to 75 bytes, OP_PUSHDATA1, OP_PUSHDATA2, OP_PUSHDATA4). As the later ones have the same result as the former ones, they result in additional possibilities.
Zero-padded number pushes In cases where scriptPubKey opcodes use inputs that are interpreted as numbers, they can be zero padded.
Inherent ECDSA signature malleability ECDSA signatures themselves are already malleable: taking the negative of the number S inside (modulo the curve order) does not invalidate it.
Superfluous scriptSig operations Adding extra data pushes at the start of scripts, which are not consumed by the corresponding scriptPubKey, is also a source of malleability.
Inputs ignored by scripts If a scriptPubKey starts with an OP_DROP, for example, the last data push of the corresponding scriptSig will always be ignored.
Sighash flags based masking Sighash flags can be used to ignore certain parts of a script when signing.

(1) has been fixed for all transactions by BIP66, and (2)-(6) are prevented by standardness rules in recent Bitcoin Core releases. A specific case of (7) is proposed to be fixed by BIP147.
Segregated Witness (BIP141) proposes fix all of them, but only for transactions that spend  solely from segwit outputs. It does this by moving the scriptSig data to a new field (the witness) which does not influence the txid.

do you really think that OP understands your answer? :)

Maybe, maybe not. OP is free to vote or accept whatever is most informative. But I'm not just answering the question for OP, and this may give a more detailed response for other people that find this page

No! The algorithms are generated by the first block created by bitcoin so if you change the hash, the transaction will not be recognized and invalid.

Transactions in mempool can be changed.

Fails quickly correct! Fortunately...

TL;DR
Today - nothing
In fact, there are several sources for malleability. Most of them (not all) are already fixed by changed consensus rules, others become transaction non-standard.
But. Are you an attacker or a defender?
You can create transaction which can be malleated by any person without invalidating it and without knowledge of your keys. It is easy.

I am attacked by someone, I see in network many copies of my transactions. Which are not mine of course and I am wondering why someone is doing that and how is that working?

can you provide txid(s)?


text:
Namecoin - How to Find Block Height via Block Hash?
Is it possible to use namecoind to determine the block number from a block hash?
Going from height to hash is easy:
namecoind getblockhash
But going from hash to height appears to be impossible...
Height is not an attribute on each block and no method appears to return it.
The closest two are:
namecoind help getblockcount
"Returns the number of blocks in the longest block chain."

namecoind help getblocknumber
"Returns the block number of the latest block in the longest block chain."

This is close, but I don't want the single, largest height value, I'm looking for a way to look up any block's height via its hash.
So there are two methods which do the same thing (return greatest height) and no methods that take a block's hash and return that block's height.  Block height is also not a block attribute.
Is there something I'm missing here?  Other coins do not appear to lack this basic functionality.

At the time of asking, this functionality wasn't supported in Namecoin. I've written a patch that adds this and a few other properties to Namecoin's getblock RPC call.
https://github.com/namecoin/namecoin/issues/87
https://gist.github.com/ryancdotorg/5e610e9ee546beed367d


text:
bitcored fastsync
Is any way to sync bitcore daemon faster?
  Options:

-h, --help          output usage information
-V, --version       output the version number
-c, --config <dir>  Specify the directory with Bitcore Node configuration
-d, --daemon        Make bitcore a daemon (running in the background)

There is no that option in CLI, and I cant find nothing about config.json

Syncing to the blockchain involves a lot of downloading, disk usage, and computation.
Look at what resources are being used the most, one of them will be the bottleneck. For me it was my hard drive that was slowing everything down, once I upgraded my platter drive for a high speed SSD it went much faster.
In your case you may be limited by your internet connection speed or your CPU. Find out which and upgrade it.


text:
BitcoinJ - Master Key from 12 word
Is there any posibilities to:
1. Create deterministic seed from 12 or 24 word
2. Create Private Master key from this deterministic seed
3. Create deterministic wallet using private master key
in BitcoinJ


text:
Arbitrage in the Bitcoin / Bitcoin Cash fork
So assuming BTC and BCC are both viable and tradeable for some period after August 1st, is it not inevitable that some people will double spend, by trading a coin on BTC and also the same coin on BCC?
Any ideas what that will look like from an arbitrage perspective while the fork works itself out?

A coin on either fork is distinctly a coin on its respective fork. Sure you can send someone BTC and then send someone else BCC that spent the "same" input, but no one will care because that is entirely a different coin using a different blockchain. With the kind of fork that will be happening, no sort of fraud (outside of any normal fraud) can occur. The fork implements two way replay protection so receivers cannot replay transactions and get money on both forks, and double spending cannot happen because this will be a persistent chain split with no possibility of blockchain reorganizations.

That there is $40 billion of market value in Bitcoin, how can they not care if it is forked? You can't maintain that stored value in both chains, or you will end up with an $80 billion market cap across the two, instantly creating $40 billion from nothing. That can't happen. Any market value that is found in BCC must, of necessity, be subtracted from BTC eventually, and vice-versa. My question is about arbitraging the liquidity between the markets for as long as both forks have any market value and liquidity at the same time.

It becomes two separate entities, so yes, there can be stored value in both chains. Creating a fork does not take anything out of the chain it forked from, it becomes two completely separate things. It becomes two completely separate coins. There is no necessity that market value of one coin be subtracted from the other as they are just now two completely different coins.

@SmackJack - The market will decide exactly what value is invested in each fork. If people value BCH more than BTC (or anything else), then they will buy BCH with BTC, EUR, USD whatever.  They have been doing this to some extent since the fork happened. BCH now has a notable value, but most seems to be coming from fiat as the BTC value (in fiat) isn't really decreasing.


text:
How to prevent specific method calls to bitcoin node
I have setup a bitcoin node and can access RPC methods via curl or bitcoin-cli.
Now I don't want to share the node with multiple parties and in such case, I want to restict some functions from being executed, like listwallets, getbalance etc.
How can I restrict some method calls?
In Ethereum we have different rpcapi and we can remove personal if we don't want others to play around with it unsafely.
My first guess will be to wrap the wallet functionalities in an application server and allow users to access the blockchain node via that application server and hence we can put any restrictions we want. Is there any better solution?

Bitcoin-core has no built-in mechanisms for restricting access to the API.
For your goals, you need to use a proxy between the user and the node.
For example, https://github.com/rsksmart/rskj/wiki/Nginx-Proxy-Server-for-JSONRPC-Calls

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


text:
bitcoin-cli is not using port specified in config
I have setup a bitcoin node in regtest mode with custom config and datadir.
I start bittcoind with command:
 bitcoind -conf=bitcoin-demo.conf  -regtest  -datadir="testdatabtc" -daemon

My bitcoin-demo.conf looks like:
regtest=1
server=1
rpcuser=alice
rpcpassword=hello
rpcallowip=0.0.0.0/0
rpcconnect=127.0.0.1
# Options only for regtest
[regtest]
rpcport=3133

I am able to connect access my node using curl command
curl --user alice:hello --data '{"method":"getblockchaininfo","params":[],"id":1,"jsonrpc":"2.0"}' -H "Content-Type: application/json" -X POST http://localhost:3133

But when I try to  access the same commands using bitcoin-cli, it tries to connect to port 8332, even when I specify the config file.
bitcoin-cli -conf="bitcoin-demo.conf"  getblockchaininfo

This command produces error:

error: Could not connect to the server 127.0.0.1:8332

This works if I specify the port and auth as command line argument:
bitcoin-cli -conf="bitcoin-demo.conf" -rpcport="3133" -rpcuser="alice" -rpcpassword="hello"  getblockchaininfo

Above command works fine. But the question is
Why bitcoin-cli does not read these arguments from the config file?

Did you try just port=3133

Maybe, try to generate rpcauth with https://github.com/bitcoin/bitcoin/tree/master/share/rpcauth


text:
Bitcoin RPC returning 401
I am using node-bitcoin-rpc to do some api calls to bitcoind, but I am getting 401 error. I know this simply means unauthorized, but I have no authorization enable in my config file.
Howerver I can query bitcoin client using vitcoin-cli --regtest listaccounts, I get the results.
My bitcoin.conf file is pretty simple
rpcport=8332
rpcconnect=127.0.0.1
regtest=1
debug=rpc

PS: I didn't have any bitcoin.conf initially, so I create above one inside .bitcoin folder in home directory.

The RPC interface is an authenticated interface. You need to provide a username and password in order to send RPC commands. These are usually specified in the bitcoin.conf file with the rpcuser and rpcpassword options or the rpcauth option. There are also temporary RPC credentials stored in the .cookie file that can be found in the datadir.
The reason that you have no problems with bitcoin-cli is because it looks up the RPC credentials from the bitcoin.conf file or the .cookie file..

should bitcoin core accept authentication if I manually set bitcoind.rpcuser="__cookie__" and bitcoind.rpcpass=<value from .cookie file> ?

I was struggling a lot as well till recognise the right configuration naming
bitcoin.conf
rpcuser=
rpcpassword=

lnd.conf
bitcoind.rpcuser=
bitcoind.rpcpass=


text:
Why do exchanges have a buy/sell column in their trade history?
Why is there a type column in the trade history on exchanges like btc-e.com and vircurex.com? If all the trades are between two users on the exchange why is a buy/sell type needed? And if there is one entry for buy shouldn't there be an equal entry for sell because the person buying is buying from someone who is selling.

See Investopedia or Wikipedia. Unless I'm mistaken, your transaction is with the market maker.

@RedGrittyBrick No, most exchanges don't buy/sell directly to/from you. They simply provide the platform for buyers and sellers to find each other, and they take a fee off each transaction.

Yes, if someone buys at a particular price, someone else must sell at that price. But they didn't place their orders at the same time. The buy/sell indicates the direction of the filled order. This is needed to make sense of the price.
Imagine an apple exchange where no trades are occurring. Then someone walks in and buys or sells an apple for $1. Do you care whether the person who walked in bought or sold? Well, yes. If the person bought an apple for $1, that means before they walked in, someone was willing to sell an apple for $1 but nobody would buy it. If that person sold an apple for $1, that means before they walked in, someone was willing to buy an apple for $1 but nobody would sell it. So without knowing the direction of the transaction, you can't tell what the price is telling you about the state of the market prior to that transaction.
This is very important in a market that isn't very liquid. For example, say the cheapest anyone is willing to sell a Bitcoin is $1,000, but the most anyone is willing to pay for a Bitcoin is $900. If it stays that way for a while, all the executing buys will be at $1,000 and all the executing sells will be at $900. If you just saw alternating $1,000 and $900 prices without knowing all the buys were at $1,000 and all the sells were at $900, you'd think the price was changing when it's actually constant. Orders that don't execute at all aren't listed because no money changes hands. So the people selling at $1,000 and buying at $900 won't be listed as transactions.

These are orders. You place an order to buy at, say $600, and it is listed on that list as a bit. It will stay there until someone places a ask to sell at $600 or lower.
The spread between them is an indication of liquidity, or how easy it is to make a transaction go through on the site. If they are very close, lots of BTC/USD is likely to be able to be bought/sold quickly.
Another indication you can gain from this is market depth. You can look at the list and figure out how much will the price change if I buy $1000. Say there is a sell order for .1 BTC that costs $100 ($1000 BTC/USD), another with .5 BTC for $505 ($1010 BTC/USD and another with .38 BTC for $395 ($1020 BTC/USD). By spending your $1000 at one time, you will not be able to spend all of it at the current price ($1000 BTC/USD), but will end up buying those .38 BTC for $1020. The more money is necessary to more the price significantly, the deeper the market is and the easier it is to make large transactions.
For more info, look up bid/ask spread and market depth.

I just realized you are asking about trade history. Oh well, I put to much effort into those explanations to delete them.

It's like any market for anything of value. Like stocks or bonds or coins.
The bid price is the price someone has asked to purchase that item for. The asked price is the price someone is asking to sell the item for.
So, if someone is saying they will sell 1 BTC for $600 USD and someone else says they will buy 1 BTC for $599 USD, these are orders waiting to be fulfilled. As long as nothing changes, these numbers stay the same.
Now, if someone else comes along and sees someone is willing to buy for $599. and they are willing to sell for $599. They put in an order to sell, and they sell the 1 BTC to the buyer for $599. If there is no one else willing to buy for $599 and the next willing buyer wants to buy at $598. Then the bid price lowers to $598. while the ask is still $600.


text:
I live in viet nam and I want to buy bitcoin. How would I do that?
I would like to buy bitcoins in viet nam. How would I do that?

@gary welcome to the site. This question has been asked a number of times for several countries in this site. You can try the search box in the upper-right corner - as others indicated, most probably "local bitcoins" will be for you.

Hello gary, this question has a generic answer at How do you obtain bitcoins?.

I would say try https://localbitcoins.com
You can buy from other people in your area/country.

did you try to contact someone on https://localbitcoins.com/country/VN
Its listed there. There are few users with reputation offering bitcoins for western union


text:
Has anyone experienced money wire from Bitfinex to a european bank? How are the fees applied?
I try to find the best way to cash-out when needed. I use Bitfinex lately and I see that they have a good fee structure (https://www.bitfinex.com/fees - if you know something better let me know). However, I am curious that if it is the same Europe. Is there any one who experienced this and give some information regarding all the fees and disposals I need to consider?


text:
Dash Supply Cap?
A while back, a friend told me dash had the same supply limit that bitcoin had of 21 mil.  I read on wiki recently that it's now 19 mil.

Estimated 19 million coins maximum, with a 7,1% decrease in the number of coins

Did this change?  How can it be increased?

No idea. But did you and your friend read this bit "All told 1.9 million coins were mined in 48 hours"? Hint: that's a sure sign of a scam, it's called pre-mine meaning the top of the pyramid started the party early and the suckers are invited later.

Moreover, the block reward got massively decreased shortly after this grab, and the coin cap was brought down after the fact (maybe even twice, I can't quite recall). All those changes being of course favorable to the dev and to the detriment of later suckers.

Might want to examine Section 5.2 of a Dash White Paper.  Here is the relevant code concerning Dash's monetary policy.
It is difficult to project the exact amount of Dash currency that will come into existence because it appears to be a function of network difficulty, not block number or time.  However, hard limits in the code appear to set upper and lower bounds in the graph of the Dash White Paper. Plus funds not fully allocated by the Dash Treasury by masternodes (the Superblocks, associated with 10% of the block awards) are burned which reduces the overall supply.
Also ran across this Dash Detailed video that provides an explanation.
It is worth noting the that the factor of ~7.14% (written as 1/14 in source code) approximately fits the Rule of 72 divided by 10, which means the amount of inflation is cut in half roughly every 10 years.

The white paper inexplicably has two Section 5's. The mining supply is discussed in the first Section 5. (In case anyone else has trouble finding the relevant section.)

The last Section 5 "Conclusion" should have been called Section 6.


text:
Bitcoin Transaction Structure
Is there a "standard" Bitcoin transaction format?
The context is that I am putting together a tech talk to explain the blockchain concept to complete newbies, and I wanted to show the general structure of a transaction. However, I see different JSON document structures (different field names and content structure) returned by different sources, for the same transaction. For example, compare the output of the following 3 sources for Tx ID 90b18aa54288ec610d83ff1abe90f10d8ca87fb6411a72b2e56a169fdc9b0219

https://blockexplorer.com/api/tx/90b18aa54288ec610d83ff1abe90f10d8ca87fb6411a72b2e56a169fdc9b0219
https://blockchain.info/tx/90b18aa54288ec610d83ff1abe90f10d8ca87fb6411a72b2e56a169fdc9b0219?format=json
https://cdn4.cryptocoinsnews.com/wp-content/uploads/2014/07/Bitcoin_tx_example.png

I know the image (#3) is showing only a subset but it has in and out arrays, and an input has a prev_out object with a hash string field. However, #1 (BlockExplorer) has vin and vout arrays, and the input does not have a prev_out object. It directly contains a string txid field with the hash of previous output transaction. There is yet another JSON structure in #2 (blockchain.info).
Is there an "official" or "standard" JSON structure of a transaction? If so, I would like to show that in my talk. Or what would be the recommended way to show a newbie what a Bitcoin transaction looks like?

The official or standard names would be the ones built into the bitcoin JSON-RPC API. The developer reference section is a good place to start you can see example outputs from different calls.
For example the result to the gettransaction call:
{
    "amount" : 0.00000000,
    "fee" : 0.00000000,
    "confirmations" : 106670,
    "blockhash" : "000000008b630b3aae99b6fe215548168bed92167c47a2f7ad4df41e571bcb51",
    "blockindex" : 1,
    "blocktime" : 1396321351,
    "txid" : "5a7d24cd665108c66b2d56146f244932edae4e2376b561b3d396d5ae017b9589",
    "walletconflicts" : [
    ],
    "time" : 1396321351,
    "timereceived" : 1418924711,
    "bip125-replaceable" : "no",
    "details" : [
        {
            "account" : "",
            "address" : "mjSk1Ny9spzU2fouzYgLqGUD8U41iR35QN",
            "category" : "send",
            "amount" : -0.10000000,
            "vout" : 0,
            "fee" : 0.00000000
        },
        {
            "account" : "doc test",
            "address" : "mjSk1Ny9spzU2fouzYgLqGUD8U41iR35QN",
            "category" : "receive",
            "amount" : 0.10000000,
            "vout" : 0
        }
    ],
    "hex" : "0100000001cde58f2e37d000eabbb60d9cf0b79ddf67cede6dba58732539983fa341dd5e6c010000006a47304402201feaf12908260f666ab369bb8753cdc12f78d0c8bdfdef997da17acff502d321022049ba0b80945a7192e631c03bafd5c6dc3c7cb35ac5c1c0ffb9e22fec86dd311c01210321eeeb46fd878ce8e62d5e0f408a0eab41d7c3a7872dc836ce360439536e423dffffffff0180969800000000001976a9142b14950b8d31620c6cc923c5408a701b1ec0a02088ac00000000"
}

Source: https://bitcoin.org/en/developer-reference#gettransaction

Note that gettransaction is a wallet RPC, which shows the effects of a transaction on your own balance/wallet. This depends on which addresses are considered yours, labels/accounts, and other transactions. If you want a pure "decode" of the actual transaction data, use decoderawtransaction on the hex field.

authors: Евгений Потравка


text:
Why isn't my full node accepting incoming connections from other nodes?
I have a full node on a Gentoo box. I have port forwarding on my router setup so that port 8333 is sent to the IP of my full node. I opened port 8333 on the machine using:
iptables -A INPUT -p TCP --dport 8333 -i wlp4s0 -j ACCEPT

The node is fully synced with the network and I can watch new blocks arrive in the debug log. I thought I was fully participating in the network, but when I check for my full node at Bitnodes it says that my node is unreachable.
Any suggestions? Is there any other way to test public access to my full node?

If you run nc -z localhost 8333; echo $? does it output 0 (success) or 1 (failure)?

Freaking Gentoo...had to compile netcat but I do get 0 from that command. I think the problem is somewhere in my router or WiFi configuration.

Next thing to try is nc -z <external ip address of router> 8333; echo $? If that fails, there's a networking issue or a portforwarding issue. PS: Debian rules.


text:
Exactly how to add bitcoind params (e.g. "verbose") on command line?
Some bitcoind commands have optional params. For example, when doing "bitcoind help", it says the getrawmempool has a "verbose" param.
But no matter what I try, I can't seem to set this param on the command line. I've tried this:
bitcoind -verbose getrawmempool
bitcoind getrawmempool verbose
bitcoind getrawmempool -verbose
bitcoind getrawmempool verbose=1
bitcoind getrawmempool -verbose=1
bitcoind getrawmempool {"verbose":"1"}
bitcoind getrawmempool {"verbose":"true"}
bitcoind getrawmempool {\"verbose\":\"1\"}
bitcoind getrawmempool {\"verbose\":\"true\"}

Especially notice how the last few result in "error: value type is obj, expected bool" whereas the others give "error parsing JSON".
What should I type on the command line exactly in order to execute the 'getrawmempool' with the 'verbose' parameter?

Usually it's fairly descriptive if you know what's going on, for example it looks for a  boolean on the end of that command, so this will do as you wish.
bitcoin-cli getrawmempool true

bitcoin-cli has replaced bitcoind for RPC commands, you'll need to get used to it as the RPC client is being removed from the bitcoind binary fairly soon.

to answer the original question:
$ bitcoind getrawmempool true

will pass "true" to the verbose parameter (and will give you the verbose output)


text:
What's up with all the QR codes?
Just bought $5 of Bitcoins from CoinBase. How do I spend them? I gather it has something to do with QR codes. . . .

don't worry -- they're there for convenience only.
Scanning the QR code helps reading either a public key (to verify) or your private key (to spend your bitcoins) into whatever application you are using to verify or spend from your balance respectively.
Copy-and-paste works as well, doing the same for you as those QR codes you see everywhere...


text:
What's an efficient model for redistribution of coins between wallets?
Let's say I have 50 addresses which have an average of 0.5 BTC. Some have two or three times the average balance, while others have less than 0.1% of the average. Many times per day an address is selected to either receive or send some amount of coins, fueling the inequality.
What's an efficient, cost-effective method of rebalancing a large number of addresses such that each contains roughly the average balance?
(Assume the algorithm to select a keypair with which to transact is fixed and cannot be modified for argument sake.)

I am wondering whether this is an XY-Problem. At least it makes me curious, why you would want to do that.

I don't believe it's an XY problem. The reason is that I would like to keep coins spread across 50 addresses roughly evenly, and sometimes I might transact with a given address without checking its balance in relation to the other 50 for performance reasons.

@Chris You still haven't answered the base question: Why do you want to keep your balance spread across 50 addresses instead of any other way (e.g. in one wallet, in whatever addresses they happen to go in)?

@TimS. I don't really see how the reasoning is relevant. The point here is that I have N addresses and want to occasionally make their balances roughly equally. Assume there's a good reason why without needing to understand that specific reason.

Better yet, assume I don't know the reason why many addresses are desirable. Assume that the parameters are set and I'm simply looking for a solution within those parameters.

Once a day, take the addresses with balances more than some multiple (say, twice) of the average, and create a transaction that sends money to the lowest-value addresses. E.g. let's say the average is 0.5 and call the addresses A-Z:

A: 2.0 BTC
B: 1.5 BTC
C: 1.0 BTC
...[other addresses with under 1 BTC]
X: 0.1 BTC
Y: 0.05 BTC
Z: 0 BTC

Transaction would send from A, B, and C to X, Y, and Z so that each has the same amount (0.775 BTC).

Another solution might be to rebalance during the regular use of the addresses:
Whenever one of the addresses is selected to spend from, check whether an above average balance would remain.
If that is the case, additionally to the planned transaction, redistribute the excess to underfunded addresses, where excess = remainder - average_balance.
You could pick recipient addresses for the redistribution by performing a greedy algorithm such as for example a knapsack problem solver, optimizing for minimal sum of squared distances from the average over all addresses. You could restrain the number of recipient addresses by only allowing an additional recipient address if all previous recipient addresses will be raised to the average.


text:
Can a Wallet Generated by Linux Multibit Client be Used with Windows Multibit client?
Probably a stupid question.
I am planning to create cold storage using Multibit on Ubuntu LiveCD, get the wallet file out of it and store it securely.
In future if I use a Windows PC with Multibit and use the cold storage wallet file with it, should it work fine? Or the wallet file structure are different for Linux and Windows Multibit clients?
Thanks.

Absolutely, if it didn't it would be a bug anyways. Linux and Windows Multibit should work properly on the same backup.


text:
Bitcoin Privacy
In my privacy class I was asked this question related to privacy in Bitcoin:
Which is the computational hard problem that is used to guarantee the privacy of users?
Can anyone help me? The only two computationally hard problems in Bitcoin I know of are the proof of work and breaking the hash collision resistant function, but I cannot quite see how these issues link to privacy.

Bitcoin does not guarantee privacy. Everyone can see exactly how much Bitcoin is associated with any address. The privacy comes from people using multiple addresses so as to hide how much Bitcoin they actually have (and this is also a generally recommended practice) and the fact that there is no way to find out the person behind an address from just the blockchain data itself. To deanonymize a person, they need to have leaked information about themselves and any addresses they control via some other medium such as forum posts, tweets, reddit posts, etc. There are also ways to figure out what addresses are likely to be in the same wallet and thus owned by the same person.
tl;dr privacy in Bitcoin comes down to the fact that users' real life identities are not directly linked to their addresses.

Technically, the hardness of the elliptic curve discrete log problem keeps your private key  private!  But we would normally say that this is what protects your Bitcoins from being stolen, since that is what happens if your private key gets leaked.  So I think this is not really a good answer except to a confused or trick question.
When people talk about privacy in the context of Bitcoin they are normally talking about the keeping the identities of users privacy, and in Bitcoin this isn't provided by cryptography but only by the use of pseudonyms: single or few use, randomly generated addresses.

You are right, these problems are not related to privacy.
Keeping your privacy while using Bitcoin is a conscious and constant effort. You need to not reuse addresses, use widely available wallets to try to limit the amount of metadata you're leaking forever on the blockchain.
What Bitcoin provides (and most people confound with anonymity) is pseudonymity: your bitcoin identity is not linked to your legal identity. But it is still possible to link together bitcoin payments to a single-but-unknown identity.
You can think of a bitcoin address as an email address: I may not know who it is, but it's most likely a single person behind it.
For more information about Bitcoin privacy, you can visit the Open Bitcoin Privacy Project.

So would it be to correct to say that linking users' real identities to bitcoin addresses is the computationally hard problem which contributes to preserving one's privacy in Bitcoin?

There is no computationally hard problem that protects privacy. It is protected by people not leaking it, if they choose to.


text:
Buying a hashrate makes any sense?
I want to start mining through one a cloud service and seems that hashflare.io is a good one. So when I go to the "Pricing" section of the website is say's that I can pay USD $1.20 per 10 GH/s.
How does that make any sense? I'll pay to have a rate, which is measured in seconds. But for how long am I going to keep that rate?
It says it is a Lifetime contract, does that mean I'll pay $1.20 and keep earning bitcoins forever? Seems a bit too generous to me.

It says it is a Lifetime contract, does that mean I'll pay $1.20 and keep earning bitcoins forever? Seems a bit too generous to me.

It is too generous. Read the fine print.

Lifetime contract*
  * as far as mining remains profitable
  Maintenance fee: 0.01 $ / 1 MH/s / 24h

i.e. you pay a fee for the electricity and colocation, and if that fee exceeds the revenue of mining, the contract is over.

I suppose they will deduct that amount from the mining revenue? This is all new to me so I guess I could put say $12 to buy 100 GH/s and just see what happens? I just want to be sure there will be no loss aside from that initial money I will be putting down.

@RodrigoMonte I assume so, but you can ask them if you're unsure.

That maintenance fee seems absurdly high, if it's quoted correctly (and if we are talking about SHA256D).  The expected revenue from mining with 1 MH/s for 24h is about $0.000001.

Are people still making money mining with cloud services?  If it was profitable wouldn't they just run it themselves instead of sitting idle waiting for someone else to pay them to make money???


text:
Why iota coin do not support smart-contracts?
I thought that Iota-coin have a lot of common with Ethereum, but I hae found that it do not have support of smart-contracts. I googled about what was there reason of do not implement it (I really thought that smart contracts is future) but I found only one mention about it:
"Iota itself cannot implement smart contracts cause there is no consensus on state finality and each node has its own personal view of the state, rendering unusable for distributed general purpose computation."
Does smart-contracts have any issues? Or What?

IOTA is very different from Bitcoin. Consensus formation and transactions are not separate. In Bitcoin you have miners that realize consensus on the order of transactions, that are separate from the transactions done. In IOTA every transaction has to validate two earlier transactions. This leads to another data structure than a blockchain, they call the Tangle:

A "blockchainless blockchain".
Now, to implement a virtual machine that can execute a smart contract it needs to have consensus on order of transactions (let's say, the order of "0"s and "0"s). With the Tangle every node has a different view of when transactions happened. This makes it impossible to have consensus on smart contracts.
Facilitating smart contracts is on the roadmap of IOTA. The idea is to do this with timestamp oracles that provide a mechanism for order of transactions. See [http://iota.org/timestamps.pdf](On the timestamps in the tangle).


text:
Which serialization format the transactions use?
I'm not very familiar with low-level structures, so I would like to know if bitcoin protocol follows a standard on how a bitcoin transaction data is serialized and sent over TCP.
Does it use any of these serialization format?
https://en.wikipedia.org/wiki/Comparison_of_data_serialization_formats

All of the data structures in Bitcoin use a custom Bitcoin specific serialization format. The standard that is followed is the Bitcoin defined standard, not any other standard. A description of the non-segwit format can be found here. For segwit transactions, the format is described in BIP 144.


text:
Can someone explain me ECDSA (creating public from private key) with 8-bit numbers?
Trying to understand Elliptic Curve maths with 256-bit numbers seems like hard to explain/understand. I wonder if by lowering down the possible numbers get's a little bit easier.

It's my opinion that mechanical explanations of ECC are almost completely worthless to people, and mostly just generate false understanding.  Exactly how two points get added to each other isn't an important thing to understand in order to understand ECC any more than understanding van der waals forces is important to someone trying to oil paint. So my advice is to find explanations that talk about the abstract algebra of ECC rather than the mechanics of group operations. :)
But some people just love the mechanics.  So if you must, find a tutorial that uses secp256k1 (the 'bitcoin' curve) and replace the field size P  with 79 (so you would be doing arithmetic mod 79 instead of 115...663), and N with 67 (instead of 115...337).  'a' stays 0, 'b' stays 7. For G you might choose {60, 10}.
The resulting curve should have all the same algebraic properties as secp256k1 (except for being discrete log insecure due to being so small). To check your math, G * 29 = {37, 10}. Meaning that the pubkey for private key 29 is the point at {37, 10} with the above parameters.


text:
Modifying data in existing blocks
NOTE: I am a Bitcoin newbie. Please excuse (and correct) any wrong terminology in this post.
Can the transaction data in an earlier block be edited? Of course, it would break the verification of the Proof-of-Work because data will not match the final block digest. However, wouldn't the original data be lost, and the link to later blocks in the chain be broken? i.e. Anybody can figure out that the block has been messed with. However, how would the correct data be retrieved?
My guess is that there are multiple copies of the blockchain. Even if the data in a block in one copy of the blockchain is corrupted, other copies of the "true" blockchain will still be "out there" and will be accepted because they would be longer (have greater difficulty score) than the broken copy.
Is that correct?

related: Can someone explain how the Bitcoin Blockchain works?

Yes, your understanding is correct.  In fact, not only are there multiple copies, there are a huge number of copies: everyone who runs a full node has a complete and validated copy of the entire block chain, which they will share with anybody over the Bitcoin peer-to-peer network on request.
In fact, if your hypothetical attacker starts sending out their corrupted block, most users won't even notice: their software will validate it, notice it's incorrect, figure there is just something wrong with the attacker's data, and request it from some other node instead.

It is possible, but very very hard. If someone has mined a block, you basically have to mine your version of it, which will take a while. You will then gave to fight against the clock as the other miners try to mine another block.
If a block is mined, all the blocks before it are basically encrypted again. To modify a block, you will have to remine it and everything after it.
Will it be possible to attack the blockchain by creating a broken block?
No. The bitcoin protocol will not accept it. If you somehow configure your node to accept it, you'll have to get the other nodes to accept it too.

I am not talking about the case where miner X wants to insert wrong information into the block chain and have it considered valid. I am talking about the data in some block (not necessarily the last) in the blockchain being modified by someone. This block will now not be valid because the hash of the data will not match the block ID and its link to all later blocks in the chain will be broken. i.e. Miner X does not want their modified data to be considered valid and accepted into the blockchain. Miner X only wants to mess up the blockchain.

Oh, I see what you mean. This is impossible, as since the block will be invalid. The bitcoin protocol automatically rejects blocks like this.


text:
Running bitcoin-cli commands without hosting a node
I want to run bitcoin-cli commands (or JSON API requests) to see example response output in the format as given on https://bitcoin.org/en/developer-reference#bitcoin-core-apis without running bitcoind locally. I do not want to have to download the entire blockchain.
For example, I want to see the output of commands like gettransaction or getblock for transactions and blocks on the main Bitcoin blockchain. Aren't there any publicly available servers that would return responses in the format as specified in Bitcoin Core API? The other blockchain explorers like blockchain.info or blockexplorer.com appear to be returning a response in their own JSON format (i.e. document structure) with different field names and object hierarchy.
I spent quite some time looking for some such service but could not find any helpful information online.

This isn't exactly what you asked, but it's close.
Take a look at https://chainquery.com/bitcoin-api you can try different JSON-RPC commands through your browser.

That seems to be exactly what I wanted. Any reason that you are saying it's not? Thanks.


text:
How do bandwidth requirements for running a full node grow with blocksize?
I know they increase.
I'm looking for something more precise than that.

The maximum bandwidth requirements for blocks previously (there is other traffic overhead including for transaction broadcasts if your node participates, the other traffic is variable depending on many factors mostly around network utilization) were ~1MB block size per ~10 minutes.
Now the max bandwidth for blocks is ~4MB block weight per ~10 minutes.
There is some information for current block size here.

So is the relationship basically linear?


text:
Clarification about lightning network
When I run a lightning node, I have to set up a lightning channel with, for example, a highly connected node.
Here a first question: When I set up a lightning channel with a node, have I need to put some bitcoins in it?
Then, if I wanted to buy something using lightning network (for example, a sticker from Blockstream), will I have to open another lightning channel with Blockcstream? Or the previously synced channel will be used to let me buy from Blockstream?
Thank you.

When I set up a lightning channel with a node, have I need to put some bitcoins in it?

Generally, yes. The person who initiates the channel creation process (i.e. the person that says "I want to open a channel with you") is the one who funds the channel.

Then, if I wanted to buy something using lightning network (for example, a sticker from Blockstream), will I have to open another lightning channel with Blockcstream? Or the previously synced channel will be used to let me buy from Blockstream?

Not necessarily. If your channels are connected to other nodes who have channels with other nodes and eventually a channel with the merchant (which is likely the case), then you do not need to open any new channels. You can make your payment route through the Lightning Network and it will reach the merchant.

Thank you very much, you have been really clear.
Excuse me, for another question... Can one choose from which lightning node pass to do a payment to some other node?

Theoretically, yes. However I'm not sure that that is actually implemented in current software.

Yes, the low level API which allows you to specify exactly which route to use is exposed. You can use the getroute and sendpay commands to control what happens.

When I set up a lightning channel with a node, have I need to put some
  bitcoins in it?
  Yes, you always need to put some BTC, even if the other side want to puts the BTC for you, then that way you cant pay!, you will only be able to receive. To pay you need to put some of your on-chain money in the off-chain contract (LN channel) so that money act as a temporal pool to get from your money in the pool and pay via LN in a fast way!

think the channel as a bag with your money, you must put money in the bag if you later want to pay from there, and you must have room/place in the bag to receive a payment, if not the coins cant keep there
nowadays channels and one side funded, and the initiator is who funds the channel, in the future full-duplex dual funded will be initiated, where both put BTC and it will be send/receive capable.
anyway there are other techniques today to reverse a channel and be able to receive.

Then, if I wanted to buy something using lightning network (for
  example, a sticker from Blockstream), will I have to open another
  lightning channel with Blockcstream? Or the previously synced channel
  will be used to let me buy from Blockstream?

your previously opened (not synced) channel if its connected to a node through which a route to destiny (Blockstream) could be found! will able you to pay, without opening a channel.
if you have to open a channel with everyone you want to pay to. i will be the same as pay with normal BTC, as opening a channel is an on-chain operation. it will only make sense to do repeated payments to the same person, the LN is a lot more useful than that, its great!
think the LN network (when you have a node with good channels opened) as your real life wallet, its handy for small payments, you go and buy a candy so you open your real life pocket wallet and you pay! instantaneously, but you don't carry your hole life savings in your real life pocket wallet!
if you have to buy a house, you go to the bank, ask for opening the safe for you, show your credentials, and you take the money (its more secure but it takes more effort to do) the bank example could be an offline paper wallet of BTC in this example. which if you want to expend from, you have to import the private key in a node, pay and wait for the tx to be included in a block, and wait some more blocks (confirmations) to be safe!... a little more time consuming and impractical than LN don't you think? but.. definitively more secure! like the Safe in the Bank


text:
How does nSequence/Check Sequence Verify work?
How does relative timelock work? I mean, I know the theoretical description, but how to use nSequence concretely ? Can you do me a practical example with 2 sample transactions one of which locked with nSequence from another?

In order to use a relative time lock, you need to provide the requirements in the scriptPubKey to which the Bitcoin is sent.
Example
scriptPubKey for escrow with 30 day timeout:
IF
    2 <Alice's pubkey> <Bob's pubkey> <Escrow's pubkey> 3 CHECKMULTISIG
ELSE
    "30d" CHECKSEQUENCEVERIFY DROP
    <Alice's pubkey> CHECKSIG
ENDIF

Then, in order to spend it before 30 days, the scriptSig that satisfies the first conditional statement (multisig script) must be provided, i.e.:
scriptSig: 0 <signature1> <signature2>
Or after 30 days, alice can provide:
scriptSig: <signature>
See BIP112
Sequence
Note that in order to set a relative locktime: the tx must have the following properties:

version must be 2 or greater
nSequence must not have 32nd bit set
nSequence must have the 23rd bit set (0x400000) if it is a lock-time type, unset for block height type
for relative lock-time type the granularity of each bit is 512 seconds
for relative block height type each bit represents 1 block

For 30 days, I believe it would be as follows:
30 * 24 * 60 * 60 = 2592000 seconds
2592000 / 512 = 5062.5 ~= 5063 or 0x13C7
sequence = 0x13C7 | 0x400000 = 0x4013C7 or 4199367
nSequence = 0xC7134000 (little endian)

The sequence is the last 4 bytes of an input, see https://en.bitcoin.it/wiki/Transaction

Thank you, very clear. Do u know where to add nSequence parameter inside a transaction?

The sequence or locktime is the very last 4 bytes of the transaction, see https://en.bitcoin.it/wiki/Transaction

@JBaczuk - Has the impact of little endian encoding been taken into consideration after performing BIP 68 bit encoding?

@skaht right, you'd need to convert to little endian before putting it in the transaction

The nSequence field is not the same as the nLockTime field.  The nSequence field is per-input, and inputs can have different values set.  See General format (inside a block) of each input of a transaction - Txin in the bitcoin wiki link.

Right, thanks I was mixing the two terms, I'll try to clarify

nSequence is at the TX input level. Was referring to each TX output CSV opcode locktime needing to be BIP 68 encoded and converted to little endian format. nLockTime is associated with absolute time locks.

TX version number must be set to 2 or greater per https://github.com/bitcoin/bips/blob/master/bip-0112.mediawiki#summary.

I am still having problems understanding the relative locktime:
I am aware that the scriptpubkey is "Time Locked" as mentioned above :
   "30d" CHECKSEQUENCEVERIFY DROP
    <Alice's pubkey> CHECKSIG

So when I want to spend this output, do I actually have to set the nSequence Field by myself. I mean, what prevents me from just calculating the right values which satisfies the OP_Code. I am missing the actual connection to the real transaction, like which procedure checks that this transaction has really been 30 days in the blockchain since it appeared in a block.
To prevent older nodes from forking of, the final nSequence should also be calculated into a resulting locktime, to prevent older nodes form spending it?

What's crucial to understand is that the redeem script (the script that you quoted here) that is present must match the script hash in the UTXO. The spender does not control the script.
So the spend dictates the value in CSV(value). And CSV(value) WILL fail if value is less than the nSequence in your input which is trying to spend the UTXO (as specified in BIP-068). So BIP-068 sets a way for inputs to be valid only a relative amount of time, while BIP-112 with CSV makes the unlock script writer able to assert a minimum relative amount of time for the input.

I still have a problem understanding the order of transactions. Here's an example:
//Blockheight(100000):
{
    nVersion: 00000001
    vin:[
        {
            prev_out_0:
            {
                txid: <placeholder(a1b2c3d4e5f6)>
                index: 00000000

                scriptSig:
                <placeholder(a1b2c3d4e5f6)>

                sequence: 0000186A0 //100000
            }
        }
        {
            prev_out_1:
            {
                txid: <placeholder(a1b2c3d4e5f6)>
                index: 00000001

                scriptSig:
                <placeholder(a1b2c3d4e5f6)>

                sequence: 0000186A0 //100000
            }
        }
    ]
    vout:[
        {
            value: 1234 satoshis

            lockingScript:
            3 OP_CHECKSEQUENCEVERIFY OP_DROP OP_DUP OP_HASH160 <RIPE160Recipent(<placeholder(a1b2c3d4e5f6)>)> OP_EQUALVERIFY OP_CHECKSIG
        }
    ]
    nLockTime: 00000000
}

//Blockheight(100001):
//Redeem-Transaction should fail -> sequence: 0000186A0=100000 + 3 in redeemScript = 100003
//100003 != 100001

//Blockheight(100003):
{
    nVersion: 00000001
    vin:[
        {
            prev_out_0:
            {
                txid: <placeholder(a1b2c3d4e5f6)>
                index: 00000000

                scriptSig:
                <placeholder(a1b2c3d4e5f6)>(redeemScript of prev tx)

                sequence: ffffffff
            }
        }
    ]
    vout:[
        {
            value: 1234 satoshis

            scriptPubKey:
            OP_DUP OP_HASH160 OP_PUSHBYTES_20 <placeholder(a1b2c3d4e5f6)> OP_EQUALVERIFY OP_CHECKSIG
        }
    ]
    nLockTime: 00000000
}

why is this principal not working?

Hey a_confused_one, to ask a new question, please create a new topic by clicking the "Ask Question" button in the top right.


text:
Transaction with expiration time
Is it possible to give an expiration time to a Bitcoin transaction so that after a definite time, it can no longer be mined?

No, bitcoin transactions that stop being valid after a certain point in time are not possible

Out of curiosity, are there proposed opcodes such as OP_PUSHTXDATA from Johnson Lan which allow for an expiration mechanism? There is no timestamp on the transaction, so specifically OP_PUSHTXDATA wouldn't allow to construct an expiration mechanism. Instead, this hypothetical op_code that would enable expiration would need the ability to push the header height to the stack ... anything such proposals so far?


text:
Lightning network: funds into channels
Is there a minimum limit of bitcoin that can be added into a channel during the initialization?
And, if I decided to open a channel with a lightning node, also that node has to add money to the channel?

Is there a minimum limit of bitcoin that can be added into a channel
  during the initialization?

According to the Lightning Network Specifications:
"The amounts for each output MUST be rounded down to whole satoshis. If this amount, minus the fees for the HTLC transaction, is less than the dust_limit_satoshis set by the owner of the commitment transaction, the output MUST NOT be produced (thus the funds add to fees)."
So, the commitment must be greater than the sum of the transaction fee (determined by miners at the time of broadcast) and the dust_limit_satoshis value. The dust limit purpose is "to prevent creation of uneconomic outputs (which would otherwise remain forever, unspent on the blockchain." - BOLT #5

And, if I decided to open a channel with a lightning node, also that
  node has to add money to the channel?

From what I understand, this is not typical, but it depends on your agreement with that other node. "Initially they each hold a bitcoin transaction that sends all the bitcoin (e.g. 0.1 bitcoin) back to one party." Lightning RFC - Introductions. So, if the fundee needed to make a payment to the funder, it could provide a payment up front.

I believe that as of the current implementations of lnd, the default, tested and only way is to open a channel when only the initiate party funds the channel. That is to answer your second question. I’ll be happy to know if there any development with this issue.

Perhaps initialization is a special case, since there are no previous commitments that one can try to commit fraud with. For all subsequent cases (after the counterparty has more than 1% of the funds), there are more things to consider: https://bitcoin.stackexchange.com/questions/80731/minimum-funds-required-in-a-channel-in-lightning/80786#80786


text:
Send data to bitcoin blockchain
Is it possible to send a transaction containing hashed values in the body of it to no one? I explain better. I would like to store data on bitcoin and I would need to send a transaction containing this value but not to any specific address. I could i do it?

Related: How do I upload a file to a testnet blockchain. The process is similar.

You are free to design your scriptPubKey for the Output Transaction as you wish. So just a OP_RETURN makes it unspendable.

Using Bitcoin for data storage is not recommended. However, the cheapest way to do so is by committing data into a custom P2WSH PUSHDATA script and spending it. When you spend this P2WSH output, script bytedata is declared in witness data. Since witness scripts are subject to a consensus limit of 10,000 bytes and a standardness limit of 3600 bytes, the ideal max script construction for storing 3574-bytes should be:
<514-bytes> <510-bytes> <510-bytes> <510-bytes> <510-bytes> <510-bytes> <510-bytes> OP_2DROP OP_2DROP OP_2DROP OP_DROP OP_1

This construction compiles to a witness script of 3600-bytes. With a %75 discount in witness data, you end up paying for 900 vBytes to store 3574-bytes.

It's storing data on bitcoin blockchain is not a good practice but is possible to create a transaction with a special script.
The transaction name is Transaction null data, a little introduction on this type of the transaction is here


text:
Reference an UTXO of a transaction that has not been yet mined
How to reference an UTXO that has not been yet mined? I want to prepare a transaction and, before spreading it, use its UTXO as input for another relative timelocked transaction. Then, spread the first prepared transaction.
How to do it?

The UTXO is referenced as an outpoint(TXID, Index) in the input of your time-locked spending transaction.
So, when creating your time-locked transaction, you need to know the TXID of the (unconfirmed) transaction you are spending.
Simply double+sha256 and swap endianness of the over-the-wire transaction serialisation to get the TXID you wish to reference.
This TXID is a unique identifier (assuming no TX malleability). The outpoint you are referencing in your spending transaction is not affected by the confirmation of said UTXO.

Thank you. So, with "Simply double+sha256 and swap endianness of the over-the-wire transaction serialisation to get the TXID you wish to reference." you mean that in this way I can find TXID before spreading transaction over the network? And with it I can create the timelocked transaction. Right?

Exactly :) you can always chain tx together this way. As long as the immediate parent is confirmed, the subsequent tx will be accepted in mempool

Worth keeping in mind: Unless all inputs to the original transaction are segwit and at least one is sighash all, the original transaction will be vulnerable to third party malleability so your second spend could get invalidated.

This seems to be more of an improvement suggestion to James answer than an answer to the asker's question. Please be sure to address the asker's question if you post an answer post. When making suggestions to other answerers please use a comment.


text:
OP_HASH160 pops the public key from stack after hashing it?
This guide https://bitcoin.org/en/developer-guide#p2pkh-script-validation mentions
"The operation executed next, OP_HASH160, pushes onto the stack a hash of the data currently on top of it—in this case, Bob’s public key. This creates a hash of Bob’s public key."
Does the HASH160 operation pops the duplicated public key? If not, why keeping a duplication on the stack? what's the point?
Thanks.

Yes, every opcode that inspects an element on the stack also pops it (OP_SIZE being an exception).

OP_HASH160 pops an item from the stack (it can be a public key or any arbitrary array of bytes), hashes it and pushes the result to the stack

e.g. the script for a P2SH is:
OP_HASH160, P2SHAddress, OP_EQUAL

if whatever was on the stack, is hashed (OP_HASH160), the result of this operation is pushed back on the stack. Then the top two items on the stack are the result of the OP160 operation, and the P2SHAddress. These two are then compared.
A good explanation is online here in Andreas' book "Mastering Bitcoin": http://chimera.labs.oreilly.com/books/1234000001802/ch05.html#p2sh


text:
What is is minimum possible number for an ECDSA private key?
Private keys are 256 bit numbers. I know the max. possible number is something around:
115792089237316195423570985008687907852837564279074904382605163141518161494336
What about the min. number possible?
Thanks.

The all-zero bitstring doesn't have a corresponding public key per the standard (according to "Are all possible EC private keys valid?" on Crypto.SE), so it's 000…001.

One is the minimum number. [This space intentionally left unblank.]

"♫ One... is... the minimum number for a private key... ♫"

If only I'd thought of that to get around the minimum answer length. :)


text:
Why bitcoin protocol does not use JSON instead of low level data structures?
Wouldn't be easier for the nodes to just build the messages with JSON, then encode it to bytes so it can be transmitted over TCP/IP? I'm not talking about JSON-RPC, but the communication between nodes.

It would:

Use significantly more CPU to parse the incoming data (and running a node is already intensive, especially when processing an incoming block).
Use significantly more bandwidth.

It would not:

Remove the need for nodes to know about the binary format, as that is used for defining the (protocol-defined) hashes of transactions, blocks, and other structures.

So if you're going to need to implement the binary format anyway for hashing, why bother implementing another more expensive, less efficient layer on top, and incur the complexity of the conversion?

When it comes to bandwidth and CPU usage (for serializing/deserializing), JSON is a terrible format.  It literally passes a label with every single field, regardless of how often that field is repeated.  It also passes numbers (both floating point and integer) as strings, which again, wastes bandwidth.  This does not scale well at all.
JSON is designed to be used with flexible object schemas, where you don't know ahead of time which fields your data may or may not contain.  That's why all the labelling is required.  Since this isn't a problem that Bitcoin has, there is no real advantage to using a flexible data format.
It's a tradeoff between bandwidth/cpu versus flexibility, and Bitcoin data does not need the flexibility.


text:
If everybody stops paying transactions fees
What would happen if hypothetically, every bitcoin user decides in consensus with the rest of the world to stop paying transactions fees from now on. Miners will be forced to include transactions anyways in the blocks, because if they don't, bitcoin will become useless for most people, thus decreasing its value as a whole. The 25 BTC they would get from solving empty blocks will be close to zero in value.
So why miners can't be satisfied with just the coinbase earnings? no fees for users = more adoption = BTC value goes up.

25 BTC?   You're way behind, the reward is 12.5 BTC

So why miners can't be satisfied with just the coinbase earnings? no fees for users = more adoption = BTC value goes up.

First of all, transaction fees is used as a mechanism in bitcoin to deter spam. If transactions can be made without paying transaction fees, then there is no cost to the user to create spam transactions that will eventually overwhelm the network. So, the inclusion of transaction fees is a necessity for network health.
Secondly, it is not necessarily true that "no fees for users = more adoption = BTC value goes up". Paypal incurs zero fees for friend to friend transactions, does everyone own a Paypal account? Would onboarding many users that do not pay transaction fees cause Paypal shares to rise? Probably not.
Finally, a fee market for bitcoin transactions is a good thing as miners need to be compensated for the work they contribute to generate blocks. As block subsidy tends to zero, the proportion of mining revenue derived from transaction fees must rise or at least reach an equilibrium where the mining revenue is equal to the security cost of securing the bitcoin blockchain.

Bitcoin mining is becoming incredibly expensive in terms of hardware required. Fees are there to allow "common people" to become miners and earn something from it.
If everyone stopped paying transaction fees then a lot of miners wouldn't find it profitable anymore to mine, so they would stop.
The result?
Only rich and selected miners would have the possibility to mine, thus creating a centralized control system, defeating the entire puropse of bitcoin: being decentralized.

Are "common people" still mining in the first place?

Well by "common people" i meant someone who can afford to buy some decent ASIC but is so rich to own a mining farm

As mining prices grow and grow, if fees don't grow proportionally only a very rich and selected group of folks will be able to profit from mining, and they will begin to impose their own rules and guess what the first would be? Higher fees.

Miners will continue to mine, and they will get only the reward for mined block, right now it's 12.5BTC.
Take this mined block for example
https://blockchain.info/block/0000000000000000012cff88e530b319ef7fe7c795c78f2cfbd5e7ab487cfccd
Total transaction fees are 3.14 BTC (~25% of 12.5), I think even without the fees the miners will profit.
But there is problem for users, right now miners pick transactions to include in the block based on the fees, the higher the fee the better for the miner, with high fee you can get your payment confirmed in the next block, with 0 fee your payment can be left waiting for 2-3 weeks and declined.

So if everybody stops paying transactions, being selective won't be an option anymore.


text:
How to secure new public proof of work blockchain?
I am fairly new to the bitcoin and blockchain technology and have recently started reading about it. So my understanding and the question bellow may not be very accurate.
As I have understood so far, proof of work is the basic building block for a bitcoin block chain and because of it, an attacker will have to produce more than 50% of the total compute power (i.e control more than 50% of the nodes) in order to manipulate the block chain by being able to produce longest block chain consistently.
Now bitcoin guys were bit lucky as they were the first and nobody paid attention in there early days. Once bitcoin gathered momentum, number of honest nodes become predominant and system became inherently secure.
But now, how someone can start a new public blockchain (for completely different application) safely ? Because, if a new blockchain is floated with few mining nodes, any attacker can come with more compute nodes and hijack the blockchain as there are small number of honest nodes.

how someone can start a new public blockchain

This is impossible to secure PoW blockchain without "work". No work by honest nodes - no security. Point.

Thanks amaclin ! Just to understand more, even if honest nodes are doing 'work', they can be outnumbered by a sufficiently large group of dishonest nodes in nascent stage of public PoW blockchain application. How to overcome this ? If it is impossible, then how to bootstrap entirely new public system based on PoW blockchain avoiding above scenario ?

if I may add two lines :-) Generally, @amacline described it very well. I think it is also a question of value. If you have only 1.000 Euros in your blockchain, who will invest in creating a 51% attack? But if the value gets bigger, do the math! Starting a new PoW blockchain can be done in a way, that you created enough blocks at the beginning (so you invested computing power), to raise the difficulty high enough, so that PoW requires a corresponding (high) investment. Not sure if it is even thinkable, to manually set difficulty to a high level at the very beginning.