text:
Need a detailed step-by-step P2PK signature validation example
In the process of validating transactions by hand with a new library in elixir. I am starting with f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16, which is one of the first P2PK transactions ever made.
I am struggling to manually validate that transaction with the secp256k1 library included with the language.
It probably has something to do with my code. Most probably is when I strip the signature, creating the message to be signed with the public key, in the process of verifying the signature, or how I encode things, I don't know.
In the process of solving that mystery, I've spent countless hours in vain trying to find a super detailed step-by-step validation of an early transaction.
Might be enough to just know a txid and the exact bytes being sent to a secp256k1 verifying function, so I make sure my code does the same.
In the event that such a document exists somewhere I'd be grateful to be pointed towards it.

Hey, the “message” input, i.e. the digest of the transaction that is being committed to by the signature in Bitcoin transactions is called “signature hash” or [tag:sighash]. I think this might be useful: https://bitcoin.stackexchange.com/a/95750/5406

I got to know exactly what "delete all the script signatures in the raw transaction" means... I am replacing it with 0100 which means one byte that equals to zero. Not 100% it's what's needed.

I was mistaken, it's 00.

There are a lot of things to keep track of when verifying.

Did you encode your data according to the proper sighash byte?
Are you using the correct key to verify?
Did you hash the data you are verifying?
Did you add the four bytes representing the sighash byte to your data?

So, for the transaction you mentioned, there is only one input that contains a signature that ends with sighash byte 01. Sighash byte 01 means we basically use the raw transaction as our data. If there had been multiple inputs, we would use zero-length scripts for the inputs we are not verifying, but in this case we only have one. But we do have to put a 4-byte little endian value at the end of the data to represent the sighash byte.
So this is the data that I believe needs to be verified.
01000000

01

c997a5e56e104102fa209c6a852dd90660a20b2d9c352423edce25857fcd3704
00000000
43410411db93e1dcdb8a016b49840f8c53bc1eb68a382e97b1482ecad7b148a6909a5cb2e0eaddfb84ccf9744464f82e160bfa9b8b64f9d4c03f999b8643f656b412a3ac
ffffffff

02

00ca9a3b00000000
434104ae1a62fe09c5f51b13905f07f06b99a2f7159b2225f374cd378d71302fa28414e7aab37397f554a7df5f142c21c1b7303b8a0626f1baded5c72a704f7e6cd84cac

00286bee00000000
43410411db93e1dcdb8a016b49840f8c53bc1eb68a382e97b1482ecad7b148a6909a5cb2e0eaddfb84ccf9744464f82e160bfa9b8b64f9d4c03f999b8643f656b412a3ac

00000000
01000000

Notice the 01000000 at the end. That represents the sighash byte which has to be signed along with the rest of the data.
I'm not familiar with the library you mentioned, but many of them will work. Typically, you need to pass the data and its length, the signature and the public key being verified. Since the signatures in bitcoin transactions usually have a sighash byte stuck on the end of them, you'll need to remove that byte before passing it to the function you use to verify.
If you serialize all of the bytes above into one message, convert it to binary and apply a double sha256 to it, I bet you can verify it with the public key included in the previous output's script.

Got the same, except for the script sig at line 5, which I tought had to be replaced by 0...

reference, point 7 here: https://en.bitcoin.it/wiki/OP_CHECKSIG#How_it_works

Usually, you would set them all to length zero as explained in step 7, and then in step 8 it says to include just the script for the input you are verifying. However, with the transaction we're looking at there is only one input, so we can just use it as is.


text:
Possible to check who signed the transaction in a multi-sig transaction case?
Say you have a multi-sig tx that originated from a 2-of-3 P2SH address.
Is it possible to say who signed the transaction? i.e. you can get access to the redeem script once the tx is broadcasted, and thus you have access to all 3 public keys that generated the 2-of-3 P2SH address. Arguably you can identify which public keys signed the transaction?
If yes, then how?

Is it possible to say who signed the transaction? i.e. you can get access to the redeem script once the tx is broadcasted, and thus you have access to all 3 public keys that generated the 2-of-3 P2SH address. Arguably you can identify which public keys signed the transaction?

Yes it is possible. When a transaction is broadcast, the redeemScript and all of the signatures are revealed and publicly available in the transaction itself. It is then trivial to just check which signature corresponds to which public key in the redeemScript. You just check the signature against each public key in the redeemScript and whichever one verifies tells you which public key corresponds to that signature.
Script interpreters essentially do this in order to validate multisig spends.

That is definitely not an answer

source: Stack Exchange

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

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

sort: votes


text:
What is the name of the attack where a single node spin thousands of node and take control of the cluster?
When we implement Raft for a decentralised public ledger a single node can easily take over the control of a full cluster by spinning thousands of nodes and making them to elect the malicious node as a leader. What is the name of this attack in security terms?

Are you referring to a Sybil attack?

I was not sure, thats why asked for the name describing the scenario. In sybil attack, a single node forge identities to appear as multiple node. But here a single node is spinning lot of nodes. Is it different or the same?

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


text:
Does Bitcoin Blockchain solves Byzantine General Problem?
If bitcoin blockchain solves byzantine general problem, can you give an example of how it solves it?
Thanks

The Proof of Work algorithms is a probabilistic solution to the Byzantine General's problem in the case where traitorous generals represent strictly less than 50% of the generals.
To simplify, the main thing a solution to this problem has to guarantee is that all honest generals (honest miners) agree on the same thing.
Let's assume there are 10 miners in the Bitcoin blockchain and a new transaction comes in. This transaction (noted tr1) is broadcasted among all miners. 10 of those miners are traitorous and they broadcast another transaction (noted tr2) where they changed the recipient in tr1.
Each miner will starts to solve a puzzle just after he received his first transaction message. Some will receive tr1 first, others will receive tr2 first.
The puzzle is difficult enough that, on average, a solution will be found every 10 minutes. After 10 minutes, miner M solves the proof of work problem. He broadcasts his solution to the 9 other miners and includes in there the transaction he received first. Upon receiving this solution, each miner adjusts his transaction to the new one received. They then all work on the next puzzle. After 1 hour, the chain has 6 blocks (6 puzzles solved). Each general can evaluate how much CPU was necessary to get solve 6 puzzles in 10 minutes. Each general knows then if the majority of the general contributed to building this chain. If the answer is yes, then they agreed on the transaction inside the initial block of this chain.
Now an interesting point: what if the transaction in the initially mined block is tr2? The solution described here doesn't prevent from agreeing on a false transaction. In the context of the Byzantine Generals problem, it is sufficient for the generals to agree on a false plan as long as they agree.

is there a reason you say POW algorithm'S' in plural? Maybe I'm mistaken in thinking of POW as a one single algorithm?

The Byzantine Generals' Problem
Imagine a time during the dark ages, where a pirate ship is under attack. There are 200
pirates aboard the pirate ship surrounded by six army ships of 50 warriors each, who've
anchored, surrounding the pirate ship. Each army ship is commanded by a captain. The 300
warriors can easily overpower the 200 pirates aboard the pirate ship. However, if they don't
all attack simultaneously, there is a very real risk that the warriors will be outnumbered by
the pirates and they'll go on to lose the battle.
So, how can the captains all agree on the same time to attack the pirate ship? These days,
we'd simply need a quick group video-conference call, and the captains would have to
agree to attack at 22:00 hours (10 PM).
However, back in the dark ages, things were a little more complicated:
The 22:00 attack message could only be passed on by a sailor on a small boat. He
has to sail around each army ship, visiting each captain in turn to confirm.
Any captain may be a traitor and in league with the pirates in the pirate ship.
Losing strategy
Captain 1 decides to attack at 22:00. He sends his sailor out with the message (22:00 attack)
to deliver to Captain 2. Upon arrival, Captain 2 reads the message, notes the time of the
attack, and sends a message that also says 22:00 attack. He sends the sailor on to share the
message with Captain 3. However, we have a problem. Captain 3 is a traitor. He wants the
attack to fail. So, when he gets the message, he rips it up and replaces it with a new message
that says 21:00 attack (9 PM). The sailor continues unaware. Captain 4 now receives a
message saying 21:00 attack. He notes the time, signs the message saying 21:00 attack and
sends this on to Captain 5, who then sends the same message to Captain 6. Now, the
message has gone around everyone, but we have a problem. The dishonest captain has
disrupted the result. We now have three captains (4, 5, and 6) with 150 warriors attacking
the pirate ship at 21:00. Expecting others to join them, they instead get outnumbered and
overpowered by the 200 pirates. The victorious pirates now stream out of the pirate ship
and join forces with the treacherous Captain 3. Suddenly, the two remaining captains (1 and
2) have only 100 warriors and find themselves fighting 200 pirates plus 50 traitors.
Unfortunately, the pirates and traitors win.
Winning strategy
Captain 1 wants to send the same message (attack at 22:00). However, this time, there are
two new rules he must obey:
He must spend 10 minutes preparing any new message for it to be valid
He must include the history of every previous message in every new message
So, let's see what happens this time. As before, Captain 1 sends the message (22:00 attack)
with the sailor on the boat. This time, however, it is different for Captain 2, because he
knows two things for certain:
The message must have taken 10 minutes to prepare
There are no previous messages, so it must be the truth (even if Captain 1 is a
traitor and put in the wrong time, it doesn't matter; if the majority of captains
followed this suggestion and went with a 22:00 attack time, they would still
outnumber those in the pirate ship and win the battle)
So, now it is time for Captain 2 to send a message. As required, he spends 10 minutes
preparing the new message and he embeds Captain 1's message into his own. The sailor
then sets off with this message (now in fact, it is two messages chained together as the
second has the first embedded within it). Now it gets to Captain 3.
Remember, he's the traitor. So, what does he do? Last time, he changed the message to 21:00
attack so that captains 4, 5, and 6 would attack early and get overpowered. Now, however,
he can't because, under the new rules, he has only 10 minutes to prepare a message for
Captain 4. He has two options:
1. Cheat by changing the message to 21:00 attack. To do this, he needs to (a) spend
10 minutes creating his message and then (b) spend an extra 2 x 10 minutes
working to create replacement 21:00 attack messages from Captains 1 and 2 to
embed these into his message and carry out this 30 minutes of work within the
next 10 minutes to avoid the other captains knowing that he's a traitor.
2. Admit defeat and prepare the 22:00 attack message during those 10 minutes.
In other words, every captain has got no more than 10 minutes to provide the next captain
with something that would take more than 10 minutes to fake if they were trying to be
dishonest. If they can't deliver it within 10 minutes, everyone knows they're dishonest and
ignores them, rendering their attempts to mislead others useless.

