text:
My Bitcoin Core wallet does not receive BTC
My Bitcoin Core wallet did not receive BTCs; it is already syncronized.
The transaction was submitted from Bitstamp on the 18th of July, as withdrawal.
In Bitcoin Core I selected the receive button, then I copied the address in Bitstamp withdrawal, then I submitted the transaction.
In Bitstamp everything appears to be ok, the amount has been transferred.
Ok but transferred where? In Bitcoin Core nothing arrived ...
Can anyone help?
Thank you

Do you have the hash of the transaction?

yes: e8efdf4663db5f8d5139e3c2ae684fc9072a89da

Thats's not the full hash, it's too short

may be he is asking about https://blockchain.info/address/1NEf87g56TMDJLUs9JfXzyenz2EUUSMqj1

According to the Blockchain, you transferred 0.01 bitcoins to the address 1NEf87g56TMDJLUs9JfXzyenz2EUUSMqj1
If you can see this Bitcoin address in Bitcoin Core wallet (Menu File > Receiving addresses) and Core is fully synchronized then something is wrong, as this shouldn't happen (see below). If you can't see this address, maybe you created/opened a different wallet and then you need to open the correct wallet, containing this address.
You could try to re-scan the blockchain for missed transactions, that is transactions that don't appear in Core. Exit Core completely (Menu File > Exit), wait for the program to exit and then start it by adding the command line option -rescan This might take a long time, depending on the speed of your computer and hard disk.


text:
How to generate random addresses from public key such that they're recoverable later using pub key only
I head that from a public key, you can generate random addresses just by adding a nonce to the public key. Then, you can regenerate all these addresses again when you need, right?
If my wallet has knowledge of my public key (of course it has), it can generate lots of private/public key pairs just by adding a number to it. For example, suppose the private key is x and its public key is y. If the wallet deleted the private key x for a while, it can generate the address y+1 and be sure that when it does x+1 it will get the private key for this address in the future when it needs to spend those funds. This is a property of elliptic curve cryptography, because there's a homeomorphism between the sets of private and public keys.
I've heard that if I give someone my public key, he can derive a unique address and send to this address being sure that I'll be able to spend it because I can find the private key for that address just by adding the same nonce he used to generate its public key. The problem is:
He has to tell me which nonce was used, otherwise I'd have to try random ones till I get to the one he used. BUT, if that's how its made, then anyone can pick my public key and find all my addresses. If he really has to tell me the nonce used (suppose it's really big and random so I couldn't guess by brute forcing), then there's the risk that I'll lose it, because I'd have to keep track of all these nonces.
So how is this done? How can I, given the public key of someone, generate a random address for him such that he'll be able to get the private/public key for it later, but such that he does not need to store anything that was used to generate that address?

I can't follow your logic completly... Do we talk bitcoin? Not sure if your statement holds true, that adding a nonce to a public key generates random addresses. Well, one could think of it. Are you sure you are not talking BIP32/44 hierarchical deterministic wallets and it's derivation of keys?

@pebwindkraft I'm talking about this: https://bitcoin.stackexchange.com/questions/41947/derive-new-public-keys-from-a-public-key

http://chimera.labs.oreilly.com/books/1234000001802/ch04.html#hd_wallets

I believe you are talking about HD derived keys, as is the previous question you linked. HD wallet structure is laid out in BIP 32.
If someone has your parent extended public key, they can derive public extended child keys using it and an index/nonce. They must have the extended key (including the chain code) But they cannot derive the child private keys. Only you can do that, using the parent extended private key. So they can tell you the index, and anyone else with the index and the extended parent public key can see which public key was used, but the only one with the private key is you.
To derive the child keys you have to at least keep the master extended private key (or the seed it came from). Without that, you cannot derive any private keys.

source: Stack Exchange

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

sort: votes


text:
What knows a LN intermediate node about a transaction?
Following with How much privacy does Lightning actually have? there is some extra questions I would like to ask.
Suppose that Alice send a LN payment to Bob and the transaction founds a route with three jumps on intermediate nodes C, D and E:
Alice -> C -> D -> E -> Bob

Can C know that Alice is the original source of the transaction, can he infer that inspecting the package it receives?
Do D knows about Alice and Bob?
Can E know that Bob is the final destination?
Does it depends on some of the channels being private?
Can a bad actor that controls both C and E knows that the transaction is the same?

An intermediate node knows the previous hop's identity and the identity of the next hop as well as the forwarded amount, the hash-lock, and the timeout value. Generally, a forwarder does not learn about the identity of sender and receiver.
Forwarding requests are always padded to the same size, so a forwarder cannot tell how many hops preceded or succeed them. Using information about the topology, a forwarder may be able to make educated guesses about origin and destination if they are the first or last hops and can assume that their neighbor does not participate in forwarding, e.g. because they don't have (other) public channels or are mobile clients that are only online intermittently. They cannot be certain, because the other nodes may have further private channels.
Two colluding forwarders can easily identify that they're part of the same payment because all the HTLCs (Hash Time Locked Contracts) along the route use the same hash to set up the forwarding agreements.
There is work in progress to replace HTLCs with Schnorr signature-based Point Time Locked Contracts (PTLCs). In payments using PTLCs each hop has a distinct secret which makes it harder to associate forwarding activity, but even then, amounts, time-out values, and timing of the forwarding requests may suffice to guess that separate hops belong to the same payment. Combining PTLCs with Multipath Payments would make it even harder to associate different hops of payments.

If the first link is a private channel, can the first forwarder be sure that is it the first hop, or is it possible to have two private channels hops?

You could have even more private channel hops. They only know that they have a private channel to the previous hops, they don't know if the other node has more private channels.

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


text:
Is there any easy tool to write raw transactions with a memo?
The idea is to build a complex transaction that have many outputs and some of them are MEMOs (using OP_RETURN) and spend one (or many) UTXOs.
A GUI tool would be awesome, but a CLI tool would also work. The important stuff is adding visibility for the fee for example, as a bad constructed transaction could be quite expensive.
In this this looking like question Electrum is mentioned, but it does not support adding a memo (as far as I understand).

Standard transactiions can only have a single OP_RETURN output

It seems that there is a special syntax in Electrum to send an OP_RETURN memo on the GUI when sending to many:
script(OP_RETURN 5468697320697320612074657374),0
tb1qerzrlxcfu24davlur5sqmgzzgsal6wusda40er,0.00003

The syntax seems to not documented, but it is mentioned on some unit tests.
As far as I could test, the OP_RETURN should be a HEX encoded string. Here is the resulting transaction

Why would you write memos into the transaction instead of storing them in your wallet and backing up your wallet?!

To interact with others, like Maya chain for example, that use those memos for some functionality.

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


text:
getrawtransaction not working for 0th BTC block transaction
I am trying to insert BTC blocks and transactions in MONGODB collection from count 0 using Python3. getrawtransaction is giving output for block 1 but not for block 0. Can somebody help me why this happening?

It's a result of a quirk from the original Bitcoin client which has been carried forward to today. Originally, the UTXO database held entire transactions; it was similar to/basically the same as the transaction index that exists now today. However the original Bitcoin client had a bug where it did not include the transaction data of the genesis block. This is because the genesis block was not processed like every new block so it's data never made it into the UTXO database. Because it was never part of the UTXO database, it affects consensus so this bug cannot be fixed without a hard fork.
Fast forward to today and the genesis block is still not processed like other blocks in order to keep UTXO databases consistent so there is not a hard fork. This also means that the transaction in the genesis block won't be part of any databases, including the transaction index, which is why you cannot look up that transaction. Fixing this so that the transaction were added to the transaction index would require significant changes to fix this one special case as the block cannot be processed or it may cause a hard fork.
Instead of trying to query the transaction, you should use getblock using verbosity level 2. This will decode the block even further to give you the transactions decoded instead of just their transaction ids. Since the block itself is known and in the block index, the block can be fetched and decoded so yo ucan get the transaction data that way. In fact, I would recommend that you always use getblock with verbosity 2 so you can get the block data and all of the transaction data decoded with one RPC instead of needing multiple to fetch each transaction in a block.


text:
bitcoin-cli -netinfo not showing incoming ipv4 peers
I was trying to get my bitcoin node to be able to receive ipv4 peers for couple of days, but could not see any incoming peers even tho my port 8333 was open and reachable and to my best knowledge bitcoin.conf is correct.
Today I have spin up another node and used addnode=mainnodeip to see whether I can connect to my main node. Connection out went fine, data is being received, but still in bitcoin-cli -netinfo of my main node I don't see this connection.Is this a bug?
I can see the outbound connection on my testing node, but not inbound in my main node.
Thank you for any tips or explanation.

