How can I use multi signature addresses with Bitcoin Core? Using the instructions on the debug window, I created a multi signature address as below:

addmultisigaddress 2 "[\"Address1\",\"Address2\"]"

MultiSigAddress

My understanding is that one needs the private keys of Addres1 and Addres2 to be able to spend from MultiSigAddress. Is this correct?

I sent some btc to MultiSigAddress, both Adress1 and Adress2 belong to me and I can go to coin control panel select MultiSigAddress as input. It will send the transaction without any problems.

What if one of the addresses belonged to someone else? How could I use the funds on MultiSigAddress using Bitcoin Core in that case?

Thirdly, the address I created in this case is 2 out of 2. What if I wanted to create an address that is 2 out of 3? How can I create that using Bitcoin Core? Or is that only possible for multi-sig transactions?

My understanding is that one needs the private keys of Adres1 and Adres2 to be able to spend from MultiSigAddress. Is this correct?

Yes that is correct

What if one of the addresses belonged to someone else? How could I use the funds on MultiSigAddres using Bitcoin Core in that case?

You will need the private key for both addresses (public keys) in order to redeem funds from the multisig address.  So you will either need to have the owner of the other address sign the the redeeming transaction or have them give you the private key so you can sign it.

Thirdly, the address I created in this case is 2 out of 2. What if I wanted to create an address that is 2 out of 3? How can I create that using Bitcoin Core? Or is that only possible for multi-sig transactions?

The following bitcoin core command will create a 2-of-3 multisig address,

createmultisig 2 '["key1","key2","key3"]'

You can view the full list of commands here


Solving block with number current number of transactions I'm trying to analize getblocktemplate that is returned by Bitcoin Core. If I'm not wrong that data that is returned contain all required data that I need to start mining. But what about the list of transactions? Even if block is currently mining, number of transaction still grows so for that same block if I again execute getblocktemplate I will receive extended list of transaction so that should change Merkel Chain and AFAIK it's used for building new block hash. So in that case how it is possible to solve a block?

As a miner, you get to choose which transactions you include in a block. Ideally, you would choose the set of transactions which maximises your incoming transaction fees, but you may choose any set of transactions you like (including none).


Does the OS make a difference for mining? I would like to know whether it makes a difference to mine on Windows, on macOS or on Linux?

Performancewise?
Is there a big difference in the quantity of software tools available to mine?
Are graphics card drivers equally available for all those OS?

The major difference that you would face is the graphic driver support.
That kind of influences the performance as well. Windows is best suited that way because of extensive driver support for almost all graphic cards out there.

From mining software perspective, almost all the matured softwares are comptabile on the major platforms you mentioned.


64: non-mandatory-script-verify-flag while broadcasting P2WPKH Bech32 with specific inputs Note: This happens with specific input, even though I've used the same
  code for other inputs and it works.

I have created a raw transaction using the following unspent:

Array
(
    [0] => Array
        (
            [txid] => 108544730bfaeccca0de66eda8546a33403899fb508bee582f1d9e1628ec0695
            [vout] => 1
            [scriptPubKey] => 0014194eef88d8428a4af66177779d0844d66d743e5d
            [amount] => 0.000560
            [address] => tb1qr98wlzxcg29y4anpwame6zzy6ekhg0jadfmrgr
            [redeemScript] =>
        ) // this i'm not able to spend.

    [1] => Array
        (
            [txid] => 5bda1b65ff7cb3c80f09f797debb2bf1749d22332e984ba6377a0c7cac30aed9
            [vout] => 0
            [scriptPubKey] => 00141f09edebd56ffadd0c1834d048c8a416d5418f68
            [amount] => 0.100000
            [address] => tb1qruy7m674dlad6rqcxngy3j9yzm25rrmgm9x3d5
            [redeemScript] =>
        )

)

https://testnet.blockchain.info/tx/108544730bfaeccca0de66eda8546a33403899fb508bee582f1d9e1628ec0695

Created Transaction Hex:

02000000029506ec28169e1d2f58ee8b50fb993840336a54a8ed66dea0ccecfa0b734485100100000000ffffffffd9ae30ac7c0c7a37a64b982e33229d74f12bbbde97f7090fc8b37cff651bda5b0000000000ffffffff02404b4c0000000000160014943a52d24537d96360fb533fdc7183a92963f9c7e8c54c0000000000160014f41ddffe9582cdf5841b332f8f3751f8c1514dd300000000

SignrawTransaction Response:

Array
(
    [hex] => 020000000001029506ec28169e1d2f58ee8b50fb993840336a54a8ed66dea0ccecfa0b734485100100000000ffffffffd9ae30ac7c0c7a37a64b982e33229d74f12bbbde97f7090fc8b37cff651bda5b0000000000ffffffff02404b4c0000000000160014943a52d24537d96360fb533fdc7183a92963f9c7e8c54c0000000000160014f41ddffe9582cdf5841b332f8f3751f8c1514dd302473044022042cb0cd01181cb2ec915bd5d981dbb197d2febb8acfbeae3c653747c8cf2b4b8022001e4ee55c7daa7197b4cd0948f4fb49b7660ecedb96e08e2220422e6485a0591012102b4592cc61c94b91c866ea6201885ce41f0f9cbc4a762c614799dfb854b6e18d50247304402204b475a5a61184aa46d1db9e22797c3084d409fffe608ceedaf3b6af7e2a9c2a002206404b55c0ba8b902d4bd48db115dd7d10befdc3cab57fdb42e2631e31c35070801210387844ba61f400e181004900f1ec59a3b310e4afd9a22d51cc8bc1a6631c057f500000000
    [complete] => 1
)

Sendrawtrasnaction response: 64: non-mandatory-script-verify-flag (Signature must be zero for failed CHECK(MULTI)SIG operation)

First of all, these are not P2SH-P2WPKH, these are normal P2WPKH outputs. They are not related to P2SH at all.

The problem here is probably that the amount is incorrect. If you are providing the previous output data yourself, then the amounts is incorrect. You have it as 0.000560 but the actual amount is 0.00055999. Since Segwit commits to the amount in the signature, having the wrong amount means that the signature signrawtransaction creates will be invalid which thus results in this error.


Any statistics on usage of Bitcoins by region or country? I would like to know if there are any statistics on turnover of Bitcoins for each country in the world. A very rough way would be to get a statistic on which traffic to Bitcoin.org by country.

WebGL Globe shows bitcoin nodes seen during last 48 hours. Install Chrome Web browser if you have problem rendering WebGL.

Google Trends has countries, cities and languages sorted by number of bitcoin related search queries.


Lost private keys. Help to recover I have blockchain wallet but have lost the private keys of it, is tr any way to restore my private keys. Plz help

No, by design, there is no way for you or anyone to access your bitcoins without the private keys.

Unless you can find the keys somehow, you are out of luck. Sorry.


Ruby: How do I create a wallet and import an electrum seed using money-tree gem I am looking for a way to use HD wallets with ruby. This is what I have found: https://github.com/GemHQ/money-tree. However I am having trouble generating a wallet and getting the seed to reload it in the program though that. I would like to be able to create many addresses in this wallet. I am also looking for a way to load my electrum wallet using the ruby money-tree gem, or any other you happen to know of.

How would I do this?

Create a new wallet in Electrum.  Copy the 'Master Public Key' and pass it to the money-tree gem like this:

require 'money-tree'

@node = MoneyTree::Node.from_bip32("YOUR_MASTER_PUBLIC_KEY")

i = 0
20.times do
  @child = @node.node_for_path "m/0/#{i}"
  puts @child.to_address
  i+= 1
end

This will give you the first 20 child nodes of the first child of the master public key.  These addresses should be the same as your "Receiving" addresses in your Electrum wallet.


Background information on warning, when closing wallet in pruned mode What are the implications and reasons behind this warning on gui popup, when closing the wallet:

  "bitcoin closing the wallet for too long can result in having to
  resync the entire chain if pruning is enabled"

A pruned node will always catch up, whats the hassle?

If you have a wallet that isn’t opened for the period of pruning, it won’t be able to scan transactions. If you set the limit to 2GB, and 4GB of blocks pass without opening the wallet, it may miss incoming transactions as the required blocks will have been deleted.


Can I download the blockchain blocks from torrent and paste them? Currently my Bitcoin Core client was stopped syncing at 40.73%.  It was not progressing any more.  I've downloaded the Blockchain from https://getbitcoinblockchain.com/ .  Can I just copy these blocks and paste these downloaded blocks to my Bitcoin > Blocks ?  Will everything be fine ?  Will the Bitcoin Core client accepts the downloaded blockchain ?

Yes you can download the blockchain from other sources then paste it inside the your main bitcoin folder.
You will need two folders:
- blocks
- chainstate
Then open bitcoin-qt for synchronization.


How does a new node get all the previous blocks in a blockchain? From what I understand, when a new full node is started, it begins by fetching all the previous blocks in the blockchain from it's peers.

I want to know how exactly it does that? Does it ask for a local copy of the blockchain from other peers and save it? In case multiple peers have different chains, how does it resolve?

The Bitcoin.org Developer Guide has a section about Initial Block Download (IBD) that goes into detail.

The basic principle in modern Bitcoin Core nodes is that the node connects to eight peers, tells them that it knows about the hardcoded Genesis Block (first block), and asks for the headers of subsequent blocks.  Headers are only 80 bytes per block (about 4.2 MB per year of blocks), so it doesn't take a lot of data for a node to get all of the headers up until the present.

Each header contains enough data for the node to see how much Proof-of-Work is contained in the corresponding block, allowing the node to select the block (headers) chain with the most cumulative proof of work.

Now that the node knows which chain has the most proof of work, the node requests each of its peers start sending it blocks from that chain.  Blocks are requested in order* from the earliest blocks to the latest.  If any block on the chain with the most proof of work is found to be invalid, that block and any blocks that descend from that block are considered invalid.  The node will poll its peers again, if necessary, and find which other block (headers) chain has the most PoW.  It will then begin downloading those blocks.

It continues to download blocks from its peers, validating each one, until it has all the blocks on the valid block chain with the most PoW.

* Modern Bitcoin Core nodes will receive blocks out of order, storing later blocks temporarily until earlier blocks are received in order to allow receiving blocks from multiple peers simultaneously.  Still, because most later blocks depend on data added to earlier blocks, some key parts of block validation can only be done in series.


What bad things could happens if Bitcoind RPC is public? It is always suggested to enforce authentication on Bitcoind RPC. However, in case the RPC authentication get compromised (or if it is public), what kind of bad things could happens?