This is an amazing analogy, +1

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


text:
SegWit. Redeem script
I'm experimenting with Segwit transactions.
Is it possible to restore redeem script, if I know
1. Address (Segwit)
2. Public key
3. Private key
Thank you.

There are many (infinite) different redeem scripts based on private key. Restoring is possible if you know what kind of script was generated

The redeem script for a P2SH-P2WPKH address is relatively simple. You take the RIPEMD160 hash of the SHA256 hash of the public key (same as P2PKH), this is known as the keyhash. The public key must be in compressed form. Then the P2SH redeem script is just OP_0 followed by a push of the keyhash. The keyhash is 20 bytes so the redeem script will always be 22 bytes long: 0014{keyhash}.

You can obtain the redeem script from the public key. See line 86 here: https://github.com/Samourai-Wallet/samourai-wallet-android/blob/develop/app/src/main/java/com/samourai/wallet/segwit/P2SH_P2WPKH.java


text:
How to connect existing MEW to Trezor?
I have got my new Trezor but I don't know how to connect my existing myetherwallet to trezor ether address ?
Is there any way I can directly import and connect to trezor ?
Or I have to create a new myetherwallet with trezor and transfer ethereum and other erc20 coins from old myetherwallet to new ether trezor address ?

You cannot import your existing MEW to Trezor wallet.
It is the security of a hardware wallet which makes it worth the price, and that is why the wallet is generated in Trezor offline.
Thus, the only way is to create a new wallet in Trezor. Transfer all your coins from existing MEW to Trezor. And after that, you can use Trezor with MEW to send or receive other alt coins which Trezor don't have support directly.
Hope this answers your query.


text:
How are thousands of transactions put into a block?
As much as I hate to admit it, I am not very tech savvy, and as such, I am fairly confused about the concept of the blockchain. I understand that the chain holds information about previously approved transactions that are grouped together into blocks. How exactly are these blocks formed? Also, does each transaction have its own hash? If so, how are all of the hashes grouped together into one has for the block?

How exactly are these blocks formed?

First a miner decides which transactions to include in their block (usually they run algorithms that maximize its profit), and collects the transactions fees in the block.

Also, does each transaction have its own hash?

Yep, transactions are named with their hash. For example the transaction c58523726c33e982a69ff092f56d782790ece31185bd4b824e36002e5f507e1e is called c58523726c33e982a69ff092f56d782790ece31185bd4b824e36002e5f507e1e.

If so, how are all of the hashes grouped together into one has for the block?

That's a complex process named "Merkle root".


text:
What is the safest way to rename my altcoin from "bitcoin" to "myaltcoin" in the source code?
Some Context
I am creating my own altcoin for learning purposes and have successfully built the bitcoin code from source with my own genesis block.
Now is it time for me to change the name of the coin, so that it is truly my own alt coin.
To do this, I presume that I must change every instance of bitcoin to myaltcoin in the code, so that when I run bitcoin-qt (after the change I hope to be able to run myaltcoin-qt), everything inside the GUI will say myaltcoin and not bitcoin.
How I propose to do this...
I figure that the best way to do this would be to do some kind of case sensitive find and replace, to recursively go through all files and directories and the strings in the files, changing every instance of bitcoin to myaltcoin
The Question
What is the safest way to do this in the linux terminal? To do this safely I assume I must:

Account for case sensitivity.
Replace file names of bitcoin to myaltcoin
Replace text instances of bitcoin to myaltcoin within files
Replace bitcoin to myaltcoin in directory names

I presume there is some way to do this with find, but I'm not sure what the best way is.

look at this https://github.com/cesjavi/createcoin/blob/main/crear.sh . You must edit seed dns "who are HARDCODED" and change it to something else

there is no faster way to rename , but there are steps you have to rename the bitcoin source code.. for ex let your altcoin's name be : andracoin
First :
inside the src folder use this command :
find ./ -type f -readable  -writable -exec sed -i 's/bitcoin/andracoin/g' {} \;

then:
find ./ -type f -readable  -writable -exec sed -i 's/Bitcoin/Andracoin/g' {} \;

then :
find ./ -type f -readable  -writable -exec sed -i 's/BitCoin/AndraCoin/g' {} \;

then :
find ./ -type f -readable  -writable -exec sed -i 's/BitCoin/AndraCoin/g' {} \;

then :
find ./ -type f -readable  -writable -exec sed -i 's/BTC/ADC/g' {} \;

then :
find ./ -type f -readable  -writable -exec sed -i 's/bitcoind/andracoind/g' {} \;

of course after you rename you will have some issues , but this is the safest way to replace names ...if you don't have a basic information about bitcoin and its blockachain you will have alot of problems during the building process. I recomand to watch this course :
How to Create Your Own Cryptocurrency in C++

To find string with in the files (including binary files), issue the command:
grep -rnw '/home/user/' -e 'bitcoin'

It will return every single entry for the word bitcoin in your code.
But I do not think that's the best way to get what you have in mind, what about "if" you have a CONST or a variable in the code called const BITCOIN or bitcoin ?
Your approach would be catastrophic for the base code and probably it will not compile. Just do not do that, instead try to find all the points with the command above, once you find all the entries, change it manually (read the code before you do that) and not using find and replace option from your code editor.


text:
API for raw Bitcoin latest block data?
I would like to get the full raw data on the latest bitcoin block. I was hoping I could get this from an API.
I looked at blockchain.com's API's but these don't seem to provide the full data for each block including the header and transactions.
Does anyone know of a good source for this? Or should I be looking at alternatives to an API?

I am not aware of any public endpoint that will serve you the raw bitcoin core data. You can try with other explorers like blockstream.info but if you're looking for raw data, the best option is to run your own bitcoin core node.

Thanks for your reply Tony. I don't know if 'raw' is the correct terminology for me to use. I need the full block data so I can see the header and transactions. If that makes any difference?

So basically something like this? https://api.smartbit.com.au/v1/blockchain/block/360973

Thanks m1xolyd1an, yes perfect! Except is their a way to get this for the latest block?


text:
Beginner's question: Why must proof-of-work be useless?
I wonder why the proof-of-work under no circumstances may be usable. The argument I understand is: If the proof-of-work could be used, its results could be sold, and doing the proof-of-work would cost the user nothing - or even could be valuable - and so would not restrict the usage of the service (e.g. bitcoins).
But why not use ideas from captchas of which the usage can be monetarized (e.g. by improving character recognition systems)?
Is a crypto currency system unconceivable where the user must pass the results of the proof-of-work to a central instance which can use them? (Prohibiting that the user can monetarize them on his own account.)
This would make crypto currencies much more sustainable than they currently are.

Here's an example of a useful proof of work: https://primecoin.io/about.php#advantages-xpm

Related, if not a duplicate of: https://bitcoin.stackexchange.com/questions/331/is-there-a-way-to-set-up-proof-of-work-systems-so-they-would-be-even-more-useful

https://satoshi.nakamotoinstitute.org/posts/bitcointalk/337 "The heat from your computer is not wasted if you need to heat your home." However this is not quite a convincing argument because in reality the heat generated is barely utilised. There are experimental/conceptual products like "mining heater" but its maintenance burden (the machine may malfunction, then it must be repaired or even discarded) and obsoletion (newly developed mining equipments will be always more powerful and energy-efficient) may overweight its potential profits.

In addition to the technical factors mentioned by MCCCS, it's important to consider economical factors as well.
If the problem being solved has value outside of the Bitcoin network, it allows miners to essentially "double dip" on the rewards - they earn both from the Bitcoin received as block rewards, as well as the incentive structure off chain.
For example, if the problem being solved is character recognition, it would enable a number of companies who seek good character parsing systems, such as Google, self driving car companies, etc, to double dip. These companies are then incentivized to build a a mining farm to not only train their programs, but also use that training to earn Bitcoin, subsidizing the operation they're already doing.
Being such large companies, their primary goal is likely to have a good text recognition system - the value of Bitcoin earned is secondary. This allows them to invest much more into their mining farms, potentially outstripping other miners who do not have a dual incentive. Moreover, as they get paid twice, it is in their favour to attempt to resolve minor reorgs to build on top of their blocks - they are already subsidized via the off chain incentive, so the cost of losing a block proportional to their operating cost is much lower, allowing them to take riskier routes to resolving minor forks.
This also reduces the cost of mounting attacks - if the mining power required to launch an attack is subsidized by external incentives, it is easier to pay for and acquire.
This also changes the reward structure overall - if the majority of the earnings for a miner are from an outside source, they are less concerned with the effects of bad blocks, 51% attacks, or other bitcoin issues that drop the value of bitcoin. The risk:reward calculation for attacking the chain becomes skewed, allowing for high reward attacks to have a lower cost than in a single use system.

Too bad they didn't pick protein folding. High utility, low value of each one.

The problem is that one can find a proof of work algorithm that gives a useful output. However, it may not stay useful forever. When the research is done, it will have to be replaced. When proof of work is replaced, years of research about ASIC designing for a specific algorithm is waster. The CPU => GPU => ASIC cycle starts again. In the first two stages of cycle, the coin is vulnerable to botnets. Since we're in the ASIC stage in Bitcoin, botnets would be relatively significantly inefficient, and there's no fear of a new miner coming in and killing the coin.
It is also unadvisable for a coin to have the same PoW algorithm as a coins with a larger hashrate, in which case the difficulty adjusting algorithm is abused and blocks are only feasible when the difficulty value drops.

But why not use ideas from captchas of which the usage can be monetarized (e.g. by improving character recognition systems)?

Because the most of proof of works aren't reusable. I can request a proof-of-work for a math problem but once you're done, there's no trustless way of generating original problems.