I think you probably connected to your other node over the local network? In that case, this issue has just been corrected in the master branch a couple of weeks ago (https://github.com/bitcoin/bitcoin/pull/26584) - so that this should be fixed with the next 25.0 release.
In the meantime, you could use bitcoin-cli getpeerinfo as an alternative, which doesn't have this problem.

Thank you foe help. It was not on a local network, but I did try 'bitcoin-cli getpeerinfo' to examine the peers close. I can see quite a few inbound peer which have "network": "not_publicly_routable" which seem odd to me. What would this mean?

That means that bitcoin core thinks that the address (field "addr" in getpeerinfo) with which they connect to you is not publicly routable on the internet.


text:
How to send coinpot to coinbase
Can I send my crytocurrency in coinpot bitcoincore bitcoincash, mooncash, ect to my coinbase wallet?
How is this done?

I have never heard of CoinPot However, if you're referring to the cryptocurrency exchange Coinbase, as of November 2018 it is only possible to store the following coins:

Bitcoin
Bitcoin Cash
Ethereum
Ethereum Classic
Litecoin
USDC
Basic Attention Token
0x

This may be different depending on your location (country), use the chart provided to confirm.
Coinbase makes it fairly easy to receive coins, simply press "Receive" under the preferred coin and submit that address in CoinPot's withdraw implementation (You may need to obtain documentation or contact them for instructions on how to do this).


text:
Start and end parameters in historical price data request are ignored
I trying to do some testing on historical coinbase data. Because I can only get 300 datapoints per request. Im looping the request and change the start and end paramter to got backwards.
My requests now look like this:
https://api.pro.coinbase.com/products/BTC-EUR/candles?granularity=60&start=2018-11-09T17:11:08Z&end=2018-11-09T18:11:08Z
AFAIK they are ISO 8601 formatted and the time difference between start and end is correct.
However, im getting not 60 points but 350, so the end date is ignored and the start date also changes whenever I reload the link.
Can someone shine some light on how to correctly do the request for 1 hour of data?

The coinbase API docs say:

If data points are readily available, your response may contain as
  many as 300 candles and some of those candles may precede your
  declared start value.

So it looks like you need to parse and remove the extra data if you don't need it.

@jbaczuk possible but that would be very inefficient.
but i just noticed something. im in utc+1 so my datetime.datetime.now() produces timestamps that are in the future when looking from utc.
so when i set my timestamp back 1 hour i get correct requests
this was produced at 22:05 local time
https://api.pro.coinbase.com/products/BTC-EUR/candles?granularity=60&start=2018-11-09T20:05:54&end=2018-11-09T21:05:54 and it should display correctly


text:
Why are most Bitcoin payment invoices time limited ?
Most bitcoin payment gateways issue time-limited payment invoices. Why is that ? AFAIK, the address stays valid even after the timer is out. For instance when sending a transaction from wallet to wallet, even if I send to that address after the 15 minutes, the recipient still gets their money. I have tried this with at least 3 wallets. In this case, what's the timer for in the first place if the address is still linked to that user ?
Thanks.

To add to Raghav Sood's answer above, beyond price volatility most of the generated addresses are "1 and done". Not only do they not want the price to change, they don't want to continue to watch addresses forever. They create a wallet address for that single deposit. They don't advertise an address to multiple users.
"But when i send money later, in some cases way later, they send it back."
They don't stop watching the address for some time after. A day, a week. It's the type of watching they get notified if something arrives in that wallet. Eventually every address is usually relegated to a "cycle" where instead of actively watching for a transaction, every address ever sent out to a customer get's checked once a day, once a week, etc. for any new deposits. This makes sure if a customer accidentally sent something later on, or had little gas in the original transaction, whatever the reason resulted in the transaction being severely delayed, the system will detect it and automatically return it without requiring customer support intervention.
Obviously every crypto processor can and is different, this seems to be the most common practice at the moment.

I upvoted you but my reputation doesn't allow it to be publicly displayed. Thank you.

Most invoices are timed to ensure the price of bitcoin (or any crypto asset) does not move too much.
Although Bitcoin is usable as a currency, it's current volatility is somewhat undesirable. Timed invoices are used to ensure that merchants get a roughly expected $ value.

Thank you. I can't upvote you as my reputation is too low for it to be publicly displayed.


text:
Is there a limit to the number of Bitcoin addresses?
Is there a limit to the number of Bitcoin addresses?
And if so, what stops someone from making all these addresses and holding the private keys for them so no one else can make a new public key?

Is there a limit to the number of Bitcoin addresses?

If I understand it correctly, there can never be more than 1461501637330902918203684832716283019655932542976 of the current type of addresses. 2160.

what stops someone from making all these addresses and holding the private keys for them ...

Probably:
There aren't enough atoms in the universe to make a big enough computer.
There isn't enough time left in the universe before those atoms cease to exist.

..so no one else can make a new public key?

Other than the improbability of it occurring, there's nothing in the Bitcoin protocols or concensus rules that would prevent two or more people independently generating the same addresses. Any of those people could then spend any money sent to that address.
Which is to say, your bad-actor can't prevent anyone from generating an private-key a public-key or an address.

It may be worth mentioning that holding the private key to an address does not prohibit another user from generating the same address.

@Murch: Good point, answer amended accordingly.

Physics nitpick: "There isn't enough time left in the universe before those atoms cease to exist", the most-accepted physical theories postulate a heat-death of the universe, which does not include a deconstruction of atomic matter. Heat-death instead describes the universe reaching a state of thermodynamic equilibrium, which implies no further work may be performed by exploiting entropic differences between different localities of matter. But in either case, your conclusion is right, we won't be able to calculate all possible addresses before that time comes :)

One would have to flip a coin 160 times. Get the same 1 or zero 160 times IN ORDER to succeed. To get the same address. Is this close?

This does not answer the question. Brute forcing all possible HASH160s will still not allow you to take over the address, since you require a private key, which is 256 bits.


text:
Is it possible to withdraw other cryptocurrencies besides bitcoin (ex: etherum) into a Bitcoin paper wallet?
I've been wanting to know if withdrawing other cryptocurrencies into a bitcoin paper wallet would be incompatible with that system.  I haven't tried it myself.

It may work, depending on the currency.
You will likely be able to send BCH to a BTC paper wallet, and LTC to a BTC paper wallet with a 3-address, due to address format overlaps.
You will not be able to send currencies with other address formats, such as Ethereum, Monero, ZCash, etc.
Do note that even if you do succeed in sending the currency, there is no guarantee that you will be able to spend it. For example, sending BCH to a BTC segwit address will work, but spending it will be extremely hard, as segwit is not enabled on the BCH network.


text:
How do brc20 wallets query the chain?
I'm having a look over OrdPay Wallet which is an extension wallet for interacting with ordinals on the bitcoin network. How can sites like these query the bitcoin ordinal chain and see that I have an ordinal inside my wallet?
I come from an EVM industry where it's super easy to check NFTs on the explorer, but not so with ordinals. Can someone explain?

please reference: https://www.youtube.com/watch?v=596InlNtfD0

I’m voting to close this question because BRC20 is a notably broken design that was initiated by Craig Wright a notably anti-Bitcoin character

It appears that you reference "BRC20" to a non-standard or less well-known token standard. However, here's the general way information on Bitcoin-based wallets interact with the Bitcoin blockchain.
Bitcoin wallets, including those used by services like OrdPay, query the Bitcoin blockchain generally by:

Connect to a Bitcoin node: Bitcoin wallets connect to Bitcoin nodes, which are computers running the Bitcoin client software and maintaining a copy of the entire blockchain. The wallet can connect to a local node or use a remote node via an API.

Send requests to the Bitcoin node: The wallet sends requests to the connected Bitcoin node using the appropriate protocol or API. The most common protocol used is JSON-RPC, similar to Ethereum. However, Bitcoin also supports other protocols like REST or WebSocket-based APIs.

Craft the request: To query the Bitcoin blockchain, the wallet constructs a request specifying the desired information. For example, to check the balance of a specific address, the wallet can use the getaddressinfo or getreceivedbyaddress method, providing the Bitcoin address as a parameter.

Send the request: The wallet sends the request to the Bitcoin node over the chosen protocol (e.g., JSON-RPC). The node processes the request and retrieves the requested information from the blockchain.

Receive and process the response: The wallet receives the response from the Bitcoin node, containing the queried data, such as the address balance or transaction history. The wallet then parses and processes the response to extract the relevant information.

Display the queried data: Once the wallet has the necessary information, it can display it to the user, such as the Bitcoin balance or transaction details associated with the queried address.

Regarding OrdPay or similar services, it's important to note that "ordinal" is not a recognized term in the context of cryptocurrencies or blockchain technology. If you meant "Bitcoin" instead, these services typically query the Bitcoin blockchain by interacting with Bitcoin nodes, as explained above, to verify and retrieve transaction details associated with your wallet address.
Please provide additional clarification if "ordinal" refers to something specific that I may not be aware of, so I can provide more accurate information.


text:
How does bitcoin broadcast information?
On Bitcoin's Blockchain, how is information transmitted instantly to all other nodes and do nodes 'talk to each other' through an API?
Do Blockchain nodes communicate with each other through HTTP requests? If yes,
do they use a Pub/Sub to transmit information to all the nodes? Or is there a delay until the full blockchain information reaches all nodes?

On Bitcoin's Blockchain, how is information transmitted instantly to all other nodes and do nodes 'talk to each other' through an API?

Information is not instantly transmitted. It takes time, nothing is instant.
The Bitcoin network has a network protocol which nodes using it speak. This network protocol allows a node to send and receive data to and from a node that it is connected to. A node will connect to multiple other nodes on the network.
This network protocol uses TCP connections and Bitcoin specific network messages.

Do Blockchain nodes communicate with each other through HTTP requests?

No. That would be inefficient.

Or is there a delay until the full blockchain information reaches all nodes?

Of course there is a delay, the speed of light is only so fast. Data takes time to transmit due to the capabilities of physical connections and the distances that information has to travel. There is always a latency due to physics. Furthermore, Bitcoin nodes will have random delays between each of their announcements of transactions in order to better preserve privacy.

Thanks for clarification. It makes more sense now! I wasn't aware at all of Bitcoin's communication protocol but I do understand it now.


text:
How profitable is mining with a ~1GH/s miner?
I'm very new to bitcoin mining, so I just tried it out on my mac using MinerGate. I made about 0.000028 XMR in 7 minutes running at 200H/s, equating to $0.0008. I figured that at that rate of money flow, I could make around $9.7/sec with just a 1GH/s speed. This does not seem very possible at all. So where's the poop?

200H/s seems insanely low for a normal PC, how did you arrive at that figure?

@MeshCollider: Note that this is for Monero (XMR), which uses the CryptoNight hash algorithm.  200 hash/sec for a CPU seems to match other reports.  I think the real question is: where do you get a 1 GH/s CryptoNight miner, and how much would it cost?  OP should be careful not to confuse these with miners for other algorithms like SHA256 or scrypt, which are neither compatible nor comparable in terms of hash rate.

Ah yes sorry, I was doing exactly that and confusing it with what I'd expect from sha256. Thanks @Nate for pointing that out :)

Let's say I wanted to use Antminer S7. How many H/s would I get mining Monero with it?

And, why is the calculated value/time so high?

@SergeyBrin: Zero. The S7 is a SHA256 miner, and Monero uses CryptoNight, as Nate already explained above.

Minergate is not by any means an effecient way to mine alt-coins. If you want to mine Monero XMR, you need to download either the source; and compile a GPU Miner, and configure it to mine off one of the many pools; and do the same for a CPU Miner; that plays nice with your GPU miner.
Claymore's GPU and CPU miner are widely adopted and used, I am not sure if they work on Macs however.
You can visit the bitcointalk.org thread for Monero; and get all the information you need on the OP Thread Post including links to miners; pools, exchanges, etc.
But in closing; XMR is trading very high right now. I mined XMR two years ago and accumulated a lot of coins... this was when BTC was at 400-600 and XMR was 1/15th the current price. Across my systems; I was mining 10-20 XMR a day. But that was 2 years ago and difficulty is drastically higher now.
HERE IS A LINK TO CPU / GPU BENCHMARKS FOR MINING CRYPTONIGHT ALGORITHM COINS
http://monerobenchmarks.info/
HERE IS A LINK TO THE THREAD ON BITCOINTALK WHERE YOU CAN GET STARTED
https://bitcointalk.org/index.php?topic=583449.0
In closing, you may want to look at AEON, which uses a forked version of Cryptonight, called Cryptonight-Light. It hashes at much higher rates. The coin seems to be in a bit of an unstable state development wise; issues with the new wallet release; etc, but in my experience mining the most profitable coin - at the moment - is not always the best strategy.
The key is finding the lower difficulty coins that you can mine now at a loss; that will 10x or 20x in value 12 months ahead. Finding these coins is the hard part; but that's where the money is.

Thank you for the answer! I'm thinking of purchasing an ASIC miner though (like antminer). Which software and servers should I use and for which coins?

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


text:
Can I use lightning for ERC-20 (Ethereum coins)
Just finished setting up my lightnig node. It is awesome!! Does anybody knows an implementation or documentation that explains how to make it work on rinkeby or ethereum mainnet?

Maybe this question is a better fit for ethereum's stackexchange?

Short answer there is non.
The Ethereum people have tried to create the Raiden Network which is supposed to be their offchain solution. As far as I know (thought not 100% certain) They use ERC-20 tokens to create payment channels but the network cannot transfer ERC-20 tokens. The Lightning Network Protocol itself is currently only designed to transfer an amount of currency.
One of the reasons is that the onions of the transport layer are limited in size.
If you are interested in transfering smart contracts or tokens you might want to look at the RGB Project by BHB Networks. This group tries to create colored coins (which are basically tokens) on top of bitcoin in a way that this is compatible with the Lightning Network. However this is work in progress and will - according to one of the main developers - take probably years before it is ready to use.


text:
Serialized transaction bigger than the actual transaction object? CVE-2013-4627
I'm surveying old Bitcoin DoS vectors and came across CVE-2013-4267, for which there appears to be little public information available. This thread should shed some light on this CVE.
There's a description in this blog post:

Transactions are also first deserialized in order to be parsed, but they are stored “as is” in a temporary cache called MapRelay, and forwarded without being serialized again. I really don’t know why this is done. But the point is that the storage of messages as they are received leads to the possibility that an attacker creates messages much bigger than the actual transaction object contained, which, when stored in MapRelay memory, can be used to exhaust the memory of a node.

There is also this relevant thread which appears to say the network was under attack using this vector.
Based on the transaction serialization and deserialization code in ~v0.8.2, it looks like the attack may have been: add large amount of random data at the end of a valid serialized transaction. The deserializer finds what it looks for (the valid blob prefix), but appears to ignore what comes after. If a serialized transaction with random data at the end of the transaction is sent to the victim node, it will be deserialized, passed to the mem-pool and then placed in mapRelay in its full size (and then possibly forwarded further, which seems like a pretty powerful attack vector).
So: was the attack described by CVE-2013-4267 based on adding random data at the end of (valid) serialized transaction data?

Yes. The attack was adding junk to the end of otherwise valid transactions to cause the junk to get relayed around. (as an aside, if we hadn't fixed that, segwit would have been easier to deploy...)

Interesting. Was it (in hindsight) fixed in a bad way, too rigid perhaps? Would a less hastily fix perhaps allowed for more forward-compatible flexibility?

Well, any fix was going to have to refuse to relay data that couldn't be validated.


text:
Entropy gathering from already generated bitcoin keys?
Say someone has generated n bitcoins. Now, these are from very good entropy. When regenerating new keys, would it be a good idea to take the keys for entropy improvement? On the one hand, the entropy is already destinated on the other hand, it comes from the best sources? As special case, would talking only parts of it be a better idea?

from: https://stackoverflow.com/questions/53238202/entropy-gathering-from-already-generated-bitcoin-keys

Welcome to Bitcoin.stackexchange. I am having trouble understanding your question. When you write "n bitcoins" and "new keys" do you mean "bitcoin keys" in both cases? What do you mean by "destinated"? Why do you write that the entropy comes from the best sources?

In basic terms, entropy is good when it is secret and not good when it is known to the attacker or guessable.
Adding the keys would not improve your already existing entropy (although they wouldn't worsen it either). They are just derived from that entropy, so an attacker who breaks your "very good entropy" can just compute those keys. He can also just compute the required parts.
If you have "very good entropy", just use that for how ever many keys you want. Any decent PRNG should have a sufficiently long period until it starts repeating.


text:
SPV clients querying the full node
Is there a way currently where an SPV client can send a TxID to a full node which is present in the UTXO set of the full node and have the full node not scan its entire blockchain to fetch the transaction data? Or under all the circumstances, the full node would always scan the entire blockchain to fetch the data?
Also, do the full nodes along with the transaction data also return the merkle proof to prove the validity of the data returned? I mean, how can an SPV node be convinced that the correct data has been returned?

Is there a way currently where an SPV client can send a TxID to a full node which is present in the UTXO set of the full node and have the full node not scan its entire blockchain to fetch the transaction data? Or under all the circumstances, the full node would always scan the entire blockchain to fetch the data?

A full node never scans the entire blockchain for a particular transaction to send to a SPV client. No client (SPV or not) can just request transactions that are in the blockchain; a node will not respond to such a request because it is computationally expensive (requires scanning the blockchain).
A SPV client can set a bloom filter which will filter for specific outputs and txids, and then request blocks from a full node. The node will send a filtered block to the SPV client then.
So no, a SPV client can't send a txid to a full node and get the transaction if it is already confirmed.
For SPV clients that use a client server model like electrum, the server is a full node which has indexed every single transaction in the blockchain (it maintains a database which maps txids to locations on disk). Those servers will respond to requests for specific txids, but they are not your typical full node and speak a different protocol.

Also, do the full nodes along with the transaction data also return the merkle proof to prove the validity of the data returned? I mean, how can an SPV node be convinced that the correct data has been returned?

Merkle proofs are provided by the nodes to prove that the transaction is in the block.

But don't the full nodes (as mentioned in link post) with -txindex flag set also maintain an index that maps TxID to some information that lets them  retrieve transaction data efficiently. Wouldn't the full nodes, in this case, retrieve transaction data for SPV client queries on TxID?

No. While -txindex allows nodes to maintain a transaction index, this data is only exposed locally to the RPC interface. It is not used for node operations. Nodes with txindex are functionally the same as those without and are not distinguishable from those without txindex without access to the RPC interface.


text:
Custom transaction IDs
I understand that TxIDs are simply the double hash of tx data. But who creates them? I assume that all the nodes create the TXIDs of the transactions on their own and the TxIDs are not transferred along with the tx data. I am asking this because I want to create custom TxIDs (for some application) for the Txs and do not want the IDs to be double hash of the tx data. Is it possible to do so, or would the nodes then reject my tx.

You cannot do that.
The txid is not "chosen"; it is defined as the double-SHA256 of the transaction data (excluding the witness, when it is a segwit transactio ). Every node computes the txid independently.

Also worth mentioning -- All nodes will produce the same TXid as long as the transaction isn't "malleable". Same input in a hash function will always produce the same result. Custom/vanity TXids are technically possible if you brute force an OP_RETURN output but naturally can only contain A-F and 0-9.


text:
i found bitcoin wallet I need qr private key where i can get that code?
i found bitcoin wallet I need qr private key where i can get that code ?
Is it impossible to get qr private code ?

I need qr private key

QR codes are a 2D barcode typically used by cryptocurrency wallets to present a payment-address which someone else uses to send you payment. They are also sometimes used when printing a private-key as a paper wallet.

where i can get that code?

Non-custodial wallets generally provide a means to extract the private-key. For example with Bitcoin-core you can use the CLI command dumpprivkey
Most wallets are protected by a pass-phrase. If you don't know the pass-phrase, and can't guess it, you cannot extract the private-key.

If you believe the private-key was printed in QR-barcode form as a paper-wallet it will obviously be wherever the owner put it - we can't really help with that.

Found wallet
You have no access to the Bitcoins associated with a wallet if you don't have the wallet's passphrase and dont have the private-key and don't know where it is in printed form and don't know a seed-phrase used to generate the private keys.

Converting a private-key from text to QR-code
If you have full-access to the wallet you found and want to convert it to a paper wallet in QR-code form - you'll need the wallet to support that or export the private key in other form (e.g. WIF) and then import it into software (perhaps a different wallet) that has the features you need.
For those comfortable with programming, I've seen people suggest downloading the HTML from, say, https://www.bitaddress.org and running that on a disconnected PC. It looks like client-side Javascript and can generate QR-codes from a known private-key with some modification. The Javascript libraries used appear to be open-source so can be obtained from the usual repositories.

People do sometimes use QR codes for private keys; e.g. this is a common way to have a paper wallet.

@Nate: Thanks, I'll delete that part of my answer

The private key was originally used to generate the address.  So, you have to get the private key from whoever generated the address.  If you generated it, then hopefully it is stored in the software you used.
If you just found an address, or someone gave it to you, then you can't get the private key and cannot use the coins.


text:
Understanding SPV, pruning and its downsides, as well
First of all, sorry by not asking an objective question, it's because I can't resume this one and I didn't find information even in the "mastering bitcoin" book. The large texts in this question are also to help people get in the context of what I'm asking.
Suppose I run a bitcoin client in pruning mode. As I understand, it'll download the entire blockchain, verify that the transactions are well formed, don't spend unexistent outputs, the signatures match, and the hashes of the block match. After that, it'll erase everything and just store the Merkle Trees of each block. I understand how a Merkle Tree works, it's a structure made of hashes of transaction IDs. Given a transaction and its merkle path, I can verify if the transaction is in the block or not.
If I just accept blocks from the network but did not previously verify the blockchain, I could be fooled to verify that a transaction is in the mined block, but I would not be able to verify if the transaction is well formed, if it spends unspent outputs, etc. So that's why the entire blockchain must be downloaded and verified before. (even though, it's unlikely that someone would waste hashpower to mine a block with an invalid input, but of course if we rely on unlikely, it would open a port for this possibility).
So, as I understand, an SPV client just receives the latest merkle root of the latest block and verify if a transaction is in it. It then see that very much hashpower was wasted on that block, and then assumes that it should be a valid block. Am I right?
In pruning mode, however, the entire blockchain is downloaded, verified, and then pruned. Now, the client just downloads new blocks, verifies them, and prunes them. As I've read, however, in pruning mode, the client maintains the latest x blocks for some reason. Why?
Also, if I have the entire blockchain in pruned mode, that is, a blockchain made of only merkle trees, given a new transaction and its merkle path, I can verify that it's in some block and I know that this block is valid because I validated it before pruning. However, how do I know that this transaction spends an unspent input? Do I need to ask for the merkle path of the referenced transaction and keep doing that?
In the current model in my head, I don't see how a pruning node could be fooled. Is the only downside of pruning nodes that they don't help the network very much? Because they can't provide merkle paths for those who ask, etc. But if I receive a transaction and I am a pruning client, can I have the same confidence as a full node that I'm not being fooled?
Is there any other disavantage of pruning that I don't know? I'm asking because I'm verfy intersted in this model and I want to run a pruning client.

there's no pruning while operating in SPV mode afaik.

@renlord yes. In SPV, you just download the block header, see that it has a lot of hashpower in it by examining the hash, and then you get a transaction and see that it's included in the merkle tree, right? No pruning

So, as I understand, an SPV client just receives the latest merkle root of the latest block and verify if a transaction is in it. It then see that very much hashpower was wasted on that block, and then assumes that it should be a valid block. Am I right?

No. A SPV client submits a bloom filter to a full node providing SPV services. Each time a block header is sent to you, a full node will check against said bloom filter is transactions that you may or may not be interested is in the block.
If yes, then said transactions will be included, including all other transactions required to compute the Merkle Root. Otherwise, you just receive a block header with no transactions whatsoever. For each block header received, your SPV client will check if it contains a proof of work solution that meets the difficulty requirement and if it is linked to the previous block (as usual).

In pruning mode, however, the entire blockchain is downloaded, verified, and then pruned. Now, the client just downloads new blocks, verifies them, and prunes them. As I've read, however, in pruning mode, the client maintains the latest x blocks for some reason. Why?

I assume you are talking in terms of a full node, since SPV nodes do not download the blockchain at all and there's nothing to prune.
The reason why the last N blocks are kept is so that when a re-organisation takes place, it is possible to systematically undo transactions that led to the current UTXO set which is based off an orphaned chain. You then undo to the point where the new succeeding chain begins and apply transactions recorded in the new chain. Without the last N blocks, there's no way to un-wind when chain re-org takes place, then to re-derive the UTXO independently requires a full download of the blockchain.

Also, if I have the entire blockchain in pruned mode, that is, a blockchain made of only merkle trees, given a new transaction and its merkle path, I can verify that it's in some block and I know that this block is valid because I validated it before pruning. However, how do I know that this transaction spends an unspent input? Do I need to ask for the merkle path of the referenced transaction and keep doing that?

I think you are confused here. While operating a full node in prune mode, your node will download every block and perform full validation. Each transaction that gets processed will update the UTXO set that is cached on your node. Therefore, you will know if transactions are spending valid UTXOs or not.

So in pruning mode it'll download the entire blockchain, prune all the transactions that were already spent (pruning means deleting or just saving the merkle tree?), keeping just the ones unspent, so it can check the validity of all new transactions, right? So the only difference of pruning mode vs full mode is that pruning won't helo by providing transactions to the network that were already spent, so new nodes would not be able to download the blockchain to verify it, right?

No merkle tree is being saved in prune mode. The merkle root hash is stored in the block header and the merkle tree is only useful during validation of a block. Yes, prune mode keeps a set of unspent transaction outputs to verify new incoming transactions. Yes, full nodes running in prune mode wont be able to serve historical blocks to other peers.

but is this the only downside of pruning mode?

Yes. There's no other downside to pruning mode other than you not being able to serve historical blocks

bitcoin has an orphaning rate of 0.5% due to competition in mining. Thus, keeping the last N block is a conservative method to prevent extra work as stated in the previous answer.


text:
Verifying a P2SH transaction script by hand. How should I concatenate OP CODES in order to hash the script?
I'm reading this:

Transaction
  40eee3ae1760e3a8532263678cdf64569e6ad06abc133af64f735e52562bccc8 paid
  to P2SH address 3P14159f73E4gFr7JterCCQh9QjiTjiZrG. You can see the
  redeem script in transaction
  7edb32d4ffd7a385b763c7a8e56b6358bcd729e747290624e18acdbe6209fc45 which
  spends that output, using OP_FALSE  { OP_1  OP_1
  OP_CHECKMULTISIG }.

from https://en.bitcoin.it/wiki/Pay_to_script_hash
I'm trying to check the validity of the transactions by hand to see if I understand what's happening. I first found the first transaction: https://blockchain.info/tx/40eee3ae1760e3a8532263678cdf64569e6ad06abc133af64f735e52562bccc8
As I understood, it is locking these outputs to the output script
OP_HASH160 e9c3dd0c07aac76179ebc76a6c78d4d67c6c160a OP_EQUAL

The text tells me to look at the other transaction: https://blockchain.info/tx/7edb32d4ffd7a385b763c7a8e56b6358bcd729e747290624e18acdbe6209fc45
which spends this output. It means that this transaction presents a script (with data) that satisfies OP_HASH160 e9c3dd0c07aac76179ebc76a6c78d4d67c6c160a OP_EQUAL. Let's see the input of this transaction:
OP_FALSE 3045022100ad0851c69dd756b45190b5a8e97cb4ac3c2b0fa2f2aae23aed6ca97ab33bf88302200b248593abc1259512793e7dea61036c601775ebb23640a0120b0dba2c34b79001 5141042f90074d7a5bf30c72cf3a8dfd1381bdbd30407010e878f3a11269d5f74a58788505cdca22ea6eab7cfb40dc0e07aba200424ab0d79122a653ad0c7ec9896bdf51ae

I should take the OP_HASH160 of this to verify it's equal to e9c3dd0c07aac76179ebc76a6c78d4d67c6c160a, right? Remember that OP_HASH160 means: ripemd160(sha256(something)). Should I concatenate that OP_FALSE int he beggining? Also, shouldn't it be a script? Where are the other op_codes beasides OP_FALSE?

https://webbtc.com/script/7edb32d4ffd7a385b763c7a8e56b6358bcd729e747290624e18acdbe6209fc45:0

You can find the execution of a similar pay to script hash (P2SH) transaction here:
Pay to Script Hash Execution
Basically the scriptSig is evaluated first, it pushes an empty array of bytes onto the stack because of the OP_FALSE code, and then pushes the signature 3045....001 onto the stack, and finally pushes the redemption script 5141...1ae on. Then we move on to the scriptPubKey evaluation, the encoded redemption script is taken off the stack and hashed, and the hash is compared to the hash e9c3...60a. if these are equal, we move on to the actual evaluation of the redemption script. This means the stack is taken back to the point before the scriptPubKey execution, so we have:
 5141...1ae
 3045....001
 (empty value)

The top element is popped off, decoded, and then evaluated. In this case, it is a OP_CHECKMULTISIG script, the decoded version is on the webpage you linked as well as in your question, but this multisig only has one public key and one signature, so it's basically equivalent to paying straight to that one address. The OP_CHECKMULTISIG will check the signature 3045...001 against the public key, and if it matches, the transaction is valid. The empty data pushed on at the start by OP_FALSE is simply there due to CHECKMULTISIG taking one more element off than it needs, due to a bug, so it's just an unused bit of data needed to make it work.
I'm not sure what you mean by it being a script. It is a script, it is just encoded in the 5141...1ae. You can decode it with the decodescript call on bitcoin RPC.

Isn't there any block explorer that shows me the script? I don't have these command line tools to decode the script

https://chainquery.com/bitcoin-api/decodescript


text:
wallet.dat from 2014 shown as empty with latest client 0.18
I have bitcoin wallet from 2014. I have saved it encrypted.
Since then I haven't checked it, until now.
I did sync the whole bitcoin block-chain and when copy my wallet.dat and re-scan wit the client, the wallet got shown as empty. My wallet.dat is 88kb.
Bitcon core Client dump of the wallet shows addresses only from 2019 and wallet keys dump from the client returns error.
Any help is appreciated.

which platform are you on?

Windows 10 Professional.
My wallet originally was saved as file not encrypted. So the client do not need password to read it.

how did you ensure you found the correct data directory?

wallallet.dat resides in the client's exe folder.
In 2014 I did try to copy out wallet.dat and then remove it back. So the client did show 0 and xx bitcoins respectively.
Now when i sync the whole block chain and  copy my wallet.dat from 2014 into client's exe folder my balance is 0, seems like no wallet at all.
So I wonder why ?

You can't swap out wallets without doing a rescan, AFAIK. Bitcoin Core minimizes space usage and doesn't store histories for addresses it doesn't control. So even though all the blockchain is synced, you'd need to restart with a rescan parameter to scan the blockchain with the wallet that you have placed there.

I did sync the whole block-chain and then did copy my wallet.dat into client's exe folder and  did restart the client with -rescan option. So after the re scan the client still shows zero in my wallet wallet balance.

Did you resolve this issue for yourself? If not, please do the following. First remove save your wallet.dat file into another folder on your pc. Second remove BTC Core entirely from your pc and restart the pc. Finally, reinstall BTC Core onto the pc. Go into the wallet directory, rename new wallet.dat which is created. Place backup wallet.dat file here. Restart BTC Core client and let it rescan the network. This will fix your issue.

I will try this, will give feedback. Thank you.


text:
incorrect passphrase
Here's goes the steps that lead me to a wallet passphrase error:
OS: Mac Mojave (64bits)

Started bitcoin-qt app to sync (long outdated)
While managing to solve disk size errors (external drive), I updated bitcoin-qt to the latest version (18), but not sure what the previous one version was (perhaps 16.0).
As soon sync finished, I choose to encrypt my wallet :(.
I saved my passphrase, as it was created (100% sure!). To make sure it works, I changed the passphrase twice, but making sure the last change was the one I saved previously.
As bitcoin base was huge in my external drive, I set prune mode on (550).
All set, asked to received from my exchange.
Finally, when I tried to send the received amount, bitcoin-qt asked me the wallet passphrase, were I got the wrong passphrase error...
Is the only cause for that the wrong passphrase ? I mean, I'm sure I have typed the right one...

I'm assuming you've already tried caps lock, the intermediate passwords you used etc.
Ideally you would backup your wallet before making changes such that you have a library of them: wallet.dat.1jun2018, wallet.dat.2jul2018 etc. Then if something goes wrong, you already know that the previous copy of the wallet is still available.
I can't tell what's gone wrong for you from your description above, but OSX Mojave does offer some facilities. First, you MUST copy your wallet as it currently stands - even though you don't have the password - to an external disk, date it as above. Then use Time machine even if you haven't been using it to have a look at the folder ~/Library/Application Support/Bitcoin. Mojave stores local backups on your computer "even when your Time Machine backup disk isn't available." You're hoping to see that wallet.dat is available from a date prior to the encryption.
If it is, then you might try restoring it. Also copy it under a new name to your external disk. You might be lucky enough that bitcoin-qt works straight away without the password. If you can restore a previous version but cannot seem to use it, things start to get a lot more tricky, very quickly.
If you don't have the local backups, or the wallet isn't within it, I would turn the computer off and sleep on it. When you get up, write down everything you did, every password you tried, in the hope that something jogs your memory.

Alistair, thanks for your reply.  I found a wallet there, but I'm getting this error "last wallet synchronisation goes beyond pruned data" and say I need to reindex...

1/ That you found a wallet there sounds like good news. I know nothing of your abilities and your set up so my suggestion is that you go back even further in the time machine and recover the wallet file from further and further back, copying them under an appropriate name to your external disk.

2/ I would then suggest not that you fix the current install, but rather create a new user (much better if this can be on a second machine), and install v16 to that - then copy successively older wallets to there instead. By this means is it left open to have specialist recovery services examine the original install.

Can't download 0.16 from an official source: https://bitcoincore.org/bin/bitcoin-core-0.16.0/   That's frustrating...

You want https://bitcoincore.org/bin/bitcoin-core-0.16.3/


text:
How secure is it to upgrade bitcoind?
The release notes of bitcoin-core suggest to just copy the bitcoind file, which appears on my system (Raspbian Butch) in /usr/local/bin.
Since I built from source using ./configure I wonder how this will influence my node. Is bitcoind really the only thing that gets changed with a new release?

Although certain releases perform database upgrades, the upgrade is handled by the bitcoind binary - updating a node only requires changing the binary, regardless of whether you downloaded a prebuilt one or compiled it from source.
If any additional changes to the bitcoin data are required, the updated bitcoind will perform them when it starts.
If you are downloading a prebuilt binary, make sure you get it from a reliable source (such as bitcoin.org) and verify the signatures to make sure it has not been tampered with.


text:
I just compiled bitcoind and run for the first time. Do I already have a private key?
Since I have a wallet.dat I suspect I already have a private key and so I could extract it for backup purpose (on paper).
How do I do it via terminal with bitcoin-cli?

Bitcoin Core will automatically create a new wallet on first start. This wallet will contain 2000 private keys (unless otherwise specified by the -keypool=<n> option) and the seed used to generate those and future keys, at least until you encrypt the wallet.
As such, there is not just one private key that you need to backup, rather you need to backup 2000 keys and the seed. Otherwise, restoring a backup will not restore all of your private keys.
The easiest way to backup your wallet is to just copy the wallet.dat file to a safe place. I would not recommend that you try to create a paper backup of your wallet.
If you insist on a paper backup, then you should record the seed. The seed can only be gotten by using the dumpwallet RPC command and then finding the private key labeled hdseed. The seed is a private key and cannot be used in any other wallet software since they do not accept the seed as a private key. You will need to remember that it specifically is not just a normal private key and that it only works in Bitcoin Core. To restore the seed, you can use the sethdseed command in a new wallet.
I really don't recommend that you try to backup the seed. There are changes happening to the Bitcoin Core wallet soon that may make your seed backup unable to work. The recommended way of backing up is to copy the wallet.dat file, and to do so periodically. This will guarantee that you have your private keys, guarantee that it is compatible with future versions of Core, and also backup transactions and metadata (such as labels).

Thanks for your comprehensive answer! I added my output as an answer, also. I wonder if the extended private key should be sufficient to recover all child keys. I recognise that xprv leads to a specific way of generation. But as long as someone uses exactly this method it should be possible to generate all the keys, right? I am doing this to investigate, not to backup a real wallet. Although I think backing up something physically on a paper might be a good thing!

Bitcoin Core doesn't allow imports of xprvs due to the internal structure not supporting it. So that is not a good way to backup your wallet. The main thing that will cause issues with restoring backups, especially with different wallet software, is the derivation paths. Bitcoin Core uses a derivation path that isn't used by any other software.

Based upon the good answer by Andrew I want to discuss my output from bitcoin-cli dumpwallet dump.txt because I think this will be interesting for people who are at the same stage as me.
cat dump.txt shows:
# Wallet dump created by Bitcoin v0.18.99.0-12fd4bbd1
# * Created on 2019-09-25T16:04:01Z
# * Best block at time of backup was 409484 (000000000000000000bec614513591c2e5d96a488c2513396e7a723bbf7b1dcd),
#   mined on 2016-04-29T22:30:07Z

# extended private masterkey: xprv*****
...

In my understanding the masterkey is derived from the seed and is used as parent for all child keys. The prefix xprv relates to it beeing hierarchical.
Then there is a list of pairs of private keys with addresses (public keys) of two kinds, reserve=1and script=1. Also, there is one hdseed=1 in the list of reserve=1. All the keys have creation dates with them and hdseed=1 has the earliest time (with others).
K**************** 2019-09-04T14:04:25Z reserve=1 # addr=3********* hdkeypath=*****

hdkeypath is probably a description to get from the masterkey to this specific child key, aka the index. This way all childkeys could be recovered from a known masterkey.
The last part of the dump contains several lines like this
0014******* 0 script=1 # addr=3**************

I am still investigating what 0014 as a starting number means.
This is a list of address prefixes.

The seed can also be encoded in easy to remember (and written) words with bx hd-mnemonic < SEED.

The prefix 0014 is the bytes native P2WPKH scripts start with.


text:
What different options are there to start bitcoin on command line?
I had troubles with my client on a Raspberry because it was using the wrong configuration file and I could not find any entry in the configuration file that referred to the right location of the data directory, but I knew it was beeing used correctly in the past.
I was trying to use -printtoconsole to debug the problem but that did also not work.

On command line bitcoin can be started in several ways
bitcoind starts a process with the current user. This way the home directory of this user will be searched for a config file and will be used as data directory as default.
service bitcoin start will use the startup script /etc/systemd/system/bitcoind.service. This might contain a link to a configuration file. In my case this config file did not contain of a data directory which I found troubling. But the solution is that it contains a user. This user's home directory is then automatically referred to.
So, in my case I was using the terminal as user pi and had to start the process as user bitcoin instead. This can be done by
sudo runuser -l bitcoin -c 'bitcoind'


text:
When installing libbitcoin there are checks of the code, why is this?
When installing libbitcoin from here with $ ./install.sh --prefix=/home/me/myprefix --build-boost --disable-shared after most of the compilation is done there seem to be checks of the sourcecode with warnings like thise one:
In file included from ./include/bitcoin/bitcoin/machine/operation.hpp:159:0,
                 from ./include/bitcoin/bitcoin/chain/script.hpp:31,
                 from ./include/bitcoin/bitcoin/chain/output.hpp:28,
                 from ./include/bitcoin/bitcoin/chain/output_point.hpp:25,
                 from ./include/bitcoin/bitcoin/chain/input.hpp:27,
                 from ./include/bitcoin/bitcoin/chain/transaction.hpp:30,
                 from ./include/bitcoin/bitcoin/chain/block.hpp:31,
                 from ./include/bitcoin/bitcoin.hpp:24,
                 from test/chain/transaction.cpp:20:
./include/bitcoin/bitcoin/impl/machine/operation.ipp:136:15: warning: ‘size_t libbitcoin::machine::variable_uint_size(uint64_t)’ defined but not used [-Wunused-function]
 static size_t variable_uint_size(uint64_t value)
               ^~~~~~~~~~~~~~~~~~

On my Raspberry Pi 2B this goes on for several hours now. Can someone explain why such a huge amount of tests would be usefull?

These are not tests. They are simply warnings generated by the compiler indicating there may be an issue with the code being compiled.
Most likely, it's just being overzealous and the developers are aware of this.

That message mentions -Wunused-function which is a compiler flag that invokes testing for useless functions that are defined in the source code but not used anywhere in the project. See stackoverflow
It may be that large numbers of these warnings arise for the ARM hardware architecture but not for x86 or x86-64 hardware architectures because of conditional compilation directives or for some similar reason.
You could probably disable -Wunused-function in the configuration file.


text:
How to convert a python example with getinfo to a usable function?
From Antonopoulos' book I try to use the example 3-3 on page 49 which uses a python skript called rpc_example.py to show the usage of the JSON-RPC API:
    from bitcoin.rpc import RawProxy
    p = RawProxy()
    info = p.getinfo()
    print(info['blocks'])

which on $ python rpc_example.py should give 394875.

Of course getinfo has been depricated and I would like to use another function, for example getblock.
I am not sure if I use it correctly or if I have an error in my syntax or if the problem below is due to something related to python.

I already had some troubles installing the library with pip install python-bitcoinlib and also did pip3 install python-bitcoinlib because I was not sure if the problem I now have is related to encoding/decoding in python version 2.

My code now is
from bitcoin.rpc import RawProxy
p = RawProxy()
infoblock = p.getblock()
print(infoblock['difficulty'])

which should print the difficulty of the block, at least in my understanding (I am new to python and to bitcoin).
I get the following error with python 2:
$ python BuchSkripte/49_rpc_example.py
Traceback (most recent call last):
File "BuchSkripte/49_rpc_example.py", line 2, in <module>
    p = RawProxy()
File "/usr/local/lib/python2.7/dist-packages/bitcoin/rpc.py", line 295, in __init__
    **kwargs)
File "/usr/local/lib/python2.7/dist-packages/bitcoin/rpc.py", line 159,
in __init__
    if '#' in line:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128)

With python3 I get:
$ python3 BuchSkripte/49_rpc_example.py
Traceback (most recent call last):
  File "BuchSkripte/49_rpc_example.py", line 3, in <module>
    infoblock = p.getblock()
  File "/usr/local/lib/python3.5/dist-packages/bitcoin/rpc.py", line 306, in <lambda>
    f = lambda *args: self._call(name, *args)
  File "/usr/local/lib/python3.5/dist-packages/bitcoin/rpc.py", line 238, in _call
    raise JSONRPCError(response['error'])
bitcoin.rpc.JSONRPCError: {'code': -1, 'message': 'getblock "blockhash" ( verbosity )\n\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block \'hash\'.\nIf verbosity is 1, returns an Object with information about block <hash>.\nIf verbosity is 2, returns an Object with information about block <hash> and information about each transaction. \n\nArguments:\n1. blockhash    (string, required) The block hash\n2. verbosity    (numeric, optional, default=1) 0 for hex-encoded data, 1 for a json object, and 2 for json object with transaction data\n\nResult (for verbosity = 0):\n"data"             (string) A string that is serialized, hex-encoded data for block \'hash\'.\n\nResult (for verbosity = 1):\n{\n  "hash" : "hash",     (string) the block hash (same as provided)\n  "confirmations" : n,   (numeric) The number of confirmations, or -1 if the block is not on the main chain\n  "size" : n,            (numeric) The block size\n  "strippedsize" : n,    (numeric) The block size excluding witness data\n  "weight" : n           (numeric) The block weight as defined in BIP 141\n  "height" : n,          (numeric) The block height or index\n  "version" : n,         (numeric) The block version\n  "versionHex" : "00000000", (string) The block version formatted in hexadecimal\n  "merkleroot" : "xxxx", (string) The merkle root\n  "tx" : [               (array of string) The transaction ids\n     "transactionid"     (string) The transaction id\n     ,...\n  ],\n  "time" : ttt,          (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n  "mediantime" : ttt,    (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n  "nonce" : n,           (numeric) The nonce\n  "bits" : "1d00ffff", (string) The bits\n  "difficulty" : x.xxx,  (numeric) The difficulty\n  "chainwork" : "xxxx",  (string) Expected number of hashes required to produce the chain up to this block (in hex)\n  "nTx" : n,             (numeric) The number of transactions in the block.\n  "previousblockhash" : "hash",  (string) The hash of the previous block\n  "nextblockhash" : "hash"       (string) The hash of the next block\n}\n\nResult (for verbosity = 2):\n{\n  ...,                     Same output as verbosity = 1.\n  "tx" : [               (array of Objects) The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 "tx" result.\n         ,...\n  ],\n  ,...                     Same output as verbosity = 1.\n}\n\nExamples:\n> bitcoin-cli getblock "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"\n> curl --user myusername --data-binary \'{"jsonrpc": "1.0", "id":"curltest", "method": "getblock", "params": ["00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"] }\' -H \'content-type: text/plain;\' http://127.0.0.1:8332/\n'}

Your code works well, but you have an error when you go to call the function getBlock(), with the bitcoin core reference the getBlock() function have a parameter and this parameter is the hash of the block.
So, your code works because of the RPC framework response with an error
bitcoin.rpc.JSONRPCError: {'code': -1, 'message': 'getblock "blockhash" ( verbosity )\n\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block \'hash\'.\nIf verbosity is 1, returns an Object with information about block <hash>.\nIf verbosity is 2, returns an Object with information about block <hash> and information about each transaction. \n\nArguments:\n1. blockhash    (string, required) The block hash\n2. verbosity    (numeric, optional, default=1) 0 for hex-encoded data, 1 for a json object, and 2 for json object with transaction data\n\nResult (for verbosity = 0):\n"data"             (string) A string that is serialized, hex-encoded data for block \'hash\'.\n\nResult (for verbosity = 1):\n{\n  "hash" : "hash",     (string) the block hash (same as provided)\n  "confirmations" : n,   (numeric) The number of confirmations, or -1 if the block is not on the main chain\n  "size" : n,            (numeric) The block size\n  "strippedsize" : n,    (numeric) The block size excluding witness data\n  "weight" : n           (numeric) The block weight as defined in BIP 141\n  "height" : n,          (numeric) The block height or index\n  "version" : n,         (numeric) The block version\n  "versionHex" : "00000000", (string) The block version formatted in hexadecimal\n  "merkleroot" : "xxxx", (string) The merkle root\n  "tx" : [               (array of string) The transaction ids\n     "transactionid"     (string) The transaction id\n     ,...\n  ],\n  "time" : ttt,          (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n  "mediantime" : ttt,    (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n  "nonce" : n,           (numeric) The nonce\n  "bits" : "1d00ffff", (string) The bits\n  "difficulty" : x.xxx,  (numeric) The difficulty\n  "chainwork" : "xxxx",  (string) Expected number of hashes required to produce the chain up to this block (in hex)\n  "nTx" : n,             (numeric) The number of transactions in the block.\n  "previousblockhash" : "hash",  (string) The hash of the previous block\n  "nextblockhash" : "hash"       (string) The hash of the next block\n}\n\nResult (for verbosity = 2):\n{\n  ...,                     Same output as verbosity = 1.\n  "tx" : [               (array of Objects) The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 "tx" result.\n         ,...\n  ],\n  ,...                     Same output as verbosity = 1.\n}\n\nExamples:\n> bitcoin-cli getblock "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"\n> curl --user myusername --data-binary \'{"jsonrpc": "1.0", "id":"curltest", "method": "getblock", "params": ["00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"] }\' -H \'content-type: text/plain;\' http://127.0.0.1:8332/\n'}

I think the problem is your configuration bitcoin-core, the code of the RawProxy, wants bitcoin to be configured in the default directory
This is the code for the how configuration library
if service_url is None:
            # Figure out the path to the bitcoin.conf file
            if btc_conf_file is None:
                if platform.system() == 'Darwin':
                    btc_conf_file = os.path.expanduser('~/Library/Application Support/Bitcoin/')
                elif platform.system() == 'Windows':
                    btc_conf_file = os.path.join(os.environ['APPDATA'], 'Bitcoin')
                else:
                    btc_conf_file = os.path.expanduser('~/.bitcoin')
                btc_conf_file = os.path.join(btc_conf_file, 'bitcoin.conf')

            # Bitcoin Core accepts empty rpcuser, not specified in btc_conf_file
            conf = {'rpcuser': ""}

            # Extract contents of bitcoin.conf to build service_url
            try:
                with open(btc_conf_file, 'r') as fd:
                    for line in fd.readlines():
                        if '#' in line:
                            line = line[:line.index('#')]
                        if '=' not in line:
                            continue
                        k, v = line.split('=', 1)
                        conf[k.strip()] = v.strip()

            # Treat a missing bitcoin.conf as though it were empty
            except FileNotFoundError:
                pass

            if service_port is None:
                service_port = bitcoin.params.RPC_PORT
            conf['rpcport'] = int(conf.get('rpcport', service_port))
            conf['rpchost'] = conf.get('rpcconnect', 'localhost')

            service_url = ('%s://%s:%d' %
                ('http', conf['rpchost'], conf['rpcport']))

Inside your code, if you have written with correct syntax  you can run the command with the hash of the block, ann example
from bitcoin.rpc import RawProxy
p = RawProxy()
hash = p.getbestblockhash(0)
infoblock = p.getblock(hash)
print(infoblock['time'])

This is the official documentation rpc framework of bitcoin core

yes, i was just figuring it out myself also. :))) the function in the example does not need an argument.