First I could think of money lost

First wallets are exposed and all the private key will get exposed, and it essentially mean all your Bitcoins can get stolen

Second with setTxFee function, any transaction created using the node will either has insufficient fee or just too much fee

Apart from money lost, is there any other things that may potential happens?

For example, if I just run the node as a block tracker and monitor if any money sent into my address. Does RPC has the ability to affect them as well?

Recently ELectrum had that bug, First of all, if your wallet were not encrypted you will lose your funds and that is the most dangerous thing might happen.

If safe mode is enabled disablesafemode=1 You will avoid any danger RPC Calls.

  Safe mode is a feature that disables a subset of RPC calls - mostly
  related to the wallet and sending.

If you want to make your server public, Enable safe mode and disable wallet access.


What is the technical difference between BTC and LN wallets? What is the technical difference between BTC and LN wallets? Are they generated via a diferrent algorithm or format?

A Bitcoin wallet mainly maintains your private keys and keeps track of the transactions associated to the corresponding public keys or the addresses. The Bitcoin wallet will also help you broadcast your signed transactions.

A lightning wallet does all the same but additionally it follows the lightning network protocol meaning it helps you set up Revocable sequence maturity contracts which are used to construct a payment channel. They are created by a sequence of signed but not broadcasted transactions and revocation keys. The hashed time lock contracts wish are used for routing are maintained in a similar way. All of this is the so called channel state and stored privately in a database of your computer. This state is needed in addition to your private keys to access your funds.


Harvesting transaction fees So let's assume I don't care about energy consumption and mining the famous reward for discovered block. Is it possible to set up a workstation optimized to harvest just the transaction fees? Do I need to participate in a pool and run mining software?

No, it doesn't work like that.  The fee for a transaction can only be collected by a miner who creates a block including the transaction.  Creating a block also entitles a miner to collect the "famous" block reward (they could decline to collect it, but that would be stupid).  There is no easier way to collect transaction fees; you have to mine like any other miner (either solo or in a pool), and at least for Bitcoin, you can't economically do that with ordinary computer workstations.


Copay wallet transaction history unavailable? Ever since updating my Copay wallet to the newest version to resolve the vulnerability issue, it won’t show my transaction history. Recent transactions will show on the main screen for about 30 minutes, but if I try to open them up to view the details I get an error message. This is especially frustrating since I should have a little more BTC sitting in my wallet than I actually do, but I can’t see where the funds may have gone since the transaction history won’t load. All it shows is an error message saying “Could not update transaction history”. Help?
Using iPhone 6, iOS 11.4.1, copay for iOS v5.4.0
Thank you!

Top search result on Google says

  Refresh the transaction cache

  Select your wallet > Tap on the icon in the upper right corner of the screen > Choose "Transaction History" > Choose "Clear Cache" to reset your transaction list.
  Note: Your wallet will say 'Updating Wallet' until the list has been retrieved.

  Refresh the server's cache.

  Select your wallet > Tap on the icon in the upper right corner of the screen > Go to "Wallet Addresses" > Choose Scan addresses for funds
  Note: Your wallet will say 'Scanning Funds' until the addresses have been scanned.

  Please do not uninstall the app or delete the wallet if you did not back it up properly, in such case, please do so. The wallet backup is the only way to recover your wallet.

Maybe that helps?


How to determine valid vanity address prefixes for any starting net byte? Question inspired by this.

There are some combinations letters that will never produce a valid vanity address prefix for various network bytes. For example, for net byte of 52 (Namecoin), one cannot create addresses starting with

Na, Nb, Nc, Nd, Ne, Nf, Ng, Nh, Ni, Nj, Nk, Nm, Nn, No, Np, Nq, Nr, Ns, Nt, Nu, Nv, Nw, Nx, Ny, Nz, NL, NM, NN, NP, NQ, NR, NS, NT, NU, NV, NW, NX, NY, NZ

Given websites like Vanity Pool that outsource vanity address creation, creating a blacklist of address prefixes for every net byte would be a complicated task. How can one determine a valid range of address prefixes that can be created with any given net byte?

Casascius' Bitcoin Address Utility includes a Base58 calculator. You can input into it the lowest and highest values to encode to obtain the lowest and highest strings.

For example, to get the lowest Namecoin address, start with the hex representation of its network byte 52, which is 34, and add 40 zeroes (representing the 160 bits of the public key hash in hex). The result is MvaNCeVyvP6ZXYFWGpKaDX9ujEQ418F7sm. Likewise, to get the highest string use 34 followed by 40 f's, giving NKuyBkoGdZZSLyPbJEetheRhMjezbtjJCf.

Only 34-character strings which are between these two, in lexicographic ordering, can be valid Namecoin addresses. The ordering of the characters is compatible with ASCII, 123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz, and thus most programming environments should be able to check the address with the built-in string comparison functions.

Specifically, the first 2 characters can only be one of the combinations between Mv and NK, which are Mv, Mw, Mx, My, Mz, N1, N2, N3, N4, N5, N6, N7, N8, N9, NA, NB, NC, ND, NE, NF, NG, NH, NJ and NK.

A more general approach is to decode the address into a number, and verify that the result is composed of the required version byte followed by any n bits (where n is the bit length of the encoded data, 160 in the case of a receiving address).


What does the is_your_order field mean in a btc-e response? Their amazing API documentation (https://btc-e.com/api/documentation) shows a field called is_your_order. Not sure what it means and they certainly don't explain it.

Does anyone know?

The field indicates that the order is yours with a value of 1. With a 0, it indicates it is not an order made by you.

It's indeed nowhere documented, the only valid arguments for my explanation are the name of the variable and the fact that I can only find 0 or 1 values for it.

(I found this piece of code where they save the is_your_order field as a boolean, testing of the value ==1.)


Create wallet address on user registration for trading platform I am creating a crypto-trading platform . I wanted to know how to create wallet address dynamically for all new registered user and also create new address for every transaction.

I am using bitcoind for bitcoin and will be doing RPC calls directly. Also let me know if there is any better way to do it.

The call you want is getnewaddress, which will generate a new Bitcoin address, add it to the current wallet, and return the address as the result of the call.

You can find documentation for the call here: https://bitcoincore.org/en/doc/0.16.0/rpc/wallet/getnewaddress/

If you were writing this in Python, it would look something like this:

from pyjsonrpc import ServiceProxy

bitcoin = ServiceProxy("http://127.0.0.1:8332")
bitcoin.username = 'testuser'
bitcoin.password = 'testpass'
print(bitcoin.getnewaddress())

You would then need to track the addresses generated and record them with your user accounts, monitoring transactions and crediting users as they come in.


relationship between inputs in single transaction I'm a student to learn about bitcoin.

i saw a lot of transactions from Blockchain.info for study, and some of transactions can not be understood.

why address '367f4YW...' pay to itself?

is it available to guess a relationship between '367f4YW...' and '15ozxv...'?

Why address '367f4YW...' pay to itself?

While reusing addresses is not recommended for various reasons (privacy, security, etc), there is nothing stopping someone from doing so. If you'd like to send the change of a transaction to the same address you used an input from, you can do so.

  is it available to guess a relationship between '367f4YW...' and '15ozxv...'?

In many cases, if there are multiple inputs, you could assume that they are all controlled by the same wallet.

However, that is not always true. For example, P2EP transactions are looking to break this assumption, so that it is harder to guess at the nature of each blockchain transaction (ownership of inputs, outputs, etc).

For bitcoin to work best, fungibility is important. Making transaction inputs/outputs harder to decode is an important part of maintaining fungibility!


Mining Primecoin with one server and no pool? Is it possible to mine with just one server (for learning about mining, not for making a living!) and one wallet?

I've configured a Ubuntu VPS on a server I had spare and run Primecoind. My primecoin.conf has a random RPC username and password that I generated but I haven't put server=1 in the configuration file. I'm not sure if I should/need to.

When viewing the information of the process running, I can see the following data:

Every 2.0s: primecoind listtransactions & primecoind getmininginfo

Thu Jul 11 22:43:27 2013
{
    "blocks" : 16149,
    "currentblocksize" : 1000,
    "currentblocktx" : 0,
    "errors" : "",
    "generate" : true,
    "genproclimit" : -1,
    "primespersec" : 7,
    "pooledtx" : 2,
    "testnet" : false
}
[
]

I'm confused by a couple of things.

Firstly, why does pooledtx fluxuate from 0 to 2 from time to time. Secondly, how would I now if I have successfully mined for the first time and if there was any balance at all?

I've got MultiBit setup on my Mac with a wallet ID available.

I'm just unsure on how it all fits together. Any pointers would be appreciated.

pooledtx is likely the number of transactions that are waiting to be confirmed by the next block. These transactions are broadcast to the network and the miners collect them to include them in a block. Since primecoin still has a really low amount of transactions and since your mining a reward transaction this will swing between 1 (just your reward transaction) and 2 (someone just made a transfer).

Since you have a fully fledged primecoin client on your system to be able to mine (primecoind) it will also generate new addresses on demand, and the balance will be credited to those addresses. with primecoind listtransactions you'll see which addresses received the mined amount. You can now use primecoin sendtoaddress <primecoinaddress> <amount> to send any amount to an external address, i.e. your multibit client.


How to know what kind of Multisignature address? I have a Multisignature bitcoin for example address [3QJmV3qfvL9SuYo34YihAf3sRCW3qSinyC]

how to know what kind of it?

according to wiki https://en.bitcoin.it/wiki/Multisignature I have know Multisignature have below.

1-of-2
2-of-2
2-of-3
2-of-3
3-of-5
2-of-2
2-of-3
2-of-3
4-of-6
2-of-2

how to know [3QJmV3qfvL9SuYo34YihAf3sRCW3qSinyC] belongs to which type?

You cannot know, to which type an address of "3QJ...inyC" belongs, unless you created it yourself, or had the underlying data. Such a "type 3" address can be a hash of any data :-)