Changing the PoW puzzle also involves centralised mechanisms like checkpoints, doesn't it?

Yes, the Bitcoin protocol developers would be accused of conflict of interest. "We all know that the ASIC producer X who can't compete anymore paid you to change it!"

I also remember that Satoshi himself said the idea of Bitcoin was originated from Nick Szabo's Bitgold proposal and Wei Dai's b-money proposal (https://satoshi.nakamotoinstitute.org/posts/bitcointalk/249/), while Hal Finney's RPOW (Reusable Proofs of Work) is "a variant of bit gold". I think that "trustless", "decentralization" and "reusable" should be deeply in the DNA of Bitcoin.

I wonder why the proof-of-work under no circumstances may be usable.

Proof of work is useful: it allows a network of untrusted participants to reach consensus without the need for a trusted party.
As others have mentioned, making the work useful in other ways actually reduces this network security, as the cost of attack is subsidized by the external usefulness of the work.

Is a crypto currency system unconceivable where the user must pass the results of the proof-of-work to a central instance which can use them?

If the user would need the approval of the centralized party in order to add the next block, then this would be a huge security risk to the network: the centralized party would have the ability to arbitrarily censor users and transactions from participating. This is very unattractive, nobody should want to participate in a system that they might be unfairly censored from.
If the user would not need approval from the central party to add the next block, then how is the validity of their solution determined?

A good PoW algo will be hard to compute but easy to verify, and it should include a method to adjust the network difficulty.
In addition to this, the proof-of-work must somehow be tied to the specific block and transactions that are being mined. A good proof-of-work cannot just be some useful-equation-solution that has been arbitrarily attached to a block, that wouldn't provide much security at all!
As example: you wouldn't want a user to be able to take the solutions to past problems, build new blocks to attach them to, and then start broadcasting a conflicting history to network peers. By what method would a new network peer be able to decide which blockchain history is the correct one? It wouldn't be possible, since the work would not be inherently tied to any block.
On the other hand, energy spent on Bitcoin's proof-of-work inspires trust in the security of the network history, and in doing so it irrevocably attaches specific transactions to specific blocks.


text:
Beneficial proofs of work
I'm new to this community and a Bitcoin novice.
I believe to have understood the concept and purpose of proof of work but also, that the high energy consumption of proofs of work is a major problem of the Bitcoin (and other blockchain based) systems.
The puzzle that need to be solved for the proof of work has to be complex:

computing the cryptographic nonce (as used in the Bitcoin system)
solving complex differential equations
operations on dense matrices

I wonder if my impression is correct that these puzzles' only purpose is to provide authentication, esp. for the right to mine new bitcoins -  and that they are otherwise "useless".
More than that I wonder if there are attempts to define complex proof of work puzzles that fulfill other purposes that are more beneficial/useful/valuable to - let's say society - which would justify the high energy consumption.
You may compare this with Google's ReCAPTCHAs that next to authentication "assist in the digitization of books or improve machine learning".

Your first point is indeed right: The BTC puzzle is only useful for ensuring the security of the blockchain.
Onto your next question: One of the first attempts to define a "useful" PoW was Primecoin, created back in 2013. Additional research in this area is being done.
In defense of Bitcoin's PoW, some people have said that Bitcoin mining tends to use up energy that would otherwise go to waste. For instance, if a hydroelectric plant is no longer being used for its original industrial purposes, then it can instead be harnessed for BTC mining. Mining on fossil fuels is currently unprofitable.
Of course, a more "useful" PoW could harness this energy for something even better. But even then you have to weigh up the pros and cons of switching BTC/ETH to such a PoW function. And you'll probably come up short.

Why should a hydroelectric plant no longer be used? Energy plants are expensive, energy is expensive - so why should energy go to waste anywhere in the world?

Hydroelectric plants produce energy regardless of whether there is demand for it. Some of it can go to waste. The energy could be stored in batteries and released on demand, but I don't know how practical that is.

Additionally, it's easy for BTC miners to "move in" and soak up unused energy

What do you mean with "move in"?

ship the ASIC equipment and start mining

For example to Africa or India? Ship the equipment and pay for "energy mining" rights?


text:
Under what circumstances does bitcoin-qt ban a peer?
Under What Circumstances Will Bitcoin-qt Ban A Peer?
In my bitcoin-qt wallet, I am noticing that often there are a lot of banned peers.
Sometimes I have as many as 10 peers banned within the wallet, but I am doubtful that all of these peers are acting maliciously.
I'm curious, what are the circumstances under which the QT wallet will ban a peer?


text:
How to send BTC to P2WSH address using sats-connect?
How can I send BTC to a P2WSH address with sats-connect?
The sats-connect documentation provides the following API for sending bitcoin on the testnet. I would like to use this API so I can fund HTLC scripts with Xverse wallet. The documentation example uses a P2SH script address for the recipient, and I would like to use a P2WSH address as my recipient, because my HTLC script uses P2WSH.
const sendBtcOptions = {
  payload: {
    network: {
      type: "Testnet",
    },
    recipients: [
      {
        address: '2NBC9AJ9ttmn1anzL2HvvVML8NWzCfeXFq4', //But I want to use a P2WSH address
        amountSats: 1500,
      },
      {
        address: '2NFhRJfbBW8dhswyupAJWSehMz6hN5LjHzR',
        amountSats: 1500,
      },
    ],
    senderAddress: 'paymentAddress',
  },
  onFinish: (response) => {
    alert(response);
  },
  onCancel: () => alert("Canceled"),
};

await sendBtcTransaction(sendBtcOptions);

When I try to use this code to send BTC to tb1qh5a0wdhlck6v3n0s5ncxnpac98wj37xftd3uzkxvhlvfwtpzh9xqh046ll I get the following error:
Error sending BTC with Xverse wallet: Error: Incorrect recipient format
    at sendBtcTransaction

So that leads me to the question:
How can I sent BTC to a P2WSH address with sats-connect instead of their recommended P2SH? Is this even possible with sats-connect? If my approach is unreasonable and there is a better way please let me know.


text:
Do any browser wallets support custom bitcoin scripts?
I am creating an atomic swap interface between Bitcoin and EVM using hashed timelock contracts as the underlying swapping mechanism. The idea is to support atomic swaps via the browser, using browser-based wallets.
To do this I need my web interface to be able to create Bitcoin scripts programmatically and create transactions to which those scripts are attached - all via the web interface. Metamask uses Web3.js for the EVM side of this transaction, but I am not sure which browser-based Bitcoin wallet has similar functionality.
I need to support a bitcoin wallet that can invoke new bitcoin scripts via javascript and create transactions based on those scripts. Does such a browser-based wallet exist for Bitcoin?
I have looked at Xverse and Trust wallet, but no such support seems to exist.
Question:
Is there a browser-based bitcoin wallet that can support the programmatic creation of transactions that include custom Bitcoin scripts?

Wallet reviews are off-topic for this site. That said it's a good question. If this helps, i think browser-based wallets are much more common in Ethereum land than in Bitcoin land. In Bitcoin the only ones you'd come across would likely be "pocket money" wallets (i'm thinking of the Joule extension, Mutiny, or even Cashu) which aren't used for onchain txs. In addition there is still a limited number of wallets with support for custom scripts, which makes it very unlikely any of the browser-based wallet does support them.

Thanks. If there are no browser-based options, are there any desktop-based options other than Bitcoin-QT/Bitcoind? I'm hoping one that doesn't require the user to run a full-node.

You only need HTLCs? Are your scripts Miniscript-compatible? They should be, or it should be easy to make them so. (Side-note: given the upvotes i think we can make an exception for this question, i'll write up an answer once this conversation in the comments is over.)

I haven't created the HTLC scripts yet - I was looking for a wallet solution first then I am happy to write them in whatever format is necessary. The main goal here is to enable the entire flow via the browser. So I am agnostic as to the implementation details of the HTLC script itself

Product and services reviews are generally off-topic for this site. That said, i think the way the question is formulated allows to give some general guidance for how to go about looking for a Bitcoin wallet which fits your needs, without getting in an opinionated analysis of each of them.
From the question and the comments, i infer you are more familiar with Ethereum. I believe web wallets are much more common in the Ethereum world than they are in the Bitcoin world. I think if you look around for web-based Bitcoin wallets you'd mostly come across "pocket money" wallets which put forward Lightning or Chaumian Mint based payments rather than onchain transactions.
Since you don't have specific requirements for the format of the script, you could either:

Look for wallets which support Miniscript. They aren't yet very common yet, but are now getting more traction and more are being developed. That said, i would expect most Miniscript-aware wallet to not support any Miniscript. Rather i'd expect they would simply leverage Miniscript for the usecase they are focused on addressing.
Look if you could integrate with Lightning. After all, payments on Lightning are just HTLC's. Except they are kept off-chain most of the time. If you choose this route, i'd advise to design your protocol such as to keep Lightning payments almost instant. It's sometimes tempting to just hold onto an HTLC (thereby blocking liquidity along the whole path), but it won't be free forever.


text:
In btc network does the limit of Vin should be less than 1000 in for a single transaction?
Suppose i am doing transaction which involves more than  50k Vins. I found that i cant do thaat in a single go. So is it true that even if the size of block is less than the maximum limit, i cant do that transaction because of limit in Vins?

Bitcoin Core enforces a standardness limit on the weight of transactions of 400000 (corresponding to 100000 bytes for non-segwit transactions). Note that miners are not required to follow this limit (though most do), and larger transactions are absolutely valid inside blocks.
There is no specific limit on the number of transaction inputs.


text:
Why can't the genesis block be found I create an altcoin?
I have built the bitcoin source code with a new pszTimestamp, hashGenesisBlock and hashMerkleRoot
The code builds fine and does not run into any assert problems when validating these hashes on [line 128 and line 129 of chainparams.cpp]. (Great)
However...
When I run bitcoin-qt I run into the error below:
Error: Incorrect or no genesis block found. Wrong datadir for network?
Potential Cause:
Is the reason I am encountering this error because I have not yet mined the genesis block? If so how do I do that? It seems that in the bitcoin code there is nothing about mining the genesis block. I have heard rumours that this functionality was removed and that I will have to download a separate program for this step. Please confirm.

I met same problem. I met CBlockDiskPos(nFile=0, nPos=8) error or AcceptBlock: high-hash, proof of work failed (code 16) error.  Have you solved? Any updates?

Thant is correct. You have to mine the genesis block first separately if you are compiling the most recent bitcoin codebase.
Checkout : https://github.com/vlamer/genesis-block-generator

Is it still work with newest litecoin source? (0.15.1)

I'm not entirely sure of that but since its a complete copy of bitcoin source, I don't think anything would be different.


text:
Why is bitcoin core failing to build on Ubuntu?

I am trying to build bitcoin core from source using Ubuntu 17.04 with this guide: http://bitzuma.com/posts/compile-bitcoin-core-from-source-on-ubuntu/

The build fails when I use sudo make.
The Error is:
Making all in src
make[1]: Entering directory '/home/oscar/src/bitcoin/src'
make[2]: Entering directory '/home/oscar/src/bitcoin/src'
  CXX      crypto/libbitcoinconsensus_la-sha1.lo
  CXX      crypto/libbitcoinconsensus_la-sha256.lo
  CXX      crypto/libbitcoinconsensus_la-sha512.lo
  CXX      crypto/libbitcoinconsensus_la-ripemd160.lo
  CXX      script/libbitcoinconsensus_la-bitcoinconsensus.lo
  CXXLD    libbitcoinconsensus.la
/usr/bin/ar: `u' modifier ignored since `D' is the default (see `U')
  CXX      bitcoind-bitcoind.o
  CXX      libbitcoin_server_a-addrman.o
  CXX      libbitcoin_server_a-alert.o
  CXX      libbitcoin_server_a-checkpoints.o
  CXX      libbitcoin_server_a-init.o
  CXX      libbitcoin_server_a-leveldbwrapper.o
  CXX      libbitcoin_server_a-main.o
  CXX      libbitcoin_server_a-miner.o
miner.cpp: In function ‘CBlockTemplate* CreateNewBlock(const CScript&)’:
miner.cpp:94:5: warning: ‘template<class> class std::auto_ptr’ is deprecated [-Wdeprecated-declarations]
     auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
     ^~~~~~~~
In file included from /usr/include/c++/6/memory:81:0,
                 from /usr/include/boost/unordered/unordered_map_fwd.hpp:14,
                 from /usr/include/boost/unordered/unordered_map.hpp:17,
                 from /usr/include/boost/unordered_map.hpp:17,
                 from coins.h:18,
                 from main.h:16,
                 from miner.cpp:12:
/usr/include/c++/6/bits/unique_ptr.h:49:28: note: declared here
   template<typename> class auto_ptr;
                            ^~~~~~~~
miner.cpp: In function ‘void BitcoinMiner(CWallet*)’:
miner.cpp:469:13: warning: ‘template<class> class std::auto_ptr’ is deprecated [-Wdeprecated-declarations]
             auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
             ^~~~~~~~
In file included from /usr/include/c++/6/memory:81:0,
                 from /usr/include/boost/unordered/unordered_map_fwd.hpp:14,
                 from /usr/include/boost/unordered/unordered_map.hpp:17,
                 from /usr/include/boost/unordered_map.hpp:17,
                 from coins.h:18,
                 from main.h:16,
                 from miner.cpp:12:
/usr/include/c++/6/bits/unique_ptr.h:49:28: note: declared here
   template<typename> class auto_ptr;
                            ^~~~~~~~
  CXX      libbitcoin_server_a-net.o
  CXX      libbitcoin_server_a-noui.o
  CXX      libbitcoin_server_a-pow.o
  CXX      libbitcoin_server_a-rest.o
  CXX      libbitcoin_server_a-rpcblockchain.o
  CXX      libbitcoin_server_a-rpcmining.o
rpcmining.cpp: In function ‘json_spirit::Value setgenerate(const Array&, bool)’:
rpcmining.cpp:173:13: warning: ‘template<class> class std::auto_ptr’ is deprecated [-Wdeprecated-declarations]
             auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
             ^~~~~~~~
In file included from /usr/include/c++/6/memory:81:0,
                 from /usr/include/boost/config/no_tr1/memory.hpp:21,
                 from /usr/include/boost/smart_ptr/shared_ptr.hpp:23,
                 from /usr/include/boost/shared_ptr.hpp:17,
                 from /usr/include/boost/date_time/time_clock.hpp:17,
                 from /usr/include/boost/thread/thread_time.hpp:9,
                 from /usr/include/boost/thread/lock_types.hpp:18,
                 from /usr/include/boost/thread/pthread/mutex.hpp:16,
                 from /usr/include/boost/thread/mutex.hpp:16,
                 from allocators.h:14,
                 from streams.h:9,
                 from net.h:17,
                 from rpcmining.cpp:10:
/usr/include/c++/6/bits/unique_ptr.h:49:28: note: declared here
   template<typename> class auto_ptr;
                            ^~~~~~~~
  CXX      libbitcoin_server_a-rpcmisc.o
  CXX      libbitcoin_server_a-rpcnet.o
  CXX      libbitcoin_server_a-rpcrawtransaction.o
  CXX      libbitcoin_server_a-rpcserver.o
  CXX      script/libbitcoin_server_a-sigcache.o
  CXX      libbitcoin_server_a-timedata.o
  CXX      libbitcoin_server_a-txdb.o
  CXX      libbitcoin_server_a-txmempool.o
  AR       libbitcoin_server.a
/usr/bin/ar: `u' modifier ignored since `D' is the default (see `U')
  CXX      libbitcoin_common_a-base58.o
  CXX      libbitcoin_common_a-chainparams.o
chainparams.cpp: In constructor ‘CMainParams::CMainParams()’:
chainparams.cpp:161:51: error: ambiguous overload for ‘operator=’ (operand types are ‘std::vector<unsigned char>’ and ‘boost::assign_detail::generic_list<int>’)
         base58Prefixes[PUBKEY_ADDRESS] = list_of(0);
                                                   ^
In file included from /usr/include/c++/6/vector:69:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6/bits/vector.tcc:167:5: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
     vector<_Tp, _Alloc>::
     ^~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/vector:64:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6/bits/stl_vector.h:450:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::vector<_Tp, _Alloc>&&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
       ^~~~~~~~
/usr/include/c++/6/bits/stl_vector.h:471:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::initializer_list<_Tp>) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(initializer_list<value_type> __l)
       ^~~~~~~~