Yes, I add the reference to the rpc documentation in the my answar

What I did not think of was the need for password and user. We talked earlier today and back then the user credentials where actually not necessary because my bitcoin-cli runs on the same machine as bitcoind. In this case another form of authentication will be used. But I have to include the RPC connection into python now, right? I try to keep it simple so I will enter a fixed hash into the script.

Did you check your code? Even if I put a fixed hash (I got from bitcoin-cli I am not able to get the skript to work. And I am sure the skript should work without authentication stuff because the example from the book also did. Also, your documentation is for pip install python-bitcoinrpc but I installed python-bitcoinlib. Not sure if it is the same...

The class RawProxy is doing all of the authentication from the config file. I probably have to put username and password into this file.

So, yes the my reference is wrong, sorry the my code example is the another library.

it is not magic but it searches in the standard configuration, I have a personal directory where I aligned bitcoin core and the library generates this error for me File "/usr/local/lib/python3.6/dist-packages/bitcoin/rpc.py", line 183, in __init__     with open(cookie_file, 'r') as fd: FileNotFoundError: [Errno 2] No such file or directory: '/home/vincenzo/.bitcoin/.cookie'

i think cookie refers to authentication without user/password. for me it does also not work with user/password in the config file. will work on it tomorrow.

I have add the another library because I think the python-bitcoinrpc not is more magic and for a while the idea of what's going on

You have the bitcoin inside the home dir?

Update my answer @Ben

Let us continue this discussion in chat.


text:
Was libbitcoin a part of bitcoin core in the past?
I am trying to use c++ code from the book of Antonopoulos for some time now and I seem to lack an include named bitcoin/bitcoin.hpp.
To compile the code the g++ compiler gets a pkg-config input with libbitcoin. So I suspect I would have to install this library.
Since the book does not mention to install anything else then bitcoin core I really wonder if parts of libbitcoin have originally been part of bitcoin core and have been excluded at some point.
The other explanation would be that the author forgot to mention it. But it seems a bit overload that I have to install another complete system for a full node (libbitcoin) to be able to run the code since the book explicitly says that running a full node with bitcoin core should suffice.
It is just a minor thing and probably laughable for an expert in the field but I am also learning how to use pkg-config and the compiler by doing this.
There have been suggestions to just install parts of libbitcoin but the developers said it is advisable to install the full thing with the automatic install skript.
Also, there is libbitcoin-dev, which is a package in debian (I run Raspbian Buster), but I was not able to compile the code with it.

Can you share what code exactly from which version of Mastering Bitcoin (?) you are trying to use? Maybe share a link or something?

@0xb10c I have several questions open regarding this issue. https://bitcoin.stackexchange.com/questions/90239/how-to-update-an-older-c-code-from-antonopoulos-book-to-work-with-current-lib and https://stackoverflow.com/questions/57754502/do-i-have-to-install-libbitcoin-server-to-be-able-to-include-bitcoin-hpp

What version of bitcoin and libbitcoin did you use?

libbitcoin is not, and was never a part of Bitcoin Core. Both are standalone implementations of the Bitcoin protocol.
Bitcoin Core, in its build process, will create a number of files named "libbitcoin_...". These are just locally generated files that are unrelated to the libbitcoin project.
Bitcoin Core does not have any files with the "hpp" extension. So are you sure you're actually trying to build Bitcoin Core?

I have built Bitcoin Core and I am running a full node. What I want is to compile a simple c++ code from the book "Mastering Bitcoin" which has an include named bitcoin/bitcoin.hpp and the compiler command from the book uses pkg-config --libs libbitcoin. So I am searching for the right library to install and I thought it should be libbitcoin.

That sounds like it's using libbitcoin indeed.

Yes, unfortunately, I was not able to compile it after I installed libbitcoin from source. But that was maybe due to the fact that I also installed the debian package  libbitcoin-dev and then there was an issue with secpk256 and I think maybe the linker took the wrong way somewhere. But thanks anyway!

Add -lgmp to deal with the secpk256 linker errors.

FWIW, since recently libsecp256k1 master no longer depends on libgmp (not even optionally).

The libbitcoin library is a completely separate library and it is not part of the Bitcoin core reference implementation code.
The book code examples has an accompanying actively maintained github repo here. However, extra care is needed for the libbitcoin library dependency as it has new breaking changes. For example, #include <bitcoin/bitcoin.cpp> has been rename to #include <bitcoin/system.hpp>. And no more bc::ec_point. It is possible to install an older compatible version of libbitcoin library, but I prefer to use the latest version and made some adjustment in addr.cpp example code.
I manually build and installed the libbitcoin library to a custom location as suggested here.
mkdir -p /opt/my/libbitcoin/
$ wget https://raw.githubusercontent.com/libbitcoin/libbitcoin/version3/install.sh
$ chmod +x install.sh
$ ./install.sh --prefix=/opt/my/libbitcoin/ --build-boost --disable-shared

And then I build addr.cpp by:
export PKG_CONFIG_PATH=/opt/my/libbitcoin/lib/pkgconfig/
g++ -o addr addr.cpp $(pkg-config --cflags --libs libbitcoin-system) -lgmp

Then run the executable by:
$ ./addr
Public key: 0202a406624211f2abbdc68da3df929f938c3399dd79fac1b51b0e4ad1d26a47aa
Address: 1PRTTaJesdNovgne6Ehcdu1fpEdX7913CK


text:
2-of-2 with different wallets?
I've been using 2-of-2 on bitpay for some years, but relying on just one wallet, which can have its source code backdoored with malware, is very dangerous.
I've been researching about multisignature over different wallets, which makes it harder for these things to occur.
Electrum works with lots of other wallets but it's very user unfriendly. The only other one I know is BlueWallet, but its package.json dependencis worry me a lot: https://github.com/BlueWallet/BlueWallet/blob/master/package.json#L67
What would be a good solution for multisignature over 2 different wallets?

You can use Specter Desktop with the Bitcoin Core wallet and a hardware wallet for the first key and second key respectively in a 2-of-2 multisig.
For a disclaimer it states on the Specter README:

This software might be ready to be used but at your own risk.

Alternatives Michael Flaxman also discussed briefly on the Stephan Livera podcast are Caravan (Unchained Capital) and Sparrow.
These are all efforts to manage multisig for different hardware wallets with Bitcoin Core. I am not aware of any efforts from existing software wallets to expand their offering to multisig with other third party software wallets.

The BitPay wallet IIRC has a very user-friendly implementation of m-of-n, even in its mobile wallet. It is also one of the most trustworthy wallets because of its matureness

I agree, but it already had an incident before with a nodejs dependency having a malware/backdoor. And lets face it, nobody audits nodejs dependencies because a simple project has 1000s of them.


text:
What is extended master key fingerprint on coldcard?
On coldcard on
Advanced -> View Identity, there's
extended master key fingerprint
I though this was the xpub from my seed, but even after I changed seeds, it remained the same.
What is it?

The extended master key fingerprint on the coldcard is indeed the xpub of your wallet. It's just that the first 10 letters or so are equal to every wallet, but the rest is different

According to the answer below, the ColdCard will update the the fingerprint after you apply the passphrase. You can also save the passphrase to a SD  to avoid entering it each time.
"You'll have to enter it in each time you restart the coldcard to access funds under that passphrase. Once you enter it and select "apply" it will update your fingerprint. You can also save the passphrase to a SD card which is encrypted and locked to that coldcard to avoid entering it each time." (link)
In the ColdCard official documentation, there is also this information:
"Press X to go back and adjust your passphrase if the fingerprint is not what you expected
Option to save encrypted Passphrase onto MicroSD
Press (1) to save your new passphrase onto a MicroSD card at this point. Your passphrase value will be encrypted and preserved on the card for next time." (link)

I don't get it. What passphrase? What is the purpose of showing a wrong master key?

I think we're not talking about the same thing. I'm talking about Advanced > View Identity, Extended Master Key


text:
Is it ok to use dices to generate seed for trezor on coldcard?
Coldcard's derive entropy function doe snot have dice method. The only way to generate a seed using dices on coldcard is on "import seed".
Is it ok if I use this feature and generate a new seed with dices and then put this seed on Trezor?

There are many ways to generate seed words that are BIP39 compliant.
It is clear to me that you wish to use dice in order to create seed entropy.  Yes, you can use Coldcard to convert your die rolls into seed words.  Those seed words can be imported into any BIP39-compliant wallet software, including hardware wallets like Trezor.
Alternately, you can use other methods to create seed words from dice.  The top method that comes to mind is the Ian Coleman BIP39 generator.  Check the option to show entropy details, and you will have a spot to enter your dice rolls.  You can select 12-24 words for your output, in three-word increments.


text:
Why bitcoin change addresses are not just the own address?
Why every wallet generates a new change address instead of sending back to itself?

Privacy.
Reusing one of the addresses an input is consuming from as change would would make it trivial for third party observers to infer which output is change and which is the actual payment.
Furthermore, there is no cost or size benefit to reusing. Bitcoin is UTXO-based, not account based, and there is no fee or complexity difference between using a fresh address vs. reusing an older one.


text:
Why these 2 pubkeys start equal?
I generated a seed into my coldcard, wrote down its pubkey:
xpubABCDEFGHIKL---------------------------------------------------

then I erased everything and generated a new seed, and wrote down its pubkey
xpubABCDEFGHIKL---------------------------------------------------

as you see, they both start with the first 15 letters the same. Then they differ.
How is that possible?

The encoding of an xpub contains multiple pieces of data:

A 4-byte fixed prefix that results in the "xpub" prefix after encoding
Depth in the tree (0 for all master xpubs, 1 for children thereof, ...)
A 4-byte checksum of the parent key (0x00000000 for all master xpubs as they have no parent)
The 4-byte index this node has in the derivation from its parent (0x00000000 for all master xpubs).
The 32-byte chaincode
The 33-byte public key

So, the first 13 bytes before encoding are identical for all master xpubs. This translates to roughly 17-18 characters after encoding.


text:
Can I modify bitcoin as per my requirement?
I have taken bitcoin code,and have builded the coin successfully, now i want to change the parameters of my coin so could it possibe suppose i want to define parameters like i want to generate total three lakhs of BTC per year and initial coin to transfer will be 20% of two lakhs BTC,so could it be possible?
Thank You in advance...

You can always create your own chain (and thereby your own coin) with a different Genesis block and changing the subsidy schedule to your liking, thereby modifying the consensus rules from the original Bitcoin chain.
The subsidy schedule is currently only a function of block height of the strong chain, adjusted with halvings every 210k blocks. You could parameterise initial subsidy and halving schedule to fit the subsidy schedule you describe above on an annual rate.
Depending on the Bitcoin implementation you choose to work with, the parametrisation of the subsidy factors in the code may vary, but is definitely possible.
Regarding the initial coin transfer, you can design your subsidy schedule to begin with a certain amount, so the coinbase subsidy reward in your Genesis block represents the value you describe.


text:
How run c-lightning with the local node bitcoin
I have a bitcoin-core-18.0 with on my linux mint, and I don't have downloaded the bitcoin with the ppa but I downloaded the official zip directory on site bitcoin.
Now my question is, c-lightning with this configuration bitcoin-core?
I'm running this command and I have this error
./bitcoin-0.18.0/bin/bitcoind -datadir=/media/vincenzo/Maxtor/BitcoinCore/node/ -daemon -testnet &
./clightning-v0.7.2.1/bin/lightningd --lightning-dir=/media/vincenzo/Maxtor/C-lightning/node/ --network=testnet --log-level=debug

The error
2019-08-22T13:00:06.878Z DEBUG lightning_gossipd(9943): pid 9943, msgfd 20
bitcoin-cli not found. Is bitcoin-cli (part of Bitcoin Core) available in your PATH?

Make sure you have bitcoind running and that bitcoin-cli is able to connect to bitcoind.

You can verify that your Bitcoin Core installation is ready for use by running:

    $ bitcoin-cli -testnet echo 'hello world'

Exist some propriety configuration c-lightning?

Do you have a fully synced bitcoin testnet node (since you are using testnet)?

hi @UgamKamat, yes, I have the same error also with the mainet

It is complaining about not being able to find the bitcoin-cli binary of the Bitcoin Core installation (which is normal since you are running it from a location that is not on the $PATH hence it can't find it).
To fix this issue you can tell lightningd explicitly which binary to use as bitcoin-cli by doing this:
./clightning-v0.7.2.1/bin/lightningd \
      --bitcoin-cli=$(pwd)/bitcoin-0.18.0/bin/bitcoin-cli \
      --lightning-dir=/media/vincenzo/Maxtor/C-lightning/node/ \
      --network=testnet \
      --log-level=debug

This will tell lightningd to use the bitcoin-cli located at $(pwd)/bitcoin-0.18.0/bin/bitcoin-cli. The $(pwd) is there to make the path absolute since lightningd will change directory internally after starting, so that relative paths might not match anymore.


text:
Is possible extract the original script P2MS from the transaction locked with the P2SH address?
This is a stupid question because if the P2SH contains the hash160 (and the hash160 contains the sha256) of the P2MS doesn't possible return to the original hex P2MS.
So, but for verifying the P2SH I must insert the real redmee script inside the scriptSig, so if I parsing the scriptSing I can found the N signature and the M "public key" inside the script P2MS, right?
An example, inside an scientific article this address is cataloged such as scam address, but this address is a script address, so it could is:

a P2MS script with M "public keys"
a script without the "public keys"

But I can access the scriptSig and parsing the hexadecimal, I should be found the original script, right?

Are you trying to extract the bare multisig script from a P2SH multisig address?

I'm trying to validate my idea, i.e the "public key" push inside the P2MS script can be extracted to parsing the scriptSig of the transaction unlock it.


text:
How get the public key to hex script? like command decodescript of bitcoin core
If I want to recreate the command decodescript of bitcoin core? how is the process for decode the script P2PK?
So I'm writing for personal exercise the Bitcoin script decompiler, form moment I have a version alpha of the process decodifier of the script P2PK script.
In my example, I get the scriptPubKey of the codebase block, so the data are
The hex of the script: 4104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac
So the decoded script is
04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac OP_CHECKSIG

The result of the command decodescript of bitcoin core
{
  "asm": "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f OP_CHECKSIG",
  "reqSigs": 1,
  "type": "pubkey",
  "addresses": [
    "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa"
  ],
  "p2sh": "3DjjKyU38gSfuVxajV43MUy4vHkg1JVL7T"
}

So the my process decode is

I get the type of transaction with this code
string hex(argv[1]);
BitcoinOPCode bitcoinOpCode;

string opcode = hex.substr(0, 2);
int32_t optValue = std::stoul(opcode, nullptr, 16);
auto optMap = bitcoinOpCode.opCodeList.find(optValue);
string optCode = optMap->second;
//Not are all type script
if (optCode == "OP_HASH160") {
    cout << "Finded the P2SHA";
} else if (optCode == "OP_DUP") {
    cout << "Finded the P2PKH";
} else {
    cout << "Finded the old style script\n";
}

The script is a script old style so I decode the hex script with this code
string key = hex.substr(2, optValue * 2);
opcode = hex.substr(2 + optValue * 2, hex.length());
cout << "Hex key is: " << key << " op code: " << opcode << endl;
optValue = std::stoul(opcode, nullptr, 16);
optMap = bitcoinOpCode.opCodeList.find(optValue);
opcode = optMap->second;

The result is 04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f OP_CHECKSIG

Find the key to this hex string 04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f

I try with this code
Bytes bytes = hexBytes(key.c_str());

 //Ripemd160
 uint8_t result[Ripemd160::HASH_LEN];
 Ripemd160::getHash(bytes.data(), key.length(), result);
 char address[36];
 Base58Check::pubkeyHashToBase58Check(result, 0x00, address);
 cout << "The script public key is: " << address  << " " << opcode << endl;

But the result is wrong 1NXtFSm6h4QAVBQ7ezaDc3ZvSKFj9GTfoV
I looked the code bitcoin, so I think the bitcoin core decode the script with this code GetScriptForDestination(WitnessV0KeyHash(Hash160(solutions_data[0].begin(), solutions_data[0].end())));
but in the my logic exist an bug, can you help me to find it? thanks

Two comments: 1) the fact that Bitcoin Core shows a 1... address for P2PK output is considered a historical mistake. There is no need to perpetuate it. 2) You should convert everything from hex to bytes, and then work on the byte data. If you feed the hex encoded form to hash functions you'll get the wrong result.