Ok, to be more precise for multisig: the address is probably created out of a redeem script (e.g. for a 2-of-3 multisig: <2><3>). This redeem script is hashed, and as a hash is a one way function (as per today's knowledge), you cannot reverse it.

You might have the chance to see which msig addresses / pubkeys and number of required sigs are included, when the spending transaction has been mined. Then you see all details of the redeemscript in the sigscript.

The way it works is described here: https://github.com/bitcoin/bips/blob/master/bip-0016.mediawiki. Much more details can be find in chapter 5 of Andreas' book "Mastering Bitcon, 2nd edition".


MultiBit sends BTC to different adress then I wanted Bug report
  Operating System: Windows 7
  MultiBit Version: 0.5.15
  Steps to replicate the problem: send BTC to specific adress
Hello I have a problem with sending BTC, what happened to me was, that when I sent BTC to my btc-e account (I used the adress they gave me for deposits), I checked everything (the amount of BTC I wanted to send and the adress) and I hit send. Problem was, that it never arrived on the adress I wanted it to and I never got my account funded. I started dealing with btc-e support, but it had not gotten me anywhere so far. But while taking screenshots as proofs I came across my transaction history.

As you can see I only used this wallet to fund my btc-e account so I sent BTC to only one adress, which is always the same (1cU8kgoVBGMxafj9ynwYjNJJH3L3PsSw7) but in those two other transactions its sent to "1cU8kgoVBGMxafj9ynwYjNJJH3L3PsSw7" (146rSpmvzyvZ4BYWCCt9fnMRLfL527CKcW) and I dont really know what that means. Except for that this adress (1cU8kgoVBGMxafj9ynwYjNJJH3L3PsSw7) never got the BTC i sent, I looked into my btc-e history and I realized that I never even got the first transaction which had this("1cU8kgoVBGMxafj9ynwYjNJJH3L3PsSw7" (146rSpmvzyvZ4BYWCCt9fnMRLfL527CKcW)) as sent to. How can I get my BTC back? I didnt do any mistake and I dont know how is this possible.
With regards Poloch

I think you might have put a bitcoin address in the label field in the send screen that is different to the actual address. This would explain the screen shot.

Of course it is the bitcoin address that is used to send to regardless of the label.


How can I be sure that bitcoin mining software is not compromised? I have been interested of generating Bitcoins but how can I be sure that the software that is available for this is not somehow compromised?

My concern is that the software may have some backdoor (reverse shell or otherwise), but to what degree is this a valid concern? Are there any steps I can take to mitigate this risk?

cgminer / bfgminer are both open source, get it from the official repository and you can be fairly sure that some geek will have noticed if there's something suspicious! If you're talking about mining some altcoin with a custom hashing algorithm then you have a valid concern.


Internet of Money git download error I tried to download the pdf from the following repository but i get an error

https://github.com/merklebloom/IoMv1
Ive done the following:
$  git clone https://github.com/merklebloom/IoMv1.git
$  cd IoMv1/
$  make pdf

It fails to create the pdf.

And I get this error message:

  if [ ! -d "_build" ]; then \  mkdir _build; \     cp -R -L
  /etc/asciidoc/images _build; \    cp images/* _build; \   cp
  chapters/en/* _build; \   cp conf/* _build; \ fi; \

  export
  XML_CATALOG_FILES=/usr/share/xml/docbook/schema/dtd/catalog.xml; \ cd
  _build; \ a2x --format=pdf --conf-file=a2x.conf --fop --xsl-file=custom-docbook-styles.xsl -k --verbose master.asciidoc; \

  /bin/sh: 3: a2x: not found Makefile:65: recipe for target 'create_pdf'
  failed make: *** [create_pdf] Error 127

Same goes for creating any other file such as pdf, html, epub, kindle.

This isn't a problem with git.  The problem is that the program 'a2x' is not found.  Either you don't have it installed, or it can't be found in your path.


WebAPI to interact with bitcoin wallet I need to automatically send funds from my hotwallet to users on my website at various times when they do something on the site.

Later I will also need to be able to see total balance for an address receive data about address totals and funds etc. (for this I have ABR block explorer and API setup to read the blockchain for addresses)

I know there are all the commands that can be executed from the terminal or CMD when running bitcoind, but how to trigger these from my website? Do I need to write a webAPI to handle such requests direct against the network? or is it more common to make a call to run these commands via scripts direct against the bitcoind?

Any help appreciated

You actually have several options, but they all relate to what your hot wallet actually is, and how you want to interact with it.

For example, you could have bitcoind running on a different server, and allow it to accept RPC commands from your web server.  These commands could either be issued by calling the command line on your server, or by adding RPC support directly into your web application.

You could also skip using an "out of the box" wallet like bitcoind, and instead add wallet features directly into your web application using a library like NBitcoin (since it sounds like you are using .NET).  In this scenario, your web application would actually be your hot wallet, and you would only build out the wallet capabilities that you plan on using.

In either of these cases, however, I would advise you to keep wallet functionality off your public facing web server, and make sure that the server handling the actual signing of transactions and storage of private keys is only accessible from your web server (with proper authentication), and not the internet at large.  When bitcoin is involved, it's best to limit your attack surface.


What happens when there are no Bitcoins miners anymore So if I'm not wrong, the proof of work is the way to validate all the transactions in a Block. The miner gets (at the moment) 12,5 Bitcoins as a reward for each validated block.
So my question is:

what happens when almost all the bitcoins have been mined and there are no miners in the system? who's gonna be there to validate the transaction blocks? (21Milloin bitcoins is the limit, so there will be someday such a big proof of work to mine that it won't be worth it, I think everyone's gonna stop mining). will the system still be working as it is right now?

The reward for a miner when it finds a new block is already composed of the subsidy (currently 12.5 BTC) and sum of transaction fees that the miner included into the block. If you look at the blockchain right now, the minimum transaction fee sum of last 3 blocks was 0.5075 BTC. This means that much sooner than before last bitcoins are mined (i.e. reaching 21M cap) the part of the reward from transaction fees will be much greater than the subsidy itself.

After next halving, the subsidy will be 6.25 BTC, then 3.125 BTC, ... and after 7 halvings, the subsidy will be less than 0.1 BTC. And this is going to happen in cca 30 years (while the last bitcoins will be mined in more than 120 years). So much sooner than what you are referring to, the transaction fees will become major dominant part of the reward.

At any point of time, miners will only stop mining if that stop becoming profitable for them. So currently, the reward from a block is about 12.5-14 BTC, which translates roughly to $31k per mined block (at current difficult over 700G). So many different scenarios can play out in 30 years. For example, price per 1 bitcoin can raise from $2.4k to $50k. At that point, if subsidy is 0.1 BTC and sum of transaction fees are just 0.5 BTC, you've got 0.6 BTC total reward, which would translate to $30k. That might be enough if difficulty stays at 700G and prices of electricity stagnate as well, or of hardware mining chip technology advances and provides better cost per hash (very likely to happen), or it might not be enough if electricity cost or difficulty goes up a lot, ...

But every transaction in the ecosystem already has to pay a fee. That will become more and more important over time as the subsidy goes down. That does not mean the cost for end user will go up. It may temporarily, but new scaling solutions are coming and are promising to reduce the need for on-chain transactions for small payments.

Also, the blocks are going to be bigger, which means more transactions will be allowed to a single block, which could mean higher reward for miners from the fees.

So many different scenarios are possible, it is impossible to predict what exactly will happen, but the sole fact of lowering subsidy is not a big problem. To answer your final question - yes, the system still can work as it is now, even after 30 years, and even after all bitcoins are mined.


What happens to a transaction once generated? I'm trying to understand how bitcoin works technically. I understand the blockchain, digital signatures etc ... I'm more interested in what happens to a transaction once it's "created".

Suppose Bitcoin only contains one transaction per block (to simplify). Basically:

someone create a transaction using its wallet
this transaction must be validated (check inputs, digital signature etc ...
a proof of work must be computed on the block hash
the the block is added to the blockchain

So I know miners are responsible to come with the proof of work. My questions are:

how does one node broadcast a transaction to miners ? Is it part of the P2P protocol ?
does miner check the transaction (digital signature, available inputs etc ...) ?
does miner directly submit blocks to the blockchain ?

This part is still confusing to me any help pointers to article would be great :)

Update:

In a P2P network, nodes are not connected to every other nodes. So let's say the network looks like this:

node1 <-> node2 <-> node3 (1 and 2 are directly connected and 2 and 3 are directly connected. 1 and 3 are connected through 2)

When node1 wants to broadcast a transaction for validation, it will only broadcast it to node2. Then node2 can eventually broadcast it to node3 to give him the chance to validate node1's transaction.

But, because we are in an untrusted network, nothing prevent node2 to validate the transaction without never transmitting it to node3 and thus, keeping mining fees for himself.

We could also imagine that node1 never broadcast it's unconfirmed transaction, do the mining work himself and only broadcast the validated block so it get "merged" into the blockchain.

How does Bitcoin deal with this situation ?

Regarding your update:

It's true that when a node receives a transaction, there is nothing forcing them to relay it.  They can just sit on it if they want.

But the network won't look like the picture you drew.  If Node1 actually wants his transaction to be confirmed, he wants to distribute it to as many other nodes as possible.  In particular, if Node2 is the only miner that knows about the transaction, then it can't be confirmed until Node2 successfully mines a block.  Assuming that Node2 only controls some fraction of the network's total mining power, this may take a (very) long time.  Node1 would prefer for his transaction to be included in the next block to be miner, no matter who mines it.

So for that reason, Node1 won't send the transaction only to Node2, but to many different nodes.  Bitcoin Core, for instance, will by default try to connect to at least 8 different nodes. If at least a few of those nodes are honest, they will relay the transaction to many more nodes, and so on. This also means that Node2 has less incentive to be greedy; it only helps to be greedy if no other miners know about the transaction (or very few), and Node2 knows this is not likely to be the case.  On the other hand, if Node2 is a miner, then she has a slight incentive not to be greedy: having invested in Bitcoin mining equipment, Node2 has an interest in having Bitcoin keep a high value, which will only happen if people continue to use it, and having their transactions confirmed fast would tend to encourage that.  So at some point, the incentives fall on the side of not being greedy.

(Keep in mind, too, that not all nodes are miners.  Many nodes on the Bitcoin network are run by people who don't do any mining, and just run a full node for fun, or to support the network altruistically, or because they installed Bitcoin Core with default settings and don't really know or care what it's actually doing.)

As for your second scenario, if Node1 is a miner himself, he can certainly keep its own transactions to include in his own blocks, rather than transmitting them on the network.  This also means that he won't have to pay fees for that transaction (or, equivalently, that he pays the fees back to himself).  There are two tradeoffs: (1) as mentioned above, the transaction will take longer to be confirmed; (2) if there is a high volume of transactions on the network, enough to keep all blocks filled, then by including his own transaction in his block, Node2 is giving up the ability to include someone else's transaction which would pay him a fee.  So it's up to Node1 to decide what is best for him. But this has no impact on anyone else, so it isn't really a problem for the network either way.


Where can I store a Bitcoin Wallet Safely? I am a newbie and I would like to know where can I create/store my Bitcoin Wallet safely. I have downloaded the Bitcoin software but storing it in my local computer seem like a high risk, but also is trusting a third-party.

How do you guys do it?

Here is an in-depth article that explains the steps you should take to secure your wallet. https://en.bitcoin.it/wiki/Securing_your_wallet.


How to make a pay-to-rawmultisig transaction? Using the default client's RPC calls, can I make a transaction that sends to a RAW multisig (not P2SH multisig) scriptPubKey?

If I made a raw transaction, and edited the bytes in the scriptPubKey of one of the outputs, could I manually write in my own scriptPubKey? Hopefully, instead of doing this manually there is either support in the core client or there is a tool out there that I don't know of that can help.

No, Bitcoin Core doesn't have any RPC calls which allow you to create a bare multisig pubkey script.

Yes, you can create your own pubkey script and insert it into a transaction.  This isn't hard---but it is dangerous.  One mistype and your bitcoins are lost forever.  Note also that greater than 3-of-3 bare multisig pubkey scripts are non-standard, so they won't be relayed or mined by standard clients.

What might be challenging is spending the output at a later time---you will need a program that understands how to correctly sign Bitcoin transactions using an arbitrary private key.  Bitcoin Core can do that if it either has stored or is given all of the private keys necessary, but not all wallets can.


Trying to find the raw genesis transaction length I see that many different altcoins have different lengths for the initial genesis tx.  How would I go about finding the length of the initial genesis tx?  I saw another answer but I have no need of making it as complicated; I just need the length and nothing else.

For example, Bitcoin's is

01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000.

However, altcoins have different lengths.  Is there an identifier I can use to determine the length of the genesis tx and nothing else?

EDIT: I am making a block explorer so I cannot use a block explorer to help me in getting info.

Unfortunately, the genesis block is not indexed in most altcoins (because they forked from bitcoin and kept the same bug), so you can't really get access to it via the RPC methods.

What you could do instead:

Use a block explorer that will tell you the size of the transaction. For example, blockchain.info makes this information available (204 bytes).
Find the parameters file and put a print the size of the genesis block to stdout.

The second option basically entails putting the following lines at the end of CMainParams() and then compiling.

CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << genesis;
printf("block: %s\n", HexStr(ssBlock.begin(), ssBlock.end()).c_str());
printf("block size: %i\n", (int)::GetSerializeSize(genesis, SER_NETWORK, PROTOCOL_VERSION));
printf("tx size: %i\n", (int)::GetSerializeSize(genesis.vtx[0], SER_NETWORK, PROTOCOL_VERSION));

This will print the raw block data, it's size, and the transaction's size. (Note, this is untested, but something along these lines should work)

NOTE: It's possible, although not the norm, to put multiple transactions in a genesis block. Just check that your assumption is correct.


What does it means "get a new address and then make the Bitcoin offline" and make it extremely secure? I have been reading about Bitcoin, and one thing was about making Bitcoin extremely secure, which is to get a new address so that nobody knows, and then making it offline right away?
Is it like
0.01 Bitcoin    Address 123-456-789-876    encrypted by my public key

and then immediately change my address to something new, and then use the existing public key to encrypt it and publish it to the Ledger / Blockchain?
Should I get a new public / private key pair as well? The thing I don't understand is, don't I need to publish this new address to the Ledger?  If it is, then other people know too.  If I don't publish and other people don't know, then 1 year later, if I want to sell this 0.01 Bitcoin, how does the Ledger know it is a valid address?

Bitcoin wallets never contain money. The only important content is one secret number. This secret number is called a private-key. In most current wallets, the secret number is instead a seed from which a series of private keys are generated in a predictable (deterministic) way.
The only place you can find out how much money you control is in the public replicated journal of transactions called the blockchain. Every wallet has a copy or access to a nearby copy. Blockchain explorers let you search their copy.
You see how much money you have by making a list of the addresses* your wallet created and looking through the whole transaction journal for mentions of those addresses receiving or spending money and add up the amounts. Subtract the debits from the credits to calculate a balance.
The Bitcoin network doesn't encrypt any data.
You use a new receiving address for every transaction so that senders can't see what other money has passed through your address. For privacy.
You use offline wallets for security - a wallet on a computer that is connected to a network can potentially be hacked into. especially if it is a computer you also use for browsing web-pages and for downloading and playing games. An offline wallet in a computer that is never connected to a network is much safer.
All well-formed addresses are valid. They are just large numbers, all large numbers are valid (you may have to add a few checksum digits) but almost all of these large numbers will never be used because there are so many of them.
You don't have to publish addresses explicitly or separately, you just use them in transactions. Unlike street addresses, Bitcoin addresses do not identify people or locations - they are just a random-looking number without any special meaning. You don't have to claim ownership of an address. You can use mathematics to prove you know a secret number (private key) from which that address was derived. The proof doesn't disclose the secret number. The proof is what allows you to spend money, it doesn't matter who you are. The Bitcoin network doesn't keep accounts for people.
A Hierarchical Deterministic (HD) wallet creates new private and public key pairs as needed (usually a few in advance of need) from one master private key.
Your wallet will take care of all these details for you.

Related

Is each Bitcoin address unique?
What's stopping someone from taking over all the bitcoin addresses?
Can two private keys generate the same (public) Bitcoin address?
Can Bitcoins be duplicated if two private keys share the same public key?
Theory: brute-force key search


Why can't bitcoin miners modify transaction outputs? I am learning the Bitcoin protocol by reading the bitcoin developer reference documentation.

As far as I know, a raw transaction consists of:

Version (which is always 1)
Inputs. Each input contains:

Hash of the transaction that contains the output that we are going to spend here
Index of the output in that transaction
Script that satisfies the conditions placed in the script of the referenced ouput.

Outputs. Each output contains:

8 bytes for the value in satoshis
Script with the conditions that must be satisfied in order for this output to be spent.

Locktime (which is usually 0)

I am not very sure what the script of the inputs contain, but I guess it should contain the public key, and a signed message.

My question is, why can't the miner modify the scripts in the outputs (replacing the address by their own), if those scripts are not part of the message that the real user had to sign?

Or maybe this question would be better asked like this: What is signed in the input scripts?

What is signed in the input scripts?

Depends.

The case of a P2PKH spending transaction, the scriptSig (input script) for each input will contain a ECDSA signature and a byte which donates what exactly was signed called the SIGHASH flag. In almost all cases this is SIGHASH_ALL, which means that the signature covers the entirety of the transaction outputs and inputs, less other signatures. If the transaction output script is modified and any input has signed it with SIGHASH_ALL, that signature would be invalidated and the transaction can not be included in a block.

Other flags can have the effect you describe, if I make a transaction which only signs a single input with SIGHASH_NONE (this signature only covers the input), then anybody in the network is free to modify the outputs as much as they want before it gets buried in a block. Nobody uses it like that for exactly this reason.

There's two other flags available today SIGHASH_SINGLE and SIGHASH_ANYONECANPAY. The former allows you to sign only one of the outputs and ignores the rest (eg vin:1 signs only vout:1), however this is buggy and not at all intuitive. The latter allows you to make transactions where the inputs are a wildcard, spend this output to this script, and make up the deficit using whatever other inputs you want.

In general nobody uses SIGHASH flags, the majority of all transactions are strictly SIGHASH_ALL.

  I am not very sure what the script of the inputs contain, but I guess it should contain the public key, and a signed message.

This depends entirely on what type of output is being spent, but we'll assume it's a very typical Pay to Pubkey Hash (address) transaction. In this case the scriptSig is extremely simple.

304402204bc6ed9b0122fc145031d4d9f6a30fbb28b63d152e3848c785a65f1e0b97ea8d02205a99bc13ba9293526ed175947cb756c5e3fca0a98890b88551e3e6c4c0bb6f5601
04988b34239b2f1c2441db4d50911b0550350414ce00b88f8dd39964f1a8631824db8e78b61d0ea6f3d9fcffcf2cd20be7d88a1583854682db4d136acd08542c3d

We have two data items, the first is an ECDSA signature in DER format, and the public points of the P2PKH output we are spending. The last byte of the signature is the SIGHASH flag, which in this case is 0x01 or SIGHASH_ALL.

If you want to follow along with how these structures work, webbtc.com has a great script visualization tool which will allow you to see how these go together. In particular here is a reasonable example transaction with one input and output, and here is a play through the script execution which does a good job of explaining how and why it is valid.


How can I get all the Bitcoin transactions data since its inception? If I want to get all the Bitcoin transactions since it started, how do I go about doing this? Is it possible to get all that data from bitcoind database?

This is called the Blockchain.  You can access it yourself if you use a client like the reference client, Bitcoin-QT.  By reference, I mean that Bitcoin-QT downloads it to your disk... you have to write a program to access past transations, because Bitcoin-QT doesn't allow you to search past transactions other than your own.

Another way to access the blockchain is to use a web site like Blockchain.info. You can either use the web pages to review the blockchain, or use some of their APIs.


Where can I get a list of upcoming features for NXT? and whats on the way for 2014? Where can I get a list of upcoming features for NXT coin? And what are some of the upcoming features for coming 2014.

On the NXT-Wiki you can find a list of planned features which are currently in development. Here some examples:

Voting System
Instant Transactions
Automated Transactions
Multisignature transactions
Shrinking (reduce size of Blockchain)

For a more detailed release plan, I guess you need to check the project sites of specific features.


Wasted satoshi due to transaction fees Say I have a wallet containing 1000 satoshi, and I want to transfer this to another wallet, but it doesn't cover the transaction fee, do I just waste it?

I don't have the private key to the wallet as it's an iOS wallet
The wallet won't let me set a zero transaction fee

Is it BreadWallet? You can restore that in Mycelium, afaik.

As to your actual problem: just leave it, file the seed words somewhere safe, and maybe one day it'll be worth actual money.


Bitcoind daemon: error connecting to the server? I am trying to create a new bitcoin address and store it in a shell variable $NEW_ADDRESS.

When I run this command:

$NEW_ADDRESS=$(./bitcoin-cli getnewaddress)

I get the following errors:

error: Could not connect to the server 127.0.0.1:8332
Make sure the bitcoind server is running and that you are connecting to the correct RPC port.
-bash: =: command not found

I have tried everything to fix the connection error, including typing the command:

./bitcoind -rpcport=8332

Or even, changing the bitcoin config:

nano ~/.bitcoin/bitcoin.conf

And typing these lines on the configuration:

rpcconnect=127.0.0.1
rpcport=8332;

But nothing works. Does anyone have an idea on how to troubleshoot and fix this?

Thanks in advance.

-bash: =: command not found

Leave out the initial dollar symbol when you assign the variable:

NEW_ADDRESS=$(./bitcoin-cli getnewaddress)

Use the dollar symbol when you use the variable:

echo $NEW_ADDRESS


Where can I learn how to create my own blockchain with a new transaction scheme? I am trying to create my own blockchain with my own transactions but there is not much information on how this works in detail.
Basically I want to create a transaction with my own structure using blockchain. It is possible?

The reason why you are not finding many detailed resources about blockchain is because it is a new innovation and not widely understood. Most resources are scattered across blogs and code repositories. A few developer and programming guides are listed lower down.

The most valuable and primary resource is the Bitcoin Core client implementation - also called the Satoshi reference client.

It is possible to design and build a blockchain client from first principles. The design will require several components, and here are the basics:

P2P networking - manage connections & send/receive messages and data
a Messaging protocol - message and data format
Database - store & retrieve block headers, blocks, transactions and previous spends (UTXOs)
client Behavior logic - handle messages, protocol rules, coinbase rules, etc
Consensus logic - gather, process and apply peer consensus about the validity of transactions, blocks and the unfolding chain
Coin generation code - mining and proof-of-work (if any)
general household code - logging, error handling, state maintenance, etc

That may seem daunting at first glance, but it is a worthwhile and achievable project.

Notice, that cryptography is not listed. This is because a private blockchain does not require secrets or obfuscation. However, if it is of interest, one can implement Bitcoin's Eliptic Curve library and address schema.

Before creating a blockchain client and protocol from first principles, it will be necessary to do some research about how the Bitcoin protocol works. Mastering Bitcoin by Andreas Antonopoulos provides good insight. Other resources of interest:

https://bitcoin.org/en/developer-documentation
This question has useful discussion and several pointers to learning resources.

Study how the reference client behaves, and read the reference client code, especially the file main.cpp - (linked to Core v0.13, since that file's code has been rationalized into separate files from v0.14 onwards)

Also, there are several open source libraries that allow you to run barebones blockchain nodes and exchange protocol messages. Some libraries are better than others:

pychain - basic blockchain prototype
PyCoin - a Python Bitcoin clone
Zen System - encrypt everything blockchain featuring communications, transactions and a DAO.


segwit compatilibity bc1 and 3 bitcoin wallet? I would like to know what's the better aproach for upgrading from a legacy address to a segwit one, but there are two type of segwit as P2SH starting with 3  and Native SegWit (bech32) starting with bc1, but don't know which of the two segwit one, is better and is compatible to transfer and receive from a legacy one. ?

I know that a segwit wallet helps to reduce the size of the tx, and reduce fee,but don't know if there is a drawback for each type of segwit?

there are two type of segwit as P2SH starting with 3 and Native SegWit (bech32) starting with bc1, but don't know which of the two segwit one, is better and is compatible to transfer and receive from a legacy one?

Generally speaking the "bc1" native SegWit address is better. It's completely redesigned comparing to the classical/legacy Base58 encoding invented by Satoshi.
Alphabets in a "bc1" address can be either all upper-case or all lower-case, the former fits QR code better, resulting in a more compact QR code. Without mixed-case alphabets, "bc1" address is also easier to be read orally.
"bc1" (P2WPKH) addresses take the least bytes in transactions comparing to "3" (P2SH-P2WPKH) addresses or "1" (P2PKH) addresses, therefore its miner fee is the cheapest among three address types.
Bitcoins can be freely transferred among all three address types.
However, when you are receiving bitcoins, there's a compatibility issue around "bc1" addresses, that some (old) wallets (including the withdrawal interface of some exchanges) simply don't recognize it.
When you are sending bitcoins from SegWit addresses, there's nothing to worry about, except a minor issue that a 0-conf SegWit transaction may not show up in the payee's view, if the payee is using an old wallet which is not SegWit-aware. In that situation, it will finally show up in the payee's view when it gets included into the blockchain.
By the way, SegWit addresses, including both "3" and "bc1", currently doesn't support the "sign/verify message" feature in Bitcoin Core. Some developers also worried about abuses of this function IIRC. Trezor and Electrum had implemented this feature in ways which were not compatible with each other. In the future, maybe we could see this standardized by BIP322.

a segwit wallet helps to reduce the size of the tx, and reduce fee

Currenty SegWit doesn't really reduce the size of the transaction. The "bc1" native SegWit address only reduce the size by several bytes. The "3" P2SH SegWit address on the contrary cosumes more bytes in the block, because P2SH wrapping itself requires a 20-byte hash.
Mostly it's just a discount, that the "witness" part (mostly digital signatures and pubkeys) would be counted as 1/4 of its actual size (aka. "virtual byte", or vB for short). Obviously, only transactions spending coins from SegWit addresses enjoy that discount.
However, SegWit has other benefits, like Signing of input values, which simplifies unsigned transaction format, especially PSBT, which could benefit offline/cold/hardware wallets and transactions involving multiple parties (related).  Update: it turns out that this improvement doesn't really work: https://blog.trezor.io/details-of-firmware-updates-for-trezor-one-version-1-9-1-and-trezor-model-t-version-2-3-1-1eba8f60f2dd


Create a Double sha256 block and trandaction I have same problem whit create a double sha256 of the transactions and blocks with C++.

The hash block it is created with the concatenation of these data,

version + previusBlock + merkleRoot + timeStamp + bit + nonce

In the hash block is not necessary to include the all data raw transaction because is are include in the merkleRoot, right?

For create, hash transaction is create whit the concatenation of these data,
versionRawTransaction + output of the transaction input + scriptSing + sequences transaction input + cAmmount transaction output + publicKeyScript + lockTime raw transaction

Or are include the data for saving the variable structure? in this method

numberRawTransactions + versionRawTransaction + numbarTransactionInput + output of the transaction input + scriptLenght + scriptSing + sequences transaction input + numbarTransactionOutput + cAmmount transaction output + publicKeyScriptLenght + publicKeyScript + lockTime raw transaction

Now I've tried to apply this theory in my C ++ program but can't get the desired hash. Can you help me?

This is the my test code

    TEST(hash_test, first_test_double_sha_bit_genesi_block_bitcoin_crypolibrary)
{
    //Init logger
    FLAGS_minloglevel = 0;
    FLAGS_logtostderr = true;
    google::SetLogDestination(google::GLOG_WARNING,  "/home/vincenzo/Github/SpyCblock/test/log/first_test_sha_not_on_bitcoin_protocolo.log");

    string version = "01000000";
    string previusBlock = "0000000000000000000000000000000000000000000000000000000000000000";
    string merkleRoot = "3ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a";
    string timeStamp = "29ab5f49";
    string bit = "ffff001d";
    string nonce = "1dac2b7c";

    stringstream stream;

    stream  << version << previusBlock << merkleRoot << timeStamp << bit << nonce;

    Bytes byte = asciiBytes(stream.str().c_str());
    Sha256Hash shaHash = Sha256::getDoubleHash(byte.data(), byte.size());

    LOG(INFO) << "The hash genesi block converting with double sha256: " << shaHash.ToString();
    ASSERT_EQ(shaHash.ToString(), "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");

}

but I get this result 46f4d3f53251d05ab58a3f8925ce7023f2115dc38468ec78521c7d0e1dc7bd19

Since I know practically nothing in cryptography in practice, I relied on this library where I use this type of data here that makes the double sha256 Find here

Sorry for my terrible English but I'm learning

The problem is that you are hashing the string of the hexadecimal representation of the bytes of the block header, not the bytes of the block header itself. You need to hash the bytes of the block header itself.

You need to set everything as a byte array, not a string. So you would have something like this for the entire block header all together:

Byte[] block_header = {0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3b, 0xa3, 0xed, 0xfd,
                       0x7a, 0x7b, 0x12, 0xb2, 0x7a, 0xc7, 0x2c, 0x3e, 0x67, 0x76,
                       0x8f, 0x61, 0x7f, 0xc8, 0x1b, 0xc3, 0x88, 0x8a, 0x51, 0x32,
                       0x3a, 0x9f, 0xb8, 0xaa, 0x4b, 0x1e, 0x5e, 0x4a, 0x29, 0xab,
                       0x5f, 0x49, 0xff, 0xff, 0x00, 0x1d, 0x1d, 0xac, 0x2b, 0x7c};

It's possible convert the string hex into matrix byte in C++ with this code

  vector<unsigned char> ToHexIntoVectorByte(string &hexData)
{

  vector<unsigned char> *bytes = new vector<unsigned char>();
  for(unsigned i = 0; i < hexData.length(); i += 2)
  {
      string byteSubString = hexData.substr(i, 2);
      unsigned char byte = (unsigned char)strtol(byteSubString.c_str(), NULL, 16);
      bytes->push_back(byte);

  }
  return *bytes;
}

for extract the matrix in the unsigned char using vectorresult.data() and if using the Bitcoin-Cryptography-Library the final code is

vector<unsigned char> vectorByte = ToHexIntoVectorByte(stringHex);

Sha256Hash shaHash = Sha256::getDoubleHash(vectorByte.data(), vectorByte.size());


Should I keep my bitcoin-qt wallet running all the time? It can take a day or more to get in synch, so it's somewhat problematic to only start it when I want to transact.  But are there any security issues in keeping it running constantly?

What's the general practice for those using local wallets?

The first time you load the client, it can take some time to download the whole blockchain (currently something like 15 GB). However, if you close the client and then reopen it, the client will only download the new blocks from the blockchain that it hasn't seen yet. The previous part of the blockchain is already stored on your computer.

To catch up a day's worth of blocks should only take a minute or two. It's perfectly reasonable to close the client when you're not using it.


Has there been a big uptake of merchants accepting Bitcoin Cash? With Bitcoin Cash still relatively new (August 2017), are there any statistics available on the percentage of merchants who previously accepted Bitcoin, that now also accept Bitcoin Cash, or that switched over to accepting Bitcoin Cash instead of Bitcoin?

Looking at the community created webpage: https://acceptbitcoin.cash/

If you are looking at the percentage of merchants who previously accepted Bitcoin, that now also accept Bitcoin Cash, there is a statement that says that 131 out of 1053 websites listed support Bitcoin Cash.


Will lightning network efficiently support a single payment of 25 cents? Suppose my website sells emojis for 25 cents a piece. And I get 1000 unique customers that each buy just one.  Will lightning network or any other technology allow me to process these transactions without making 1000 separate commits to the blockchain?

I want to avoid paying 1000 transaction fees (and thereby invalidating my business model).

First off, yes, the lightning network will not require 1000 on-chain transactions added to the blockchain.  The lightning network aggregates off-chain transactions into single on-chain settlements.

Like the Bitcoin network, the lightning network will also operate on a model of market-driven transaction fees.  However, these are not the same fees paid to miners on the Bitcoin blockchain.

The lightning network will be a hub and spoke network of bi-directional payment channels.  Channels are connections between two nodes on the network, and a single transaction may travel through several channels.  Nodes will charge you to use their channels, so you end up paying fees to multiple nodes.

However, these fees are likely going to be very small.  Unlike mining, there is no large hardware investment to run a lightning node.  Even a cheap computer will be able to do so.  The real cost of running a node is that an amount of bitcoin must be tied up in each payment channel that node has open.  This also limits the amount of total bitcoin that a channel can transfer in one direction.  Because of this, channels will adjust their fees to incentize transactions in different directions.

When a channel has had too much bitcoin travel in one direction, it will either have to close and re-open, or will have to get people to transfer in the opposite direction.  The cost of closing and re-opening is an overhead that will be worth avoiding, since that is when on-chain fees will have to be paid.  This means that there will always be channels trying to get you to use them...even if it means negative fees (see this answer).

Wallets should be smart enough to route your payment through a series of channels that will minimize your fee.  On some channels you will pay higher, some lower, and with negative fees, some may even pay you!  Due to the relatively low barrier of entry for running a node, this will likely drive down overall fees.  Some have even speculated that fees will be effectively zero.

In short, unlike Bitcoin, the lightning network is poised to be a true micro-payment network.


bitcoind connection refused error with curl my bitcoin.conf:

server=1
rpcauth=myusername:e2aa83d74a55b7addfe070367546e72d$953dda2b7e2d5a151a7ef0e82ed50a734bf4c4ac55289fede8bd340489d5af0f
rpcallowip=46.101.245.27clientip address
datadir=/mnt/volume_fra1_03/

my cliend side options:

BITCOIND_SCHEME=http
BITCOIND_HOST=142.93.165.221
BITCOIND_PORT=8332
BITCOIND_USER=myusername
BITCOIND_PASSWORD=mysecretpassword

everything is correnct but i get connection refused error.
on serverside 8332 is open and bitcoind listen.
bitcoin-cli getblockchaininfo is working.
bur i try connect remotely i geer error connection refused.

Try setting rpcbind to the same ip address as rpcallowip. I believe the behavior of those options changed recently with 0.18.0, https://github.com/bitcoin/bitcoin/blob/master/doc/release-notes/release-notes-0.18.0.md.

  The rpcallowip option can no longer be used to automatically listen on all network interfaces. Instead, the rpcbind parameter must be used to specify the IP addresses to listen on. Listening for RPC commands over a public network connection is insecure and should be disabled, so a warning is now printed if a user selects such a configuration. If you need to expose RPC in order to use a tool like Docker, ensure you only bind RPC to your localhost, e.g. docker run [...] -p 127.0.0.1:8332:8332 (this is an extra :8332 over the normal Docker port specification).


I can't find my bitcoin address and my bitcoin core is out of sync by 3 years Hey guys I am a newbie at Bitcoin just recently found out about it.

I downloaded Bitcoin core; I encrypted the wallet; I created a backup folder, but it is out of sync by 3 years 4 weeks and i can't seem to find my Bitcoin address due to it. How do I find my Bitcoin address if it is out sync?

Go to the top left, click File then receiving or sending addresses. There, you can create new adresses and look at your current addresses.


Why are there no Bitcoin price/trade records before 2013? Example: http://www.livebitcoincharts.com/
On that chart, it starts at $135. That's quite a sum to start with. Why does it only start in 2013 when it started "blowing up" for the first time?
"All time" apparently means "since sometime 2013".

This is a fascinating question and good catch. The only chart I could find listing anything before 2013 is 99Bitcoins. TradingView history begins in May 2014, and CoinMarketCap goes back to May 5, 2013. The bigger exchanges I checked don't go back that far except for Bitfinex, which starts in January 2013, and for dates during that period Bitfinex only charts weekly changes.
I don't have a definitive answer but will offer two possible explanations. The first is that this lack of price data is related to the March 12, 2013, "accidental hard fork" caused by an undiscovered inconsistency between versions 0.7 and 0.8.0, when a block created by a miner running the newer version was considered invalid by miners running the older one. This would mean that for a short time there wasn't a way to define a price because there wasn't consensus about what wallets held which coins (which led Mt. Gox to temporarily suspend deposits with a subsequent crash in exchange rate).
But the more plausible explanation for why there aren't trading records or a price prior to 2013 is that for there to be "a" publicly available price for any exchangeable asset, there has to be some sort of public market for the asset. BitcoinWiki has a table of prices for periods before 2013, but before March 2010 the price is listed as "basically none." The page also says that on Oct 5, 2009, the first public sale was offered on the New Liberty Standard stock exchange (at a rate of 1 USD/1,309.03 BTC), which is also mentioned in this review of Nathaniel Popper's Digital Gold: Bitcoin and the Inside Story of the Misfits and the Millionaires Trying to Reinvent Money. So before October 2009, there literally wasn't a price (if by "price" we mean the exchange rate denominated in fiat currency). There were no trades (denominated in fiat), hence no trade history.
On March 17, 2010, the first online market exchange, BitcoinMarket.com, began operating. Mt. Gox launched the same year and by 2014 was the largest exchange. Although both companies are now defunct and their trade histories (presumably) not publicly available, 99Bitcoins does list "the" price of bitcoin going back to the day BitcoinMarket.com began operations. For these two companies there likely isn't a publicly available record of trades that would allow for an accurate calculation of an average exchange rate in fiat currency for bitcoin before still-existing exchanges began publishing their trade histories. Exchanges may only publish pricing information from the date they begin operation, and the USD/BTC exchange rates on TradingView are all based on particular exchanges, which is why even their aggregate data may not go back before 2014.


What is local Bitcoin? I was listening to the Pompliano podcast and there was this really awesome guy talking about how he has been able to use local Bitcoin to stay afloat in amidst a collapsing economy and society in his home nation of Venezuela.

He shared how others like him have been able to survive economically thanks to local Bitcoin, but what is local Bitcoin? Where can I learn more about it?

LocalBitcoins is a service that allows you to trade BTC with real money. The difference between it and other exchanges is that LocalBitcoins staff themselves don't buy or sell, but its users set their trading fee, price, and the currency, and to buy or sell bitcoins the site allows you to find a merchant-user.

A local Bitcoin does not exist. The BTC blockchain is a whole and only meaningful if it's together.


Verify Bitcoin Transaction Following the great post [Redeeming a raw transaction step by step example required, I came up with  code below but the verification failed.

// pubkeyBytes, len: 65
// 042daa93315eebbe2cb9b5c3505df4c6fb6caca8b756786098567550d4820c09db988fe9997d049d687292f815ccd6e7fb5c1b1a91137999818d17c73d0f80aef9

// data, len: 32
// 30f10a6468b7d98257af63fb40dfcf2cefe991346fd37c67cf7b51ff8d4404d3

// signatureBytes, len: 71
// 30450220587ce0cf0252e2db3a7c3c91b355aa8f3385e128227cd8727c5f7777877ad772022100edc508b7c14891ed15ab38c687019d7ebaf5c12908cf21a83e8ae57e8c47e95c

    ECPublicKey publicKey = (ECPublicKey)KeyBuilder.buildKey(KeyBuilder.TYPE_EC_FP_PUBLIC, KeyBuilder.LENGTH_EC_FP_256, false);;
    Secp256k1.setCommonCurveParameters(publicKey);
    publicKey.setW(pubkeyBytes, (short) 0, (short) pubkeyBytes.length);

    Signature eccSign = Signature.getInstance(Signature.ALG_ECDSA_SHA_256, false);
    eccSign.init(publicKey, Signature.MODE_VERIFY);
    boolean verified = eccSign.verify(data, (short)0, (short) data.length,
                signatureBytes, (short)0, (short)signatureBytes.length
            );
    Assert.assertTrue(verified);

Assertion failed at the end.

Have been stucked for hours. Cannot figure it out. Any help is highly appreciated. Thanks.

static void test_sig ( )
{
  const MyByteArray pubkey ( QByteArray::fromHex ( "042daa93315eebbe2cb9b5c3505df4c6fb6caca8b756786098567550d4820c09db988fe9997d049d687292f815ccd6e7fb5c1b1a91137999818d17c73d0f80aef9" ) );
  const MyByteArray signat ( QByteArray::fromHex ( "30450220587ce0cf0252e2db3a7c3c91b355aa8f3385e128227cd8727c5f7777877ad772022100edc508b7c14891ed15ab38c687019d7ebaf5c12908cf21a83e8ae57e8c47e95c" ) );
  const MyKey32     digest ( QByteArray::fromHex ( "30f10a6468b7d98257af63fb40dfcf2cefe991346fd37c67cf7b51ff8d4404d3" ) );
  qDebug ( ) << ( digest.verify ( pubkey, signat ) ? "passed" : "failed" );
}

my result is:: passed

the signature is correct for digest and public key

may be something is wrong in your verification code with decoding hex values and/or byte order in digest?


Bitcoin transaction as been unconfirmed for 9 days Please what can I do? I received a transfer of 0.559btc and it has remained unconfirmed for 9 days, I can't even find it again on the blockchain.info but it was there for almost 4 days. I can see the transaction here on tradeblock. I have alerted the company that made the transfer to me but their customer service is horrible. Please any help? Can I still get this deposit?

Also why did it disappear from blockchain.info?

When transactions are published to the network, they first are mere payment promises. You have received notice of a transaction on the network to one of your addresses. However, for the money to actually become signed over to you, transactions need to be confirmed by being included in a block of the Bitcoin blockchain.

Most nodes on the network track unconfirmed transactions on the network only for a few days before they drop them from their memory pool. For example in Bitcoin Core this timelimit used to be three days previously and is now fourteen days. It seems that blockchain.info dropped the transaction because it timed out of their memory pool.

To speed up confirmation of the transaction, you could try to construct a child-pays-for-parent transaction: you would send another payment from your wallet and spend the money that you would receive from the unconfirmed transaction. If you use Bitcoin Core, you can specifically select inputs by enabling the "coin control features" in the settings. Otherwise, you can enforce spending the unconfirmed transfer by spending your complete balance. Many recent wallets will then automatically generate a new transaction with a higher fee that should get both the parent and the new transaction confirmed.

Unfortunately, the only other options are

to wait it out
to request that the sender updates their payment with a higher fee.

In this particular case, I think that your transaction should soon go through, as there are currently only about 3MB of transactions above 240 satoshi/byte and the one that you're waiting for pays ~239.18 sat/B.


How are Bitcoin Signed Messages generated? Ledger Nano S and other pieces of Bitcoin software and hardware can sign messages using the private key associated with an address.

Doing this, I get the following output:

-----BEGIN BITCOIN SIGNED MESSAGE-----
Test
-----BEGIN SIGNATURE-----
1BqtNgMrDXnCek3cdDVSer4BK7knNTDTSR
ILoOBJK9kVKsdUOnJPPoDtrDtRSQw2pyMo+2r5bdUlNkSLDZLqMs8h9mfDm/alZo3DK6rKvTO0xRPrl6DPDpEik=
-----END BITCOIN SIGNED MESSAGE-----

What exactly is being signed? How is the signature generated? What is the hash preimage that goes into the ECDSA signing algorithm?

The message that is signed is prepended with

"\x18Bitcoin Signed Message:\n" + compactSizeEncoding( len(message) )

\x18 is Python syntax for unicode character 0x18. This new text string is then converted into a byte array by interpreting the string as UTF8. This will give you the correct hash preimage which is:

SHA256(SHA256(utf8.to_bytes("\x18Bitcoin Signed Message:\n" + compactSizeEnc( len(message) + message )) =
559766ea41f2bc4125e5449200dbf7e902b724b66104820ca5b7fc59f30a19e0

You can see a Python code example here. The function msg_magic generates the hash preimage from the message. This Python code example does not correctly implement compactSizeEnc, however. So it only works with a message length up to 253 bytes.

The correct way of handling compactSizeEncoding is documented here.


What's the default strategy miners employ when they select txs from their pool? Each tx has an associated fee and size. Moreover, we have a size limit on blocks. Finding txs that maximize the profit under this restriction is basically the Knapsack problem.

So, do default client miners really employ Knapsack algorithm when they do their selection ?

You are correct, it is infact equivalent to knapsack problem. To the best of my knowledge most miners simply sort by fee and this gives a good approximation for optimal solution.
A couple of things of things to highlight how difficult the transaction slection is:

1) Knapsack problem as you pointed out.

2) But even if the constraint in knapsack were removed(i.e infinite blocksize), still calculating optimal fees is NP hard problem.

  Transactions also have dependencies and conflicts. We’ll take
  conflicts first, which come from the prohibition on double-spending.
  We’ll also make the problem considerably easier by ignoring the block
  size limit and assuming all transactions have a constant fee. If
  transactions B and B’ both claim funds from transaction A, then only
  one of B and B’ can be published and we say they conflict. If this is
  the only constraint, we can simply draw a graph of all transactions
  with edges between transactions which conflict. The miner’s task is to
  find the largest set of vertices (transactions) with no edge between
  then (no conflict). Solving this is exactly the maximum independent
  set problem. (Source)

I presume the double-spend instances are rare and so are dependant transactions(child pays for parent known as CPFP). Therefore, my best guess is that simple greedy algorithm(taking CPFP into account) is close to optimal. Furthermore, there is also the tradeoff of time complexity which is very crutial for miners when we attempt alogrithms which are not simple.


How can wallets users know their private keys? Why don't some bitcoin wallets give the private keys to its users?
Is it safe to use these wallets? Is there any way for the users to know their private keys without the need to contact the wallets companies?

Electrum: pulldown menu "wallet", "Priv keys", --> export.

The idea to hide priv keys is linked to the security of the system. If the privkey is immedeatly "visible/accessible", the risk of unwanted access (be it malware, be it other people) is high, as the knowledge of the key allows for access to your funds. So the majority of wallets hide the priv key behind some access logic. There are passwords and seeds as most common layers, to be able to open the wallet, and then find the priv key behind a menu.

Yes, generally these wallets are save to use. On the opposite side there are so called "online wallets", offered by some providers. These wallets usually don't give you access to your priv key, and as such you have to trust these companies, that they have stored the priv key correctly (and safe) for you.


How to "cash out" of the Lightning Network without closing channels? I am working on an ecommerce site that accepts lightning payments and was curious about how to "cash out" to pay vendors without closing channels to customers. I was planning to run two LN LND nodes and have two channels between them. One node for personal use highly connected and one running on BTCPay Server. Since not all my vendors accept bitcoin, I was working through the best way to be able to "cash out" my bitcoin to fiat (by closing one of my channels between my personal node and my BTCPay Server business node) to pay my vendors while still having an open channel to the world through which individuals who did not have an open channel with me could route payment. Rather than having my store (BTCPay Server business node) close channels to customers to "cash out" to pay vendors, I thought I would send LN payments from my store node to my personal node and close one of the two channels between my store node and my personal node. My thoughts may be convoluted and unnecessary and I would welcome any suggestions.

This will get easier in the future as exchanges will be implementing deposits and withdrawals via LN.

At this time, if you need to deposit BTC and the exchange does not support LN deposits, I'm afraid you are stuck with closing channels for now.

Perhaps there will be a way soon to rebalance the channels to minimize the number of closures required.  Basically, push back funds on channels from customers 1-4, to pull the funds onto the customer 5 channel, and close only the one customer 5 channel.


Why does Coinjoin need multiple participants to increase privacy? Coinjoin is a method that make a transaction with other transaction of
  other parties to hide the link between txin and txout.

In case of this, why we need others transaction? We have many bitcoin address since we are using HD Wallet(BIP32) so I think we don't need to wait other bitcoiner to participate into shuffling for making a transaction. we can just give our address set.

Is there a special reason that enforce to combine mine and others stuff?

Sorry for my English.

The only advantages of doing a coinjoin is that the recipient of your funds cannot see the source of your funds (and the sender of funds to you cannot see your future transactions). If you do a coinjoin with only your funds, any branch they follow along this trail will lead to a source (or destination) of your funds.

Every source you include in the coinjoin will thus be exposed. Your recipient, of course, won't know that they're all of your sources, but if they're keeping a log of addresses that are likely tied to your identity, now all of those addresses, and only those addresses, will be in their log. If you instead do this with other people, it muddies such a log with false leads.

Similarly, the sources of your funds will all have logs of that destination of funds. Also, they can follow the chain back and deduce that your address is likely tied to another address if you have multiple sources, and they will all have an list of your other addresss. Again, they won't know that the other address are necessarily your address, but they actually will be, and so their log will contain accurate address linkage data.


How can a 51% attack be successful? In the paper by Nakamoto, miner can accept the mined block only if all transaction are valid.

Assume that there are 5 miners in the world. 4 of 5 are honest that have 10% of 100% hash power and 1 of 5 is malicious that has 90% of all hash power.

Let's say group A consists of honest nodes (4 of 5).
Let's say group B consists of malicious node (1 of 5).

Group B wants to create a block which has a fraud transaction (e.g. Alice wants to spend 1000 BTC but she actually does not have it).
Group B is successively creating and propagating some blocks with huge hash power, but Group A does not accept these blocks because transactions in blocks are invalid.
Yes, 51% attack is not accepted with only hash power. So, length of chain of group A is short but group B is long. But group A does not accept chain of group B.

So my conclusion is that 51% attack makes a mess in the network, not coin control.

I'm confused. Please help me understand where I am wrong.

A 51% attack does not allow the attacker to spend coins they do not own; the usual rules of validity still apply for transactions and blocks. If those rules are broken, the block/transaction will be ignored by the rest of the network, no matter how much hashpower the miner making invalid blocks has.

This question has a more complete explanation of what a 51% attacker can, and can not do.


How to determine where a bitcoin address resides I sent bitcoins to a different address that I might own. However, I am unable to determine where that bitcoin address resides. How can I determine where it resides and or how to access that bitcoin address?

You cant. You can send BTC to anywhere, including addresses that will never exist.

If you're reasonably sure that the address is in use, i.e. by seeing active transactions on bitcoin.info, you could try sending a small transaction with a message in it, but it will likely be ignored.

In all probability, you lost these coins.


Can someone recognize any two addresses (generated by hardware wallet) come from the same hardware wallet/mnemonic seed? Can someone recognize any two addresses (generated by hardware wallet) come from the same hardware wallet/mnemonic seed?If I generate multiple cryptocurrency accounts/addresses in ledger live,is it possible for someone to recognize it comes from the same hardware wallet/seed? I would also want to ask the same question for software wallet. Thanks.

Although there is no link between your addresses alone (someone would need your seed, xprv, or xpub for that) you do leave some residual identity once you start spending.
For example if your wallet builds a transaction where two or more of your previously unassociated addresses are used as inputs in the same transaction, then it may suggest that the spender owns both (or more) of those addresses.
Wallet technologies exist that attempt to muddy the waters of those trying to surveil by combining multiple unrelated coin owners to sign a single transaction together with multiple inputs. Basically disproving the assumption that multiple addresses as inputs in the same transactions means one owner owns all the inputs.


Unable to establish connection to bitcoin using json and php I'm newbie to bitcoins. Im trying to get the info, as much as I can.
I'm trying to get the information by using getinfo() method that is mention in api documentation.
The code i have tried is mentioned below.

   require_once('jsonRPCClient.php');
        $bitcoin = new jsonRPCClient('http://identifier:identiferpass@rpc.blockchain.info:443');
 print_r($bitcoin->getinfo());

I have googled it but didn't find the solution. I'm not getting what is the issue in the above code.

I just want to create a hello world connection. Any suggestions will be appreciated. Thank you

You are trying to connect to http over the https port.

For HTTP use:

  $bitcoin = new
  jsonRPCClient('http://identifier:identiferpass@rpc.blockchain.info');

For HTTPS use:

  $bitcoin = new
  jsonRPCClient('https://identifier:identiferpass@rpc.blockchain.info');

According to the blockchain.info documentation both should work.


How to accept payments with Blockchain in PHP I am trying to set up sort of a BitPay system where

1) A user selects how much money they want to send (price in BTC).
2) The system gives the user an amount of money they need to pay and the address they need to send to.
3) The system checks if money is sent from the user's Bitcoin address, to the receiving address with the amount of bitcoins specified
4) If all is good, display a message or whatever, if not display error

How can I do this?

Since you say "sort of a BitPay system", I assume you don't want to use BitPay.

You can start with dissecting some of the work people have done in the space on repositories such as bitwasp or bitcoin-php. This is probably more than you need, however the building blocks are there for what you want to do if you wanted all of the logic to live in php.

If you want to actually generate addresses, here is a good place to start.

Here's a quick stab at a workflow that I think would be pretty straightforward to develop.

User enters value in their currency.
Querying an exchange rate table such as the one on Blockchain.info, display the amount in Bitcoin.
You could generate a QR code using PHP QR as well as displaying a link to click/address to copy/paste, then verify that the transaction was completed using Blockchain.info or something else.

Or.... you could just use Blockchain.info's free tool, but I assume you have a reason why you want to build your own solution.

In the case that I'm mistaken and you do actually want to use BitPay, you would probably use either the Bill or the Invoice method of the BitPay API.


What factors decides the number of tokens to generate? Tron has decided to generate 100B tokens with some initial price? What parameters do these centralised crypto owners consider before deciding the number and price of tokens?

There are no answer to that.
Depends on many things the token creators want to accomplish.


Can a miner give themselves less than the maximum block subsidy if they wish to do so? The current maximum block subsidy is 12.5 bitcoin. A mined block recently got rejected from full nodes after a miner tried to post the block subsidy as 13.26 bitcoin. But what about in the other direction? Would it have been accepted if the miner posted the coinbase transaction with 10 bitcoin?

Yes, it would have. In fact, this has happened before in many different blocks.

The Bitcoin wiki has two instances of this documented:

  In block 124724, user midnightmagic solo mined a block which caused one less Satoshi to be created than would otherwise have come into existence. Therefore, all calculations from this block onwards must now, to be accurate, include this underpay in total Bitcoins in existence. Then, in an act of sheer stupidity, a more recent miner who failed to implement RSK properly destroyed an entire block reward of 12.5 XBT in block 501726.


How Lightning Networks protect itself from 'Selfish Mining'? It is a well accepted fact that mining pools do engage in 'selfish mining' by not broadcasting a block to the network when they find a PoW solution, but building on top of that block so as to maximize revenue. Now from the point of view of lightning nodes that are creating a HTLC, assume that the blockchain height is 'h'. A HTLC is forwarded by the origin node and each node on the way uses 1 block of CLTV_expiry_delta (say there are 5 intermediary nodes). But soon after the final node reveals the pre-image to its peer, 3 blocks gets relayed simultaneously. Now, it may be the case that even after including a buffer, some nodes along the path can get exposed as its peer can relay the transaction to the blockchain due to timeout. Is there a protocol in place to stop intermediary nodes from getting vulnerable due to selfish mining?

Your question seems very similar to the 51% attack vector on the lightning network which I described on the lightning dev mailing list. I am not aware of any protocol to prevent this nor do I see any way of preventing what you and what the mailinglist post describe. The timeouts depend on blockheight and the Bitcoin protocol has the consensus rules that the longest proof of work chain wins.

I think it is a generally accepted assumption that Bitcoin will only operate in a secure way if at least 51% of the mining power comes from honest nodes (which are following the rules) on the plus side any secrete mining operation would statistically speaking only be harmful if the operation has at least 51 percent which is hard to achieve and probably also more expensive than the gains from winning such an attack.


Does the Taproot update benefit all bitcoin users? or is it for a selective amount of people I came across a blog post where it mentions that the taproot update is promised to speed up BTC transactions, lower their fees, etc. but does this mean that literally, anyone sending or receiving BTC will benefit from it? will it require special software to operate?

Bitcoin transactions require a certain size and with taproot and tapscript we can decrease that size.
This means that effectively we will be able to store more transactions in one block allowing overall a slightly higher throughput of bitcoin transactions in the network.
So even if you continue to use legacy transaction formats you might still benefit from the fact that the blockchain might be less congested as it can fulfill a higher demand with the same space.
Of course if you want to use it you will need a wallet / software that supports the new format but as it seems it will be merged to bitcoin so modern wallets should be compatible and also implement it.
The only direct benefit that you get from switching to taproot is that your tx will be smaller in size allowing you to either save on fees or if you want to pay the same fees allow you to have a higher feerate. Though miners are not forced to mine transactions with highest fee rates first they are certainly economically incentivized to do so. Thus besides doing something good for the network your tx might also be confirmed faster.


Does bitcoin improve on "hard" currencies in any way? Question is in the title. Anyone who's toyed sufficiently long enough on the foreign exchange understands that currencies are largely driven by sentiment or manipulated on the odd occasion. Plus, there's the fact that money has no intrinsic value. Has bitcoin overcome any shortfalls and risks of conventional currencies ?

There are huge differences between FIAT and Bitcoin.

Fiat is created out of thin air "with fractional reserve banking" and other mechanisms, there is no stop on how many will be created.

Another problem is that every country is FORCED to create more of it.
Since otherwise the value of their money would increase to much, ending all export industry and tourism in that country.

So when the US prints an extreme amounts of FIAT they know that China must follow, which means that Japan must follow and the US must print more, and so it goes on.

Bitcoin can not be created out of thin air, and it takes an ever increasing energy cost to create one.

And since no country base their economy on it, its free from having to be endlessly printed. (It can´t even if it would be.)

Another very important difference is that Bitcoin is the only digital money you can own yourself with no one else having any access, and thus keep on your own computer or in your own cellphone or store on a USB the key to your money.

All other digital money, is money that is stuck in a bank and thus they might play around with it and go bankrupt.

But a Bitcoin is a Bitcoin and not simply a promise in their system.
This also means that you can send them any time of the day instantly to anyone you like now even on Facebook or in emails.

The limited amount also gives it a longterm backing in that if it picks up in any market, it cant stay this low and will have to go much much higher, a value of something like $50-$5000 would not be strange in 10-20 years IMO.


Cannot check balance with blockchain.info API I tried below code and gave valid credentials, but we could not get the response of balance check. What would be the solution?

<?php

$guid="xxxxxxxxx";
$main_password="xxxxxxxxx";

$json_url = "https://blockchain.info/merchant/$guid/balance?password=$main_password";

$json_data = file_get_contents($json_url);

$json_feed = json_decode($json_data);

$balance = $json_feed->balance;

echo $balance;

You are using the old, version 1, blockchain wallet API which was deprecated earlier this year.  None of the calls you are trying will work.

The new, version 2, API requires you to run a local nodeJS service to handle the calls. This will require you to have root access to your webserver so you will need to use a VPS instead of a basic shared web host.

You will need to request an API key here https://blockchain.info/api/api_create_code

Install nodeJS
Install NPM
Install blockchain-wallet npm install -g blockchain-wallet-service
It should install to usr/local/bin
Run the service node blockchain-wallet-service start --port 3030
Now it's running, but you still need to complete the handshake with blockchain's server. We can do that with a cURL request in a PHP file.

some_file.php

//replace with your GUID, password and API key
 $url = "http://127.0.0.1:3030/merchant/YOUR-GUID/login?password=YOUR-PASSWORD&api_code=YOUR-API-CODE";
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_URL, $url);
 $ccc = curl_exec($ch);
 $json = json_decode($ccc, true);
 var_dump($json);

Save the above and run it on your server. The file should keep spinning and loading since blockchain doesn't recognize the IP address. Wait for it to timeout about 60 seconds, and then check your email. Blockchain should have sent you an API access attempt showing what IP tried to connect. Follow the link and authorize the attempt, also the IP address from the email and whitelist it in your wallet account settings.

Now try running the file again.
If you did everything correctly you should see a response that lists your GUID followed by Success TRUE

Now you're connected and you can start sending requests with your wallet.

Check their API documentation for example calls once you're set up. https://blockchain.info/api/blockchain_wallet_api


How to get Bitcoin input transaction hash string from bitcoinjslib Transaction object? I'm using bitcoinjs-lib and its Transaction object. Transaction.ins is an array of objects, each which has a hash and script property. Both of these properties are Uint8Arrays.

I am trying to get the hex string version of the input.hash but Transaction.ins[i].hash.toString('hex') produces an incorrect result. Is there a way to get this value properly?

Apparently you need to reverse the array before toString. Transaction.ins[i].hash.reverse().toString('hex') produces the correct result. Make sure to call hash.reverse() afterward.

source: ScriptHash from bitcoin address with BitcoinJS


How can i switch from BIP32 to BIP44 using bitcoinj i am working on a wallet that is using BIP32 for creating Accounts, addresses, xpub, public keys, transaction and etc. but now i want to switch from BIP32 to BIP 44. how can i do this using bitcoinj i also study this, but there is nothing related to implementation. All i need to know that how can i implement BIP44 using bitcoinj and what is specific changes i have to do.Do i have to change all the hierarchy, if yes, then how can do this

Checkout bitcoinj master branch

Discussion https://github.com/bitcoinj/bitcoinj/pull/1341

    Wallet walletBip39 = Wallet.fromSeed(params, seed);
    System.out.println(walletBip39);

    Wallet walletBip44 = Wallet.fromSeed(params, seed, Script.ScriptType.P2PKH, ImmutableList.of(new ChildNumber(44, true), new ChildNumber(0, true), ChildNumber.ZERO_HARDENED, ChildNumber.ZERO));
    System.out.println(walletBip44);


How to get the list of blockheader I know that i can use getheader 'hash' from bitcoin core, but i can't use it for all blocks, it's time consuming.
Is there a site where i can find all bitcoin blockheader? Like a blockchain site but shows the blockheader?
Help is appreciated, thank you

You can take advantage of Blockchain.com's API (formerly Blockchain.info).
You can access BTC blocks based on their block height via a URL of the form https://blockchain.info/rawblock/<height+1>. We use <height+1> because 1 is used as the index of the genesis block, which is instead usually referred to as block 0, as it is defined to have a height of 0.
By default, this endpoint provides a JSON dump of the data in the block, but you can get the raw block data as a hexadecimal string instead by appending the query string ?format=hex. For example, https://blockchain.info/rawblock/2?format=hex will give you the data in the block after the genesis block (the block with height 1) as a hexadecimal string.
The block header is 80 bytes, or 160 nibbles (hexadecimal characters), so you can e.g. use curl to fetch the data, and then head to truncate it to just the header, and then save that hex string to a file:
curl 'https://blockchain.info/rawblock/2?format=hex' | head -c 160 > block-1.txt

You can use a simple Bash script to automate this for all blocks:
#!/bin/bash

latest_block_height=670288

for ((i=0; i <= latest_block_height; i++)); do
    if ! [ -f "block-$i.txt" ]; then
        curl 'https://blockchain.info/rawblock/'"$(($i + 1))"'?format=hex' | head -c 160 > "block-$i.txt"
    fi
    echo "Downloaded block $i."
done