chainparams.cpp:162:51: error: ambiguous overload for ‘operator=’ (operand types are ‘std::vector<unsigned char>’ and ‘boost::assign_detail::generic_list<int>’)
         base58Prefixes[SCRIPT_ADDRESS] = list_of(5);
                                                   ^
In file included from /usr/include/c++/6/vector:69:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6/bits/vector.tcc:167:5: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
     vector<_Tp, _Alloc>::
     ^~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/vector:64:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6/bits/stl_vector.h:450:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::vector<_Tp, _Alloc>&&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
       ^~~~~~~~
/usr/include/c++/6/bits/stl_vector.h:471:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::initializer_list<_Tp>) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(initializer_list<value_type> __l)
       ^~~~~~~~
chainparams.cpp:163:53: error: ambiguous overload for ‘operator=’ (operand types are ‘std::vector<unsigned char>’ and ‘boost::assign_detail::generic_list<int>’)
         base58Prefixes[SECRET_KEY] =     list_of(128);
                                                     ^
In file included from /usr/include/c++/6/vector:69:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6/bits/vector.tcc:167:5: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
     vector<_Tp, _Alloc>::
     ^~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/vector:64:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6/bits/stl_vector.h:450:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::vector<_Tp, _Alloc>&&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
       ^~~~~~~~
/usr/include/c++/6/bits/stl_vector.h:471:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::initializer_list<_Tp>) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(initializer_list<value_type> __l)
       ^~~~~~~~
chainparams.cpp:164:72: error: ambiguous overload for ‘operator=’ (operand types are ‘std::vector<unsigned char>’ and ‘boost::assign_detail::generic_list<int>’)
      base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E);
                                                                     ^
In file included from /usr/include/c++/6/vector:69:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6/bits/vector.tcc:167:5: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
     vector<_Tp, _Alloc>::
     ^~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/vector:64:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6/bits/stl_vector.h:450:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::vector<_Tp, _Alloc>&&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
       ^~~~~~~~
/usr/include/c++/6/bits/stl_vector.h:471:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::initializer_list<_Tp>) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(initializer_list<value_type> __l)
       ^~~~~~~~
chainparams.cpp:165:72: error: ambiguous overload for ‘operator=’ (operand types are ‘std::vector<unsigned char>’ and ‘boost::assign_detail::generic_list<int>’)
      base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4);
                                                                     ^
In file included from /usr/include/c++/6/vector:69:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6/bits/vector.tcc:167:5: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
     vector<_Tp, _Alloc>::
     ^~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/vector:64:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6/bits/stl_vector.h:450:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::vector<_Tp, _Alloc>&&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
       ^~~~~~~~
/usr/include/c++/6/bits/stl_vector.h:471:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::initializer_list<_Tp>) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(initializer_list<value_type> __l)
       ^~~~~~~~
chainparams.cpp: In constructor ‘CTestNetParams::CTestNetParams()’:
chainparams.cpp:220:53: error: ambiguous overload for ‘operator=’ (operand types are ‘std::vector<unsigned char>’ and ‘boost::assign_detail::generic_list<int>’)
         base58Prefixes[PUBKEY_ADDRESS] = list_of(111);
                                                     ^
In file included from /usr/include/c++/6/vector:69:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6/bits/vector.tcc:167:5: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
     vector<_Tp, _Alloc>::
     ^~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/vector:64:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6/bits/stl_vector.h:450:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::vector<_Tp, _Alloc>&&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
       ^~~~~~~~
/usr/include/c++/6/bits/stl_vector.h:471:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::initializer_list<_Tp>) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(initializer_list<value_type> __l)
       ^~~~~~~~