Thanks, @PieterWuille, on your 1 comment, the historical mistake of the P2PK is because inside the script is insert the pure public key? on the 2 comments, to the function Base58Check::pubkeyHashToBase58Check I must pass the bytes, right?

Yes, 1... addresses should refer purely to P2PKH addresses to avoid ambiguity. P2PK outputs simply don't have a corresponding address.

Sorry @PieterWuille if I reopen this question, can you help me to understand the problem with the P2PK script? what does it mean P2PK outputs simply don't have a corresponding address?

Addresses are shorthand notations for specific scripts. But not every script has a corresponding address. P2PK scripts don't have one. P2PKH ones do.

So, if in my example 1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa not is the Key but the result of the process command decode, so sha256 -> Ripemd160 -> Base58Check, What data is entered in the script to unlock the transaction?

That's a completely unrelated question. I think you should go through some reference material (the bitcoin.org developer documentation, maybe a book on Bitcoin, ...) and if you have specific questions, ask them here.


text:
Can I generate multisig addresses directly in the coldcard?
According to coldcard's multisig video tutorial: https://www.youtube.com/watch?v=OMpZ5heLsRg I need to export the 3 xpubs and then create a multisig wallet in each coldcard using these 3 xpubs. Then it exports a list of addresses that can be plugged into Electrum.
However, I don't wanna trust seeing this list on the computer. Can I see these addresses on the coldcard itself?
Like, generate/visualize one address at the coldcard and then compare it with the electrum one just to be sure I'm sending to my wallet?

After digging the source code for 2 days I found it. YES, it's possible.
When you power your coldcard, select Address Explorer, then CC 2-of-2 (in my case) and then you'll be able to see your addresses. However I think you cannot see them entirely, just the beggining and end.
PS: these are testnet addresses for a disposable wallet for my tests


text:
How does muun lightning wallet requires no trust and no backups?
https://muun.com/ claims it has a wallet that does not rely on backups.
Here: https://blog.muun.com/why-not-just-a-mnemonic/ it says

Muun is a multisig wallet with lightning support, so backing up a
mnemonic alone would mean your bitcoin could be easily frozen.
Self-custodianship is at the core of everything we do, so this wasn't
acceptable. We built an Emergency Kit that gives you full self-custody
of your money when combined with your Recovery Code[6].
Your Emergency Kit is a PDF document with the information and
instructions needed to find and spend your funds independently. No
need to brute-force any missing data. Everything is there, including
your private keys and output descriptors[7].
Your private keys are securely encrypted with your Recovery Code. This
makes your Emergency Kit harmless by itself: you can keep multiple
copies, and you can even store it safely on the cloud.

How can it, however, keep track of the state of my lightning wallet? If I use it to only spend, then there's no problem. However, if I receive more than I spend, it's of my interest to save the transaction state so I can propagate it when I want to close the channel.
I don't see how this emergency recovery kit can help me recovering the state.