chainparams.cpp:221:53: error: ambiguous overload for ‘operator=’ (operand types are ‘std::vector<unsigned char>’ and ‘boost::assign_detail::generic_list<int>’)
         base58Prefixes[SCRIPT_ADDRESS] = list_of(196);
                                                     ^
In file included from /usr/include/c++/6/vector:69:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6/bits/vector.tcc:167:5: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
     vector<_Tp, _Alloc>::
     ^~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/vector:64:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6/bits/stl_vector.h:450:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::vector<_Tp, _Alloc>&&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
       ^~~~~~~~
/usr/include/c++/6/bits/stl_vector.h:471:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::initializer_list<_Tp>) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(initializer_list<value_type> __l)
       ^~~~~~~~
chainparams.cpp:222:53: error: ambiguous overload for ‘operator=’ (operand types are ‘std::vector<unsigned char>’ and ‘boost::assign_detail::generic_list<int>’)
         base58Prefixes[SECRET_KEY]     = list_of(239);
                                                     ^
In file included from /usr/include/c++/6/vector:69:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6/bits/vector.tcc:167:5: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
     vector<_Tp, _Alloc>::
     ^~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/vector:64:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6/bits/stl_vector.h:450:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::vector<_Tp, _Alloc>&&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
       ^~~~~~~~
/usr/include/c++/6/bits/stl_vector.h:471:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::initializer_list<_Tp>) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(initializer_list<value_type> __l)
       ^~~~~~~~
chainparams.cpp:223:72: error: ambiguous overload for ‘operator=’ (operand types are ‘std::vector<unsigned char>’ and ‘boost::assign_detail::generic_list<int>’)
      base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF);
                                                                     ^
In file included from /usr/include/c++/6/vector:69:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6/bits/vector.tcc:167:5: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
     vector<_Tp, _Alloc>::
     ^~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/vector:64:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6/bits/stl_vector.h:450:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::vector<_Tp, _Alloc>&&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
       ^~~~~~~~
/usr/include/c++/6/bits/stl_vector.h:471:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::initializer_list<_Tp>) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(initializer_list<value_type> __l)
       ^~~~~~~~
chainparams.cpp:224:72: error: ambiguous overload for ‘operator=’ (operand types are ‘std::vector<unsigned char>’ and ‘boost::assign_detail::generic_list<int>’)
      base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94);
                                                                     ^
In file included from /usr/include/c++/6/vector:69:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6/bits/vector.tcc:167:5: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
     vector<_Tp, _Alloc>::
     ^~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/6/vector:64:0,
                 from chainparamsbase.h:9,
                 from chainparams.h:9,
                 from chainparams.cpp:6:
/usr/include/c++/6/bits/stl_vector.h:450:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::vector<_Tp, _Alloc>&&) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
       ^~~~~~~~
/usr/include/c++/6/bits/stl_vector.h:471:7: note: candidate: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(std::initializer_list<_Tp>) [with _Tp = unsigned char; _Alloc = std::allocator<unsigned char>]
       operator=(initializer_list<value_type> __l)
       ^~~~~~~~
Makefile:3117: recipe for target 'libbitcoin_common_a-chainparams.o' failed
make[2]: *** [libbitcoin_common_a-chainparams.o] Error 1
make[2]: Leaving directory '/home/oscar/src/bitcoin/src'
Makefile:6228: recipe for target 'all-recursive' failed
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory '/home/oscar/src/bitcoin/src'
Makefile:569: recipe for target 'all-recursive' failed
make: *** [all-recursive] Error 1

I think the problem is in the configure step, but I could be wrong:
I have tried running the below command both with and without the --disable-wallet option. It seems to get further with this option, but still crashes with the same error:
$ ./configure CPPFLAGS="-I${BDB_PREFIX}/include/ -O2" LDFLAGS="-L${BDB_PREFIX}/lib/" --with-gui
Why is it failing here? Is there any work around?

Those instructions appear to be several years old, notwithstanding the date at the top of the page.  They are very obsolete and not helpful for the present day.

It's based on Ubuntu 14.04, which dates from 2014.
It is telling you to build version 0.10.0 of Bitcoin Core, which was released in February 2015 and won't work well with the current network.  Moreover it seems to be incompatible with modern compilers, hence the errors you are seeing.
They want you to build Berkeley DB from source, which is pointless.  There are perfectly good packages in Ubuntu.

You can find up-to-date build instructions in the source tree at doc/build-unix.md, or read them online at https://github.com/bitcoin/bitcoin/blob/master/doc/build-unix.md.  However before doing anything else you'll want to git checkout v0.15.1 so that you are looking at the current version (as of this writing).
(By the way you shouldn't need to sudo make.  It's safer to do that as an unprivileged user.)

The Bitcoin core build documentation is a bit convoluted. The easiest way to build is to use the provided dependency make script rather than trying to install the dependencies individually.
In your case it looks like maybe you've got the wrong version of Boost or maybe your gcc version is too old. Either way I'd recommend starting from scratch and use these steps:
$ sudo apt update
$ sudo apt upgrade
$ sudo apt-get install build-essential libtool autotools-dev automake pkg-config libssl-dev libevent-dev bsdmainutils python3 curl
$ sudo git clone https://github.com/bitcoin/bitcoin.git
$ chown -R your_username:your_username /usr/src/bitcoin
$ cd bitcoin/depends
$ make
$ cd ..
$ ./autogen.sh
$ CONFIG_SITE=$PWD/depends/x86_64-pc-linux-gnu/share/config.site ./configure --prefix=/
$ make
$ sudo make install

Please update in 2018, so that it works for new comer.


text:
why did assert fail when creating my own genesis block?
I am trying to create my own genesis block using the bitcoin source code but my new hashes are not being accepted by the assert statements.
Step 1:
I have changed the pszTimestamp variable in chainparams.cpp to generate my own genesis hash.
I have added into the code some print statements to check the genesis hash and merkle root as they are generated from my new pszTimestamp.
The hashes I have generated are:
MERKLE ROOT:9f46bcd8a56be2b6b022acbcc859b201534c21801b1b73685a69de17ad37665e
GENESIS HASH:cc45935bfeb12faacc8ab2797d2f5507f7eef8a44c597f3622c704cc0af8a648
Step 2:
I have changed the assert statements below to assert the new hashes on line 131 and line 230 of chainparams.cpp
The Genesis Block
assert(consensus.hashGenesisBlock==uint256S("0xcc45935bfeb12faacc8ab2797d2f5507f7eef8a44c597f3622c704cc0af8a648"));
The Merkle Root
assert(genesis.hashMerkleRoot==int256S("0x9f46bcd8a56be2b6b022acbcc859b201534c1801b1b73685a69de17ad37665e"));
However...
These assert statements still fail. Why?
I have included the error message below:
bitcoin-qt: chainparams.cpp:230: CTestNetParams::CTestNetParams(): Assertion `consensus.hashGenesisBlock == uint256S("0xcc45935bfeb12faacc8ab2797d2f5507f7eef8a44c597f3622c704cc0af8a648")' failed.
Aborted (core dumped)

Downvoted. We have many questions regarding programming issues when creating a new altcoin. I don't believe such questions benefit a general audience, and this is a Q&A site, not a place for support. Furthermore, as a learning experience, contributing to an existing project is far more valuable.

The question has over 1000 views now so obviously others are facing the issue...

The problem is that you changed the testnet parameters too, not just the mainnet parameters. However I doubt that you regenerated the testnet genesis block, or if you did, you did not set the assert correctly. You set the assert in the testnet chain parameters to be the mainnet genesis block hash and merkle root. But that is obviously wrong; testnet is not the same as mainnet. To fix this, you should either revert the change, or generate a new testnet genesis block and set those asserts accordingly.

If I revert the testnet params back to their original values. I still get an assert error bitcoin-qt: chainparams.cpp:227: CTestNetParams::CTestNetParams(): Assertion consensus.hashGenesisBlock == uint256S("0x000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943")' failed.
Aborted (core dumped)`


text:
High end electrum servers directly reading blk.dat files
These days, high end electrum servers directly read blk.dat files straight from Bitcoin Core's blocks folder in the process of creating their initial internal indexes. I guess they also do in the course of their lifespan to keep indexes in sync, but unsure about that.
First things first, I've just read here that it is bad practice for technical reasons.
Also, Bitcoin Core makes sure those files are readable ONLY by its own user. Thus, the only solution I found to sync those electrum servers is to run them with that same user. Giving rights to those pieces of software to modify block files seems a bit awkward, to say the least.
This concerns me a bit. Many projects need those bitcoin addresses indexes, thus, I guess most of them accept that compromise. I think the best option would be for electrum servers to NOT use those files. Though, the reality we have to live with is that they DO as we speak.
Although the best solution might be for electrum servers to stick to RPC calls, I doubt they will for performance reasons, I guess. Then, why doesn't Bitcoin Core include a configuration switch to at least allow readonly access to those files?

If your question is essentially just a feature request for Bitcoin Core, it should be filed here: https://github.com/bitcoin/bitcoin/issues

I am here to discuss about it with bitcoiners at large

I guess that if the feature isn't available in 2024, there might be a good reason for it... then, maybe electrum server developers might chime in and explain why these apps apparently have to run in the context of Bitcoin Core's user so they can sync their databases.

Hey RooSoft, this site is a Q&A platform, unfortunately it does not work well for discussions. Could you perhaps touch up your post to highlight what question you would like to get answers for?

Well, I want to know how high profile bitcoin services deal with this problem.


text:
Bitcoin not received since 3days now

Two different bitcoin payment was sent I sent into one Wallet Address requested, But only one came into my wallet successfully. But I am yet to receive the second one, and when I try to look it up on blockchain explorer. The only information that comes up, is the bitcoin that came in successfully, But nothing can be found about the second transaction.

You should call their support. They did not make the payment that receipt says that they made.

Okay, thanks a lot....I hope they will have it fixed, because I have really been bothered and been trying to call and message them, But no response yet...Am worried.


text:
What prevents a miner to be ignored by the other participants?
What prevents that certain miners and the blocks they can contribute to the chain are not ignored? What do the other participants in the network gain from  accepting their answers to the puzzle?