There is information about "Explore the Emergency Kit" but please explore it before to do, don't trust the website. An analogy can be when at my first year of University I had a web site where I published some Fortran tutorial, the funny things are that I don't know the Fortran language :-)

I'm the CEO at Muun wallet.
Muun does rely on backups since the Emergency Kit is a backup, just not using mnemonics. The problem with mnemonics is that they don't contain a lot of stuff needed for the recovery of a multisig / lightning wallet, like the derivation paths, scripts, etc.
When using Muun, you will back up two pieces of data: the Recovery Code and the Emergency Kit. The Recovery Code is a randomly generated code that you write on a piece of paper, in the same way that you usually do with mnemonics. In fact, this code has higher entropy than a 12-word mnemonic. The Emergency Kit is a PDF document with all the stuff needed for recovery but harmless by itself. It has:

The two private keys (Muun is a 2-of-2 multisig), encrypted using the recovery code.
The output descriptors, with the derivation paths and scripts.
Instructions on how to use this data to recover your funds.
All this data is also available inside the PDF in a machine-readable format.

When using the recovery tool (https://github.com/muun/recovery), you will be able to move the funds using your Recovery Code and Emergency Kit combo. The next version of the recovery tool will use the machine-readable metadata in the PDF for easier input and better UX.
Regarding the lightning aspect of the recovery process, Muun uses super optimized submarine swaps to execute the lightning payments, both incoming and outgoing. This means that your funds are on-chain and thus recoverable by the mechanism I just described.
From the next version, Muun will start maintaining off-chain funds, and thus it will need to backup the off-chain commitment transactions. These transactions will be included in the PDF metadata. I'll update here with more information once we release this.


text:
New on bitcoin want to try it out
I finally got an bitcoin account and i wanna try it out! can you guys donate/give bitcoin so i can try it ?
My bitcoin account.
1MD5FXNdwmPpS2JBWrCJcwHBREtg9dk8Uz

Hello Angu Ilia, we're a question and answer platform focused on collecting knowledge about cryptocurrencies. Your asking for money is off-topic here, so I'm voting to close this question as off-topic.

nice try :-) you may want to look for a "bitcoin faucet", and perform the work yourself. You can earn some Satoshis, which will help you to get started.