Ignored by miners or nodes? For some reason, all the answers so far are explaining why miners shouldn't ignore blocks from other miners. But it's also conceivable that all the nodes connected to a miner could choose ignore its blocks.

@user253751 you can generalize all of the answers to be applicable to network full nodes, just by replacing the idea of being 'incentivized to follow new blocks for the best chance of receiving mining rewards' with 'incentivized to follow new blocks so that you keep up to date with the most current network state'--which is the entire point of running a node in the first place! :)

@chytrik Except I don't think nodes are incentivized to do that. Some nodes are run altruistically by volunteers to improve the network quality, or selfishly to improve the network quality by people who heavily use the network. But nodes have no particular incentive; nothing stops a miner, for example, from deploying nodes that delay blocks mined by other miners. I don't think there is any disincentive against doing this, other than the cost of running the nodes and the low probability of achieving any benefits.

@user253751 running a node grants the user financial sovereignty, that is the incentive. Altruism may occur, but it is most certainly not what keeps the network afloat. What you wrote about a miner running nodes to delay other blocks would be an absolute waste of resources. Miners use specialized networks like FIBRE to communicate extremely efficiently. Running a ‘block delaying node’ would have literally no effect on other miner’s view of the network. See: https://bitcoinfibre.org/

@chytrik but what if they run this nodes to delay other blocks in order to attack the network/a particular miner? Maybe ask for money in order to stop the attack?

@Joan What you described in your comment is known as an eclipse attack. A node on the network needs just one single honest peer to reliably obtain an accurate view of the network, and the peering rules are also designed to help to mitigate such an attack, so it would be very difficult to attack a node in this way, a miner even more so.

Miners don't mine for fun or out of generosity. They mine because they want to get the block reward and the transaction fees. Clients are programmed to choose the "longest" chain, that is, the one that took the most mining work to produce.
Now, say you're a miner who has 1% of the network's hash rate. You're trying to mine block 50,000 when someone else mines a new block 50,000. You have two choices, you can try to mine another block 50,000 or you can try to mine block 50,001 on top of the new one.
If you successfully mine another block 50,000, there is a very low chance anyone will accept it. They already have a block 50,000. However, if you successfully mine a new block 50,001, everyone will accept it because it allows them the chance to mine a longer chain rather than an equally-long chain.
Essentially, because the longest chain wins, everyone wants to mine a block on the longest chain they can. That means that unless you control a huge percentage of the mining power and have a realistic chance of mining two or more blocks in a row, you always want to mine on top of any new block that lengthens the chain.
(By "longest", I mean the one that took the most work to produce.)

IIUC Even if your block 50000 initially gets accepted you run the risk that your block gets retroactivly rejected when a new block 50001 gets published.

@Taemyr Correct. If the other block 50000 was produced first, you lose fair and square. If the other block 50000 was produced after, the person who produced it likely did so unintentionally. If they do so intentionally, they run the high risk that a new block 50001 will be produced on the other block first and then they'll never get any reward.

What do the other participants in the network gain from accepting their answers to the puzzle?

Essentially, consensus.
As long as a miner controls less than 51% of the network hashrate, they must always try to mine on top of the newest block.
If miner A creates block 1000, miner B may ignore it. Let's say B controls 20% of the hashrate. If B continues to mine on block 999, there is an 80% chance that another miner will produce block 1001, linking back to block 1000 - now B needs to find a block for heights 1000 and 1001 to keep up, and is currently out of sync with the network. This gap only grows as more blocks are added to the longer chain (which again will happen more frequently than B discovering a block and working to catch up).
Now, B has found no blocks, and receives no reward - instead, if B accepts A's block 1000 and continues mining on top of the newest block consistently, there is a 20% chance that they will receive the block reward + fees as the block will be part of the main chain the moment is is produced, instead of only being accepted after B is able to produce enough blocks to bridge the gap, which will (probably) not happen until B's hashrate is >=51% of the network hashrate.

This is not really correct. There’s nothing saying that a miner should mine with a majority, and they can’t even define what that is given the participants are anonymous. The white paper for bitcoin even points out the situations and risks for mining forks, and more recent research called selfish mining weakens the system significantly past that.

@Anonymous the idea is that if you control more than half of the hash rate, you can (with high probability) eventually build a longer chain than the rest of the network. If you have less than half of the hash rate, you will (with high probability) build a shorter chain, which won't give you any reward. You don't need to know who the other miners are for doing this.

Bitcoin miners are anonymous. There’s no identifying information in blocks that could be used to censor a particular participant. The attributions for miners shown on block explorers are guesswork presented as fact.

What do the other participants in the network gain from accepting their answers to the puzzle?

There are a number of great answers already, but here is another way to look at it: consider flipping this question around.
What does a miner lose by mining on block X+1 instead of block X?
The answer is: nothing. Assuming an ~equal payout for finding block X and/or block X+1, the miner should not really care what block height they’re mining at. They just want to find a valid block so that they can get paid. As others mentioned, the best chance of getting paid means mining at the chain tip.


text:
Why hardended xpub key cannot generate child public key?
I'm trying to understand bip32 hardened mechanism, but I'm confused about it.
I got xpubKey from this site, and what I'm trying to do is demonstrate failure when trying to generate child pubkey from hardened xpubkey.
Here's my test details.

network : bitcoin testnet
mnemonic : dash axis fat pilot truly river guitar sea tonight popular type ill inmate quote upset
parent path : m/44'
parent xpubKey : tpubDA4h4NTsxqEXATU9dPS22ZVuBHd2jVketkP8RNhBZ6fMhW9WuMhrjf37qNmfmLQZoFreLmHf9LsTnvW2eJYx1fkzo7vVxsf7bKVixz2FjGw
target child path : m/44'/0 (non regular, just for test)

and I wrote some js code, and I assumed to fail, but succeeded.
const bitcoinjs = require('bitcoinjs-lib');

const xpubKey = 'tpubDA4h4NTsxqEXATU9dPS22ZVuBHd2jVk...';

const parentNode = bitcoinjs.bip32.fromBase58(xpubKey, bitcoinjs.networks.testnet);

////////
// I THOUGHT BELOW WILL FAIL!
////////

// trying to get m/44'/0
const derived = parentNode.derive(0);

// result was valid public key for m/44'/0
console.log(derived.publicKey);

In my thought, if I have a valid xpubKey(hardened or not), means that I have a valid chain code and public key for current node (means that I can derive children).
So what's meaning of

Hardened public keys cannot derive any children?

FYI, I quoted that in this video (20:24).

Non-hardened parents effectively use the public key to derive their children, where hardened parents derive their children from the private key.
The derivation of a child private key from a non-hardened parent private key k uses the following hash function:
HMAC-SHA512(chainCode, point(k) || i)

We know that K = point(k), where K is the parent public key. Thus, if we only know K and not necessarily k, we are still able to derive the child key by replacing point(k) with K, and follow the regular process.
With hardened private keys, the hashing is done differently:
HMAC-SHA512(chainCode, 0x00 || k || i)

Here you can see that there is no possible way that you could compute this hmac without knowing k. Just knowing the public key K will not help.

It looks as though you need to use the deriveHardened function in bitcoinjs rather than plain derive.

The even shorter answer is that you cannot derive hardened public keys from xpubs, because hardening is specifically designed to make exactly that impossible.


text:
Improve uniqueness of block for nonce creation
I am going through online Blockchain course and in the course, they have mentioned that uniqueness of a block is defined using hashes with leading zeros as well as timestamp. Since, in the training, they have assumed 18 leading zeros in hashes, the valid hash count is 4 billion. So, with the unique combination, every node has 4 billion valid hashes per second to get the golden nonce. But since all the miners are trying at the same time to generate the nonce, this range gets covered quickly within a second. So for this, the solution is to change block configuration.
My question is -
If per second, all the 4 billion hashes are getting covered without finding golden nonce, why cannot we have 1 more field in the block like node id?
So, the uniqueness of the block can be defined using 3 variables - node id, timestamp and hash. Since node id of the node is unique to the node, every node gets free chance to use up to 4 billion hashes per timestamp.
I am sure this must been thought of by designers or probably I am not thinking properly.

Blocks include more than just those 3 variables. One of the most important ones is the merkle root. This is the hash of all of the transactions in the block, in a particular order. If different transactions are included or they are included in a different order, that merkle root is going to be different. So if each miner has a different merkle root, then they are going to have their own set of nonces to work with. That is what actually provides uniqueness here.
Miners all have different merkle roots. This is because the merkle root includes the transaction that pays the mining reward - the coinbase transaction. Since every miner wants that reward, they will have a coinbase transaction which is different from every miner as it will include their payout address, not someone else's. So by virtue of having different payout addresses in their coinbase transactions, the blocks that miners are working on will be unique and different from other miners.


text:
Tracking incoming transactions using nodejs and own node
I need to verify that user from my database has sent btc to my wallet.
Ideally I want to generate a unique address for each user transaction and then track all those addresses but I suppose it will be difficult to implement due to address gap limit, so I decided to just ask users for their bitcoin address and then expecting tx with funds transfer from that address to my wallet so I can verify funds were sent by them.
I have own bitcoin node which I want to use for tracking all the transactions to my wallet.
So let's say I want to track all txs just to my wallet address.
I was following the guide how to implement this with ZEROMQ. I've updated bitcoind config file with to can listen for raw txs via zeromq.
There are my nodejs code:
const bitcoin = require('bitcoinjs-lib');
const zmq = require('zeromq');

const sock = zmq.socket('sub');
const addr = 'tcp://127.0.0.1:3000';

module.exports = function (app) {

    sock.connect(addr);
    sock.subscribe('rawtx');

    sock.on('message', function (topic, message) {
        if (topic.toString() === 'rawtx') {
            let rawTx = message.toString('hex');
            let tx = bitcoin.Transaction.fromHex(rawTx);
            let txid = tx.getId();

            const address = bitcoin.address.fromOutputScript(tx.outs[0].script, bitcoin.networks.testnet);

            console.log("address ", address)
            console.log('received transaction', txid, tx);
        }
    });
}

As I understand, when I connect to node in live network from this code, I'll be notified about all txs that are happening in the network?
How can I validate transactions with transferring funds only to my wallet and decode address from which funds were transferred?
Are there some easy ways to implement this and maybe some code/project examples?

It's also a good practice to handle block rewards

I was doing almost the same thing you need, to accomplish that I created a database with the addresses I wanted to monitor and keep track of them on the mempool of my fullnode which I could read the transactions and check each one of them if any of my addresses is there if it is I record the txid for further checking.
If the transfer gets confirmed before it is in my mempool (never happened to me) but the logic would simply be to check the block sent by ZMQ scraping all transactions and looking for any of the addresses.


text:
Is it possible to build bitcoin source code into a windows .exe file, using Ubuntu?
I am using an ubuntu machine and have compiled the bitcoin source code a few times without issue. I am able to use bitcoin-qt just fine in the terminal to load the interface, but I'm wondering if I can make the code into a .exe file and put that file onto windows and run the client there without dependencies.
Is it possible to do that? Or will I have to install the dependencies on windows and compile in windows into a binary that requires no dependencies?

Yep you sure can instructions can be found at https://github.com/bitcoin/bitcoin/blob/master/doc/build-windows.md.
And the provided build scripts all use static linking so you end up with one big executable that does not require installing any dependencies on your Windows machine.

In fact, the Bitcoin Core release binaries for Windows are produced using an Ubuntu VM.


text:
How to get historical balance of a Bitcoin address at a particular block number or date?
I would like to get the balance of a Bitcoin address at a particular block number or date.
Is there any way to retrieve this data from JSON-RPC? Alternatively, is there any API or blockchain analytics service that provides this? Thanks.

Account/address balance are higher level constructs that are built on Bitcoin's low-level transaction scripting language and cryptography. As such, data related to funds 'belonging' to a particular address is not readily available in the blockchain, but has to be built separately by scanning the entire database. The Bitcoin-Core reference client does not even support showing 'balances' of address that are not part of your wallet, let alone providing you the data related to a particular address at a particular point in time. You would either have to do this yourself or search for third-party data providers who provide this kind of information through an API (that is off-topic on this forum).

That's rather complicated as "balance" is an higher order construct which exists only at wallet application level.
This means that you need to do some substancial coding.
Anyway, you could approach the problem this way:
1) convert the desired point in time to block height
2) query the blockchain by address. You can easily do that using blockchain.info API
https://blockchain.info/multiaddr?active=$address|$address
the API will return also a list of transactions received/sent by a given address.
3) loop through the transaction list to figure if relevant outputs (UTXOs) ware received and unspent at a given point in time. You can do that by referencing the transaction block height provided by the API after having mapped incoming (received) and outgoing (sent) TXs by cross-referencing TX hashes.

I have written a program in Python3 that allows you to search for any address on bitcoin core whether it belongs to your wallet or not.
Here is the github link:
https://github.com/ORP967/Bitcoin_Core_RPC_par_address
Let me know what you think or if you have any improvements you might have.