text:
What happens to my Bitcoins if I leave them at Coinbase after the hard fork?
So I have a few hundred dollars worth of bitcoins that I bought at Coinbase. I basically just bought them to figure out how to buy bitcoins.
Anyway, it was going to cost like $2-3 in transaction fees to move them to an external wallet so I basically decided to just keep them at Coinbase for now, even if it is the unsafe thing to do, seeing as it's only a few hundred dollars.
I just received an email from Coinbase saying that after the fork, they will only support the current version of bitcoins (BTC) and that I would not be able to withdraw the BitCoin Cash (BCC) ones.
My understanding is that after a hard fork, basically everyone gets their bitcoins duplicated. One BTC and one BCC. So given that Coinbase isn't supporting BCC, what happens to my BCC bitcoins? Are they lost somehow?
Also, I thought that my Coinbase wallet would be exactly the same as any wallet you can get on a computer / wallet. Why is it then that if I keep my coins up on Coinbase, I only get the BTC but if I have it on my own computer, I would get to have both the BTC and BCC bitcoins.

This is what Coinbase says about the November 2017 expected hard fork:
Customers with bitcoin balances stored on Coinbase at the time of the fork will have access to bitcoin on both blockchains. There is no action required from customers and bitcoin can be securely stored on Coinbase before, during, and after the fork. Read more about it here:
https://blog.coinbase.com/update-on-the-bitcoin-segwit2x-hard-fork-69426f14bc85


text:
When is the bitcoin reward provided to the miner?
The rewards are provided to the miner if the miner finds a valid block. So Is the rewards(new bitcoin 12.5 + transaction reward) provided to the miner as soon as the new block is found by miner or reward is provided only when validated by other miners?
If reward is provided as soon as block is found, what happens in case of fork created. ?

Possible duplicate of At which point and how does the miner who successfully solved hash get coins?

The reward is just a transaction which payers the miner, called a Coinbase transaction. Thus it only pays the miner if that transaction is in the accepted blockchain, i.e. if it was invalid or if another block was found first that block would not be included so the miner would not be paid. In fact coinbase transactions only mature after 100 blocks have been mined on top of them, to avoid miners spending coins straight away and then a reorg happens and the block becomes a fork


text:
Buying/Operating Bitcoin ATM
I am looking for some assistance in gathering the correct information about starting to buy/run/operate a bitcoin ATM in Los Angeles, CA. I would like to start with one and expand to multiple areas.
Unfortunately, I have not been able to find a website that advises where I would begin the application process on obtaining a license or banks that deal with Bitcoin ATM's?
Please advise on requested information if anyone knows where to start. That would be greatly appreciated.
Have a wonderful day.