text:
Creating a nothing-up-my-sleeve public key
I am trying to create a public key whose x starts with "34" and is followed by the minimum number n such that the concatenation of "34" and n is the x of a valid point (x, y) on the elliptic curve secp256k1. Submit the concatenation of 04, x and y in hexadecimal form. This is a valid bitcoin public key, the corresponding secret key of which is not known by anyone.
I was told that the minimum number is 0.
My understanding is that the answer is supposed to be like this: '0434' + hex(n) + y_value.
I am not sure how to approach this.
Is it true that x-coordinate is supposed to be 32 bytes and y coordinate 32 bytes too?
Is it true that each coordinate is represented in hex mode of 64 chars?
Is the public key represented by 130 hex chars?
I have tried some online tools: e.g. https://iancoleman.io/bitcoin-key-compression/ and some python code but I always get a wrong answer.
X = '0x3400000000000000000000000000000000000000000000000000000000000000'
p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f
print("x coordinate = %s " % X)
x = int(X,16)
print(x)
ysquared = ((x*x*x+7) % p)
print("ysquared= %s " % ysquared)
y = pow(ysquared, (p+1)//4, p)
print("y1 = %s " % hex(y))
print("y2 = %s " % hex((y * -1 % p)))
print("-----------------")
print('04' + X[2:] + hex(y)[2:])
print('04' + X[2:] + hex((y * -1 % p))[2:])

I was told that the minimum number is 0.

That is correct. 0x3400000000000000000000000000000000000000000000000000000000000000 is a valid x-coordinate on secp256k1.

My understanding is that the answer is supposed to be like this: '0434' + hex(n) + y_value. I am not sure how to approach this

That is also correct. However, you will have two y-coordinates. One even and one odd and hence two uncompressed public keys. That is the reason why we append a prefix to the x-coordinate to tell us whether the y-coordinate associated with that x-coordinate is even or odd.

Is it true that x-coordinate is supposed to be 32 bytes and y coordinate 32 bytes too?

That is the maximum size. It can be below that as well.

Is it true that each coordinate is represented in hex mode of 64 chars?

Related to to above. One byte representation needs two hexadecimal characters.

Python code

I'll use the below one.
p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
def modular_sqrt(n, p):
    ''' Find a quadratic residue (mod p) of 'n'. For Bitcoin p is an odd prime, that satisfies
        the identity p % 4 == 3. As a result, this is a simple solution where the modular square
        root of y^2 is : y = pow(y^2, (p + 1) // 4, p).
        If p did not satisfy that identity we would have had to use the Tonelli-Shank's algorithm
    '''
    return pow(n, (p + 1) // 4, p)

def y_coordinate_from_x(x_coordinate_with_prefix):
    public_key_x_coordinate = int(x_coordinate_with_prefix[2:], 16)
    public_key_y_coordinate_sign = int(x_coordinate_with_prefix[:2])
    y_squared = (public_key_x_coordinate**3 + 7) % int(p)
    public_key_y_coordinate = modular_sqrt(y_squared, int(p))

    # check the sign (odd or even) and match that to the sign provided by x-coordinate
    sign_check = 0 if public_key_y_coordinate_sign == 2 else 1
    if int(str(public_key_y_coordinate)[-1:]) % 2 != sign_check:
        public_key_y_coordinate = int(p) - public_key_y_coordinate

    return '%064x'%public_key_y_coordinate

x = '3400000000000000000000000000000000000000000000000000000000000000'
y1 = y_coordinate_from_x('02' + x)
y2 = y_coordinate_from_x('03' + x)

so your uncompressed public keys are '04'+x+y1 and '04'+x+y2

Thank you very much for your reply! Your code produces the same keys as mine though. And if x can be less than 32 bytes then is x=0x320 a valid point on the curve? I tried that too but it is not still the correct answer.

@ΔήμητραΓεωργίου Yes, x can be less than 32 bytes. However, not all points are members of the secp256k1 curve. For example, 0x32 is not a valid x-coordinate but 0x320 is. In most programs (including the one I pasted above), you will need to pad the public key hexadecimal to 32 bytes. Also what do you mean by correct answer?

Thank you again! My professor does not accept '0434000000000000000000000000000000000000000000000000000000000000009d143cafb07ae7ea8025f44c9cf201dc34e4cc71003869b81cca00e0844d16f4' or '04340000000000000000000000000000000000000000000000000000000000000062ebc3504f8518157fda0bb3630dfe23cb1b338effc79647e335ff1e7bb2e53b' as correct answers. Maybe this is what you say now: "pad the public key hexadecimal to 32 bytes".  Could you please explain what you mean?  I have really lost my mind over this.

@ΔήμητραΓεωργίου Hey, so both the keys that you mentioned are valid points on the secp256k1 curve and as such are valid Bitcoin public keys. disregard the padding, it was related to something else that might just confuse you.

Ok! Do you you know what is the answer to the above problem because I still don't know. Thank you again!

@ΔήμητραΓεωργίου you gotta ask your professor why he doesn't accept it (I wouldn't know about his thought process). The public keys you mentioned are valid Bitcoin public keys. May be he/she is looking for compressed public keys (the ones with just the x-coordinate and the sign of the y-coordinate as prefix)?

authors: Δήμητρα Γεωργίου


text:
Create a 2-of-3 multisig raw transaction
I would like to create a Bitcoin transaction with a single input and a single 2-of-3 multisig output that pays 1 BTC to any 2 of the following 3 keys:
02983a79d2de8e504d00ddd2343b582acef7e17ed91b308ade8dff027a92e7716d, 03548ca1916957bc06dd1c6e3639ebf7b2c3c8b1715915433c1d37cab56fb26ef0, and
0218a240a599ba437cb1458966eb456d9f848e5bdef45ea0ee4ec31fc40aa4ffa8.
I just want a syntactically valid transaction, the reference to the UTXO does not have to exist.
Could you please guide me through the steps?

are you using the Bitcoin Core cli, or looking for a step by step in terms of how it is done?

Thank you for answering. I tried with bitcoin-cli but I could not continue. I have done this: createmultisig 2 '["02983a79d2de8e504d00ddd2343b582acef7e17ed91b308ade8dff027a92e7716d","03548ca1916957bc06dd1c6e3639ebf7b2c3c8b1715915433c1d37cab56fb26ef0","0218a240a599ba437cb1458966eb456d9f848e5bdef45ea0ee4ec31fc40aa4ffa8"]'......./bitcoind createrawtransaction '[{"txid" : "d6f72aab8ff86ff6289842a0424319bf2ddba85dc7c52757912297f948286389","vout":0}]' '{"3DjMQ5f21bGg2LBhxwHAMW1MzoKH8TJ8eS":1}'

that should work, what is the issue?

I do not know how to continue. I have to sign it then I think but I cannot use signrawtransaction. I have to use another one but I got stuck.

You almost have it, you just need to make sure you are creating a transaction with an output that your wallet can sign.
Example (on regtest)
bitcoin-cli -regtest addmultisigaddress 2 '["02983a79d2de8e504d00ddd2343b582acef7e17ed91b308ade8dff027a92e7716d","03548ca1916957bc06dd1c6e3639ebf7b2c3c8b1715915433c1d37cab56fb26ef0","0218a240a599ba437cb1458966eb456d9f848e5bdef45ea0ee4ec31fc40aa4ffa8"]'
￼
{
  "address": "2NA1HC31wqFexbpp8bGB6rsMR5Lz9SrUKkt",
  "redeemScript": "522102983a79d2de8e504d00ddd2343b582acef7e17ed91b308ade8dff027a92e7716d2103548ca1916957bc06dd1c6e3639ebf7b2c3c8b1715915433c1d37cab56fb26ef0210218a240a599ba437cb1458966eb456d9f848e5bdef45ea0ee4ec31fc40aa4ffa853ae"
}
￼
bitcoin-cli -regtest getnewaddress
￼
2NAsEawSCjsjJjtAZcpP9jhXojqNUevjo63
￼
bitcoin-cli -regtest generatetoaddress 110 2NAsEawSCjsjJjtAZcpP9jhXojqNUevjo63
￼
[
  "7e974615714bdcee6f4c69ea158b92fe2c0b728742110737e7ff13d9e8eb49ad",
  ...
]
￼
bitcoin-cli -regtest listunspent
￼
[
  ...
  {
    "txid": "9c9298a5d7ceca73f657110c0222ee606324263694d59722a2194b22ccc8b0ff",
    "vout": 0,
    "address": "2NAsEawSCjsjJjtAZcpP9jhXojqNUevjo63",
    "label": "",
    "redeemScript": "0014821824c23b9c82fa639789bc3314194d1e44ec4a",
    "scriptPubKey": "a914c1499c99d26f5bb7101f1213747bf730c4b9346287",
    "amount": 50.00000000,
    "confirmations": 102,
    "spendable": true,
    "solvable": true,
    "desc": "sh(wpkh([29b8db74/0'/0'/0']03557ff8751b55175307c0550460694dfe3c84598672fe5b9c53dca71bcb9122ee))#25k8n2ql",
    "safe": true
  }
]
￼
bitcoin-cli -regtest createrawtransaction '[{"txid" : "9c9298a5d7ceca73f657110c0222ee606324263694d59722a2194b22ccc8b0ff","vout":0}]' '{"2NA1HC31wqFexbpp8bGB6rsMR5Lz9SrUKkt":49.999}'
￼
0200000001ffb0c8cc224b19a22297d5943626246360ee22020c1157f673caced7a598929c0000000000ffffffff01606b042a0100000017a914b7d6fcff0fe015a393f8baee424ba82c4e18c6d48700000000
￼
bitcoin-cli -regtest signrawtransactionwithwallet 0200000001ffb0c8cc224b19a22297d5943626246360ee22020c1157f673caced7a598929c0000000000ffffffff01606b042a0100000017a914b7d6fcff0fe015a393f8baee424ba82c4e18c6d48700000000
￼
{
  "hex": "02000000000101ffb0c8cc224b19a22297d5943626246360ee22020c1157f673caced7a598929c0000000017160014821824c23b9c82fa639789bc3314194d1e44ec4affffffff01606b042a0100000017a914b7d6fcff0fe015a393f8baee424ba82c4e18c6d487024730440220249224a99d24a0ae1d91328ea2e8da0936916ea31a28e35013de003af72f658d02201c48618283ac00a8c5b362e8ade530f4cfacd396a99ab78081cea2d18ad8d165012103557ff8751b55175307c0550460694dfe3c84598672fe5b9c53dca71bcb9122ee00000000",
  "complete": true
}

bitcoin-cli -regtest sendrawtransaction 02000000000101ffb0c8cc224b19a22297d5943626246360ee22020c1157f673caced7a598929c0000000017160014821824c23b9c82fa639789bc3314194d1e44ec4affffffff01606b042a0100000017a914b7d6fcff0fe015a393f8baee424ba82c4e18c6d487024730440220249224a99d24a0ae1d91328ea2e8da0936916ea31a28e35013de003af72f658d02201c48618283ac00a8c5b362e8ade530f4cfacd396a99ab78081cea2d18ad8d165012103557ff8751b55175307c0550460694dfe3c84598672fe5b9c53dca71bcb9122ee00000000

8b0cd4413dad3e1f02f7344236ba4b3d1994c3cd3bbdda1acc9b2d2c0e184453

Thank you very much!! Could you please also tell me what would I do differently if I did not want P2SH but a simple locking script?

no problem! I don't think there is a built-in way to do that in Bitcoin Core, you'll have to use createrawtransaction but instead of using address in the output section, use raw hex data that you've created with the raw scripts: https://bitcoincore.org/en/doc/0.18.0/rpc/rawtransactions/createrawtransaction/

so it will be something like this: bitcoin-cli -regtest createrawtransaction "[{"txid":"9c9298a5d7ceca73f657110c0222ee606324263694d59722a2194b22ccc8b0ff","vout":0}]" "[{"data":hex}]". Do you also know how would I state the amount of BTC spent and what is this hexadecimal value? Again thank you so much!

Yeah, but that's a lot more involved, you could search for how a transaction  is built and how multisig scripts are built

authors: Δήμητρα Γεωργίου


text:
Miners conceding forks
When bitcoin forks, does anyone know how many blocks ahead one chain gets before the miners on the shorter chain concede?
I am doing a research project on modeling Bitcoin, and I am wondering how realistic it is for miners to abandon their chain as soon as they receive a chain that is one longer than the one they have.
I imagine that as chains get longer (and more money/computational work is at stake) miners are more likely to try to catch up from a 'deficit' of one block.
There is also the fact that a miner with sufficient hashing power (40+ percent) has a reasonable chance of catching up from being behind.
Any thoughts on this stuff?

Miners are incentivized to always mine at the longest valid chain tip. If there were incentives to not mine on the longest known chain, then we would expect the network to be unable to maintain consensus on the blockchain's state. And without that, it would be impossible to build a reliable financial system.
So it isn't about 'miners conceding a shorter chain', its just that miners will always all be mining at the chain tip. Currently, the majority of the block reward is constant (the newly minted coins), so a miner should not really care if they mine block X or block X+1: their reward will be ~the same in either case. As such, a miner is incentivized to just mine at the chain tip, because the chance of finding a valid block at either height is equivalent, but the potential reward for finding one at the chain tip (thus extending the longest chain) is much larger. Finding a block at a height that has already been found will likely mean the miner gets no reward, since that block will be rejected by the network as not being a part of the longest chain.
All of the above concerns situations in which there is not a fork due to a change in consensus code, just the regular competition between miners. If you mean to ask about forks caused by changes in consensus code, you'll need to be a little more specific, as the nature of the code change will affect the game theory. But in general: Bitcoin works because miners are incentivized to mine at the chain tip. Without this incentive, the system would likely not achieve the stability required to give any sort of reliability guarantee.

I understand what you are saying, but I am worried about this situation:                     Two miners find a block around the same time. Both get a bitcoin block reward. One extends his chain, so the other either has to concede that his bitcoin reward is no longer considered valid, or attempt to "catch up" and make his chain longest again. I may be misunderstood, but I believe this could happen in real life.

@user97236 This indeed happens all the time, and it's the reason why mining exists in the first place. The answer is that in this case the miner is still incentivized to switch, because if he observes the other fork being extended, he can assume that the rest of the network also switched to that fork, and thus even if he would succeed in extended his own fork, he is less likely to succeed to find 2 blocks in the same time as the rest of the network can find one.

@user97236 yes, that situation is possible and expected, the losing block is commonly referred to as an ‘orphan block’. If you search for that term on this site you’ll find lots of info. The losing miner’s most profitable play is to abandon their block and continue mining at the chain tip. Unless they have a majority of hashing power (>50%), they would be incurring a massive opportunity cost by attempting to outrun the rest of the network, with a low chance of success.

Thanks for the input guys, I think I understand now. The only people who wouldn't switch over to the longest chain right away are those who have blocks in the orphan chain. So this is at most k people if the fork is k long.

@user97236 even miners who found the block(s) on the shorter chain will maximize their expected profit by immediately switching to the longest chain. Note that it is exceedingly rare for an orphan block chain to be longer than one block.


text:
Mining Probability
Assuming two miners have a (1/x) chance of finding a block over some time period, is the probability of both miners finding a block within that period simply (1/x^2)?
More generally, would  n miners with equal hash rates have a (1/x^n) chance of all finding blocks within some time period of each other?
This is for a research project where mining probabilities are being factored into a simulation, and I'm not sure if certain configurations are eliminated when the first miner finds a block (ie they would be dependent events)

In addition to what @JBaczuk wrote, you may be interested to learn more about orphan blocks, which are created when two miners find a valid block within the latency period of block transmission across the network.
In practice, the amount of time passing between the finding of a valid block, and that block propagating across the network is very, very small, as much work has been done to optimize the network for fast block transmission (see: the FIBRE network). But within that small window of time, there is a small chance that two miners would find competing blocks.
Keep in mind: if a miner has ~10% of the hashrate, then they have a ~10% chance of finding a new block within the next 10 minutes. The chance of them finding a block within a time period of a couple seconds would be much smaller. The chance of two miners finding competing blocks within those couple of seconds would become even much smaller still!

Would it make sense to use a Poisson distribution here? The idea is that you could assume a block is found every 10 minutes on average, so the chances of finding two blocks within 60 seconds is something like 0.45%. Of course this seems like a pretty generous upper bound assuming a network without any adversarial nodes purposely not propagating solutions. And I guess there is also the external consideration that this refers to two blocks in one minute, and not necessarily two blocks that have the same parent (ie a fork)

@user97236 yes, mining can be modelled as a Poisson process. I'd agree about the external consideration of whether two blocks being found have the same parent or not, but this externality will not affect the probabilities of finding some block, just the higher-level condition of block competition/validity.

Assuming two miners have a (1/x) chance of finding a block over some time period, is the probability of both miners finding a block within that period simply (1/x^2)?
More generally, would n miners with equal hash rates have a (1/x^n) chance of all finding blocks within some time period of each other?

I believe these are both correct assuming the miners are working independently of each other.
In practice, however, as soon as a miner finds a block, it is in their best interest to publish that to the network as soon as possible to prevent another from publishing a block before them. So, there is a certain amount of time where the new block will propagate across the network after which a miner will not attempt to mine that old block anymore (usually seconds), so network latency has an effect here.