Bitcoin Transaction Сonfirmation - BitcoinWiki

For devs and advanced users that are still in the dark: Read this to get redpilled about why Bitcoin (SV) is the real Bitcoin

This post by cryptorebel is a great intro for newbies. Here is a continuation for a technical audience. I'll be making edits for readability and maybe even add more content.
The short explanation of why BSV is the real Bitcoin is that it implements the original L1 scripting language, and removes hacks like p2sh. It also removes the block size limit, and yes that leads to a small number of huge nodes. It might not be the system you wanted. Nodes are miners.
The key thing to understand about the UTXO architecture is that it is maximally "sharded" by default. Logically dependent transactions may require linear span to construct, but they can be validated in sublinear span (actually polylogarithmic expected span). Constructing dependent transactions happens out-of-band in any case.
The fact that transactions in a block are merkelized is an obvious sign that Bitcoin was designed for big blocks. But merkle trees are only half the story. UTXOs are essentially hash-addressed stateful continuation snapshots which can also be "merged" (validated) in a tree.
I won't even bother talking about how broken Lightning Network is. Of all the L2 scaling solutions that could have been used with small block sizes, it's almost unbelievable how many bad choices they've made. We should be kind to them and assume it was deliberate sabotage rather than insulting their intelligence.
Segwit is also outside the scope of this post.
However I will briefly hate on p2sh. Imagine seeing a stunted L1 script language, and deciding that the best way to implement multisigs was a soft-fork patch in the form of p2sh. If the intent was truly backwards-compatability with old clients, then by that logic all segwit and p2sh addresses are supposed to only be protected by transient rules outside of the protocol. Explain that to your custody clients.
As far as Bitcoin Cash goes, I was in the camp of "there's still time to save BCH" until not too long ago. Unfortunately the galaxy brains behind BCH have doubled down on their mistakes. Again, it is kinder to assume deliberate sabotage. (As an aside, the fact that they didn't embrace the name "bcash" when it was used to attack them shows how unprepared they are when the real psyops start to hit. Or, again, that the saboteurs controlled the entire back-and-forth.)
The one useful thing that came out of BCH is some progress on L1 apps based on covenants, but the issue is that they are not taking care to ensure every change maintains the asymptotic validation complexity of bitcoin's UTXO.
Besides that, The BCH devs missed something big. So did I.
It's possible to load the entire transaction onto the stack without adding any new opcodes. Read this post for a quick intro on how transaction meta-evaluation leads to stateful smart contract capabilities. Note that it was written before I understood how it was possible in Bitcoin, but the concept is the same. I've switching to developing a language that abstracts this behavior and compiles to bitcoin's L1. (Please don't "told you so" at me if you just blindly trusted nChain but still can't explain how it's done.)
It is true that this does not allow exactly the same class of L1 applications as Ethereum. It only allows those than can be made parallel, those that can delegate synchronization to "userspace". It forces you to be scalable, to process bottlenecks out-of-band at a per-application level.
Now, some of the more diehard supporters might say that Satoshi knew this was possible and meant for it to be this way, but honestly I don't believe that. nChain says they discovered the technique 'several years ago'. OP_PUSH_TX would have been a very simple opcode to include, and it does not change any aspect of validation in any way. The entire transaction is already in the L1 evaluation context for the purpose of checksig, it truly changes nothing.
But here's the thing: it doesn't matter if this was a happy accident. What matters is that it works. It is far more important to keep the continuity of the original protocol spec than to keep making optimizations at the protocol level. In a concatenative language like bitcoin script, optimized clients can recognize "checksig trick phrases" regardless of their location in the script, and treat them like a simple opcode. Script size is not a constraint when you allow the protocol to scale as designed. Think of it as precompiles in EVM.
Now let's address Ethereum. V. Buterin recently wrote a great piece about the concept of credible neutrality. The only way for a blockchain system to achieve credible neutrality and long-term decentralization of power is to lock down the protocol rules. The thing that caused Ethereum to succeed was the yellow paper. Ethereum has outperformed every other smart contract platform because the EVM has clear semantics with many implementations, so people can invest time and resources into applications built on it. The EVM is apolitical, the EVM spec (fixed at any particular version) is truly decentralized. Team Ethereum can plausibly maintain credibility and neutrality as long as they make progress towards the "Serenity" vision they outlined years ago. Unfortunately they have already placed themselves in a precarious position by picking and choosing which catastrophes they intervene on at the protocol level.
But those are social and political issues. The major technical issue facing the EVM is that it is inherently sequential. It does not have the key property that transactions that occur "later" in the block can be validated before the transactions they depend on are validated. Sharding will hit a wall faster than you can say "O(n/64) is O(n)". Ethereum will get a lot of mileage out of L2, but the fundamental overhead of synchronization in L1 will never go away. The best case scaling scenario for ETH is an L2 system with sublinear validation properties like UTXO. If the economic activity on that L2 system grows larger than that of the L1 chain, the system loses key security properties. Ethereum is sequential by default with parallelism enabled by L2, while Bitcoin is parallel by default with synchronization forced into L2.
Finally, what about CSW? I expect soon we will see a lot of people shouting, "it doesn't matter who Satoshi is!", and they're right. The blockchain doesn't care if CSW is Satoshi or not. It really seems like many people's mental model is "Bitcoin (BSV) scales and has smart contracts if CSW==Satoshi". Sorry, but UTXO scales either way. The checksig trick works either way.
Coin Woke.
submitted by -mr-word- to bitcoincashSV [link] [comments]

Technical: The `SIGHASH_NOINPUT` Debate! Chaperones and output tagging and signature replay oh my!

Bitcoin price isn't moving oh no!!! You know WHAT ELSE isn't moving?? SIGHASH_NOINPUT that's what!!!
Now as you should already know, Decker-Russell-Osuntokun ("eltoo") just ain't possible without SIGHASH_NOINPUT of some kind or other. And Decker-Russell-Osuntokun removes the toxic waste problem (i.e. old backups of your Poon-Dryja LN channels are actively dangerous and could lose your funds if you recover from them, or worse, your most hated enemy could acquire copies of your old state and make you lose funds). Decker-Russell-Osuntokun also allows multiparticipant offchain cryptocurrency update systems, without the drawback of a large unilateral close timeout that Decker-Wattenhofer does, making this construction better for use at the channel factory layer.
Now cdecker already wrote a some code implementing SIGHASH_NOINPUT before, which would make it work in current pre-SegWit P2PKH, P2SH, as well as SegWit v0 P2WPKH and P2WSH. He also made and published BIP 118.
But as is usual for Bitcoin Core development, this triggered debate, and thus many counterproposals were made and so on. Suffice it to say that the simple BIP 118 looks like it won't be coming into Bitcoin Core anytime soon (or possibly at all).
First things first: This link contains all that you need to know, but hey, maybe you'll find my take more amusing.
So let's start with the main issue.

Signature Replay Attack

The above is the Signature Replay Attack, and the reason why SIGHASH_NOINPUT has triggered debate as to whether it is safe at all and whether we can add enough stuff to it to ever make it safe.
Now of course you could point to SIGHASH_NONE which is even worse because all it does is say "I am authorizing the spend of this particular coin of this particular value protected by my key" without any further restrictions like which outputs it goes to. But then SIGHASH_NONE is intended to be used to sacrifice your money to the miners, for example if it's a dust attack trying to get you to spend, so you broadcast a SIGHASH_NONE signature and some enterprising miner will go get a bunch of such SIGHASH_NONE signatures and gather up the dust in a transaction that pays to nobody and gets all the funds as fees. And besides; even if we already have something you could do stupid things with, it's not a justification for adding more things you could do stupid things with.
So yes, SIGHASH_NOINPUT makes Bitcoin more powerful. Now, Bitcoin is a strong believer in "Principle of Least Power". So adding more power to Bitcoin via SIGHASH_NOINPUT is a violation of Principle of Least Power, at least to those arguing to add even more limits to SIGHASH_NOINPUT.
I believe nullc is one of those who strongly urges for adding more limits to SIGHASH_NOINPUT, because it distracts him from taking pictures of his autonomous non-human neighbor, a rather handsome gray fox, but also because it could be used as the excuse for the next MtGox, where a large exchange inadvertently pays to SIGHASH_NOINPUT-using addresses and becomes liable/loses track of their funds when signature replay happens.

Output Tagging

Making SIGHASH_NOINPUT safer by not allowing normal addresses use it.
Basically, we have 32 different SegWit versions. The current SegWit addresses are v0, the next version (v1) is likely to be the Schnorr+Taproot+MAST thing.
What output tagging proposes is to limit SegWit version ranges from 0->15 in the bech32 address scheme (instead of 0->31 it currently has). Versions 16 to 31 are then not valid bech32 SegWit addresses and exchanges shouldn't pay to it.
Then, we allow the use of SIGHASH_NOINPUT only for version 16. Version 16 might very well be Schnorr+Taproot+MAST, with a side serving of SIGHASH_NOINPUT.
This is basically output tagging. SIGHASH_NOINPUT can only be used if the output is tagged (by paying to version 16 SegWit) to allow it, and addresses do not allow outputs to be tagged as such, removing the potential liability of large custodial services like exchanges.
Now, Decker-Russell-Osuntokun channels have two options:
The tradeoffs in this case are:
The latter tradeoff is probably what would be taken (because we're willing to pay for privacy) if Bitcoin Core decides in favor of tagged outputs.
Another issue here is --- oops, P2SH-Segwit wrapped addresses. P2SH can be used to wrap any SegWit payment script, including payments to any SegWit version, including v16. So now you can sneak in a SIGHASH_NOINPUT-enabled SegWit v16 inside an ordinary P2SH that wraps a SegWit payment. One easy way to close this is just to disallow P2SH-SegWit from being valid if it's spending to SegWit version >= 16.

Chaperone Signatures

Closing the Signature Replay Attack by adding a chaperone.
Now we can observe that the Signature Replay Attack is possible because only one signature is needed, and that signature allows any coin of appropriate value to be spent.
Adding a chaperone signature simply means requiring that the SCRIPT involved have at least two OP_CHECKSIG operations. If one signature is SIGHASH_NOINPUT, then at least one other signature (the chaperone) validated by the SCRIPT should be SIGHASH_ALL.
This is not so onerous for Decker-Russell-Osuntokun. Both sides can use a MuSig of their keys, to be used for the SIGHASH_NOINPUT signature (so requires both of them to agree on a particular update), then use a shared ECDH key, to be used for the SIGHASH_ALL signature (allows either of them to publish the unilateral close once the update has been agreed upon).
Of course, the simplest thing to do would be for a BOLT spec to say "just use this spec-defined private key k so we can sidestep the Chaperone Signatures thing". That removes the need to coordinate to define a shared ECDH key during channel establishment: just use the spec-indicated key, which is shared to all LN implementations.
But now look at what we've done! We've subverted the supposed solution of Chaperone Signatures, making them effectively not there, because it's just much easier for everyone to use a standard private key for the chaperone signature than to derive a separate new keypair for the Chaperone.
So chaperone signatures aren't much better than just doing SIGHASH_NOINPUT by itself, and you might as well just use SIGHASH_NOINPUT without adding chaperones.
I believe ajtowns is the primary proponent of this proposal.

Toys for the Big Boys

The Signature Replay Attack is Not A Problem (TM).
This position is most strongly held by RustyReddit I believe (he's the Rusty Russell in the Decker-Russell-Osuntokun). As I understand it, he is more willing to not see SIGHASH_NOINPUT enabled, than to have it enabled but with restrictions like Output Tagging or Chaperone Signatures.
Basically, the idea is: don't use SIGHASH_NOINPUT for normal wallets, in much the same way you don't use SIGHASH_NONE for normal wallets. If you want to do address reuse, don't use wallet software made by luke-jr that specifically screws with your ability to do address reuse.
SIGHASH_NOINPUT is a flag for use by responsible, mutually-consenting adults who want to settle down some satoshis and form a channel together. It is not something that immature youngsters should be playing around with, not until they find a channel counterparty that will treat this responsibility properly. And if those immature youngsters playing with their SIGHASH_NOINPUT flags get into trouble and, you know, lose their funds (as fooling around with SIGHASH_NOINPUT is wont to do), well, they need counseling and advice ("not your keys not your coins", "hodl", "SIGHASH_NOINPUT is not a toy, but something special, reserved for those willing to take on the responsibility of making channels according to the words of Decker-Russell-Osuntokun"...).


Dunno yet. It's still being debated! So yeah. SIGHASH_NOINPUT isn't moving, just like Bitcoin's price!!! YAAAAAAAAAAAAAAAAAAA.
submitted by almkglor to Bitcoin [link] [comments]

Why CHECKDATASIG Does Not Matter

Why CHECKDATASIG Does Not Matter

In this post, I will prove that the two main arguments against the new CHECKDATASIG (CDS) op-codes are invalid. And I will prove that two common arguments for CDS are invalid as well. The proof requires only one assumption (which I believe will be true if we continue to reactive old op-codes and increase the limits on script and transaction sizes [something that seems to have universal support]):
ASSUMPTION 1. It is possible to emmulate CDS with a big long raw script.

Why are the arguments against CDS invalid?

Easy. Let's analyse the two arguments I hear most often against CDS:

ARG #1. CDS can be used for illegal gambling.

This is not a valid reason to oppose CDS because it is a red herring. By Assumption 1, the functionality of CDS can be emulated with a big long raw script. CDS would not then affect what is or is not possible in terms of illegal gambling.

ARG #2. CDS is a subsidy that changes the economic incentives of bitcoin.

The reasoning here is that being able to accomplish in a single op-code, what instead would require a big long raw script, makes transactions that use the new op-code unfairly cheap. We can shoot this argument down from three directions:
(A) Miners can charge any fee they want.
It is true that today miners typically charge transaction fees based on the number of bytes required to express the transaction, and it is also true that a transaction with CDS could be expressed with fewer bytes than the same transaction constructed with a big long raw script. But these two facts don't matter because every miner is free to charge any fee he wants for including a transaction in his block. If a miner wants to charge more for transactions with CDS he can (e.g., maybe the miner believes such transactions cost him more CPU cycles and so he wants to be compensated with higher fees). Similarly, if a miner wants to discount the big long raw scripts used to emmulate CDS he could do that too (e.g., maybe a group of miners have built efficient ways to propagate and process these huge scripts and now want to give a discount to encourage their use). The important point is that the existence of CDS does not impeded the free market's ability to set efficient prices for transactions in any way.
(B) Larger raw transactions do not imply increased orphaning risk.
Some people might argue that my discussion above was flawed because it didn't account for orphaning risk due to the larger transaction size when using a big long raw script compared to a single op-code. But transaction size is not what drives orphaning risk. What drives orphaning risk is the amount of information (entropy) that must be communicated to reconcile the list of transactions in the next block. If the raw-script version of CDS were popular enough to matter, then transactions containing it could be compressed as
....CDS'(signature, message, public-key)....
where CDS' is a code* that means "reconstruct this big long script operation that implements CDS." Thus there is little if any fundamental difference in terms of orphaning risk (or bandwidth) between using a big long script or a single discrete op code.
(C) More op-codes does not imply more CPU cycles.
Firstly, all op-codes are not equal. OP_1ADD (adding 1 to the input) requires vastly fewer CPU cycles than OP_CHECKSIG (checking an ECDSA signature). Secondly, if CDS were popular enough to matter, then whatever "optimized" version that could be created for the discrete CDS op-codes could be used for the big long version emmulating it in raw script. If this is not obvious, realize that all that matters is that the output of both functions (the discrete op-code and the big long script version) must be identical for all inputs, which means that is does NOT matter how the computations are done internally by the miner.

Why are (some of) the arguments for CDS invalid?

Let's go through two of the arguments:

ARG #3. It makes new useful bitcoin transactions possible (e.g., forfeit transactions).

If Assumption 1 holds, then this is false because CDS can be emmulated with a big long raw script. Nothing that isn't possible becomes possible.

ARG #4. It is more efficient to do things with a single op-code than a big long script.

This is basically Argument #2 in reverse. Argument #2 was that CDS would be too efficient and change the incentives of bitcoin. I then showed how, at least at the fundamental level, there is little difference in efficiency in terms of orphaning risk, bandwidth or CPU cycles. For the same reason that Argument #2 is invalid, Argument #4 is invalid as well. (That said, I think a weaker argument could be made that a good scripting language allows one to do the things he wants to do in the simplest and most intuitive ways and so if CDS is indeed useful then I think it makes sense to implement in compact form, but IMO this is really more of an aesthetics thing than something fundamental.)
It's interesting that both sides make the same main points, yet argue in the opposite directions.
Argument #1 and #3 can both be simplified to "CDS permits new functionality." This is transformed into an argument against CDS by extending it with "...and something bad becomes possible that wasn't possible before and so we shouldn't do it." Conversely, it is transformed to an argument for CDS by extending it with "...and something good becomes possible that was not possible before and so we should do it." But if Assumption 1 holds, then "CDS permits new functionality" is false and both arguments are invalid.
Similarly, Arguments #2 and #4 can both be simplified to "CDS is more efficient than using a big long raw script to do the same thing." This is transformed into an argument against CDS by tacking on the speculation that "...which is a subsidy for certain transactions which will throw off the delicate balance of incentives in bitcoin!!1!." It is transformed into an argument for CDS because "... heck, who doesn't want to make bitcoin more efficient!"

What do I think?

If I were the emperor of bitcoin I would probably include CDS because people are already excited to use it, the work is already done to implement it, and the plan to roll it out appears to have strong community support. The work to emulate CDS with a big long raw script is not done.
Moving forward, I think Andrew Stone's (thezerg1) approach outlined here is an excellent way to make incremental improvements to Bitcoin's scripting language. In fact, after writing this essay, I think I've sort of just expressed Andrew's idea in a different form.
* you might call it an "op code" teehee
submitted by Peter__R to btc [link] [comments]

/u/Septem_151 on Cybercash, as imagined in 1998

TL;DR: A Transaction Input is what reveals your public key, not the Transaction Output, and an address represents the hash of a Public Key.
UTXOs that are P2PKH (Pay to Pub Key Hash) go to the hash of a public key. More specifically, the following script, known as the scriptPubKey, is pushed onto a stack: OP_DUP OP_HASH160 OP_EQUALVERIFY OP_CHECKSIG
These operations define how the coins are allowed to be spent. OP_DUP = Duplicate the top item of the stack, OP_HASH160 = Popping the top of the stack and pushing the RIPEMD-160 hash of the SHA-256 hash of the popped data back onto the stack, = Pushing the recipient’s decoded Address onto the stack, OP_EQUALVERIFY = checking if the top two values on the stack are equal and popping them if true, and OP_CHECKSIG = checks if the signature is verified by the public key on the stack (more on this later). For more information, check the bitcoin wiki’s section on bitcoin script.
A legacy bitcoin address (beginning with a 1) is just a public key hash that is encoded in Base58 with a version byte (0x00) prepended, and a checksum appended to the end. To convert an address to a PubKeyHash is as simple as decoding from Base58.
However, when a UTXO is Spent, the spender must prove ownership by providing some additional values to satisfy the UTXO’s scriptPubKey. This combination of values is known as the scriptSig, and for P2PKH consists of two parts: Signature>
When a Transaction is evaluated and verified, the input’s scriptSig and the scriptPubKey of the output it’s spending are placed onto a stack so the whole thing becomes: OP_DUP OP_HASH160 OP_EQUALVERIFY OP_CHECKSIG
First, the signature is pushed to the stack. Then the public key associated with the bitcoin address. OP_DUP duplicates the public key, OP_HASH160 pops the public key off the stack and pushes the hash of the public key onto the stack. Then the PubKeyHash whom the coins belongs to is pushed to the stack. Then OP_EQUALVERIFY checks to see if the public key does indeed hash to the specified PubKeyHash. If true, the two values are popped off the stack. Then OP_CHECKSIG takes the last two elements from the stack (the signature and the unhashed public key) and checks if the signature is valid. If true, the input is valid and “unlocks” the UTXO for spending.
This is a big part of why you should not reuse addresses: only when you SPEND a UTXO do you reveal your Public Key to the world. Until spent, your public key is secured behind other barriers (SHA-256 and RIPEMD-160). If Elliptic Curve cryptography is to be broken by quantum computers, it will also need to break the hashing algorithms above as well to at least invalidate P2PKH outputs. Back in the very early days, some Outputs were made using P2PK (Pay to Pub Key) which does not use this intermediary hashing technique and is considered far less secure, thus it is rarely used today if at all.
submitted by highhighhopes101 to TalkativePeople [link] [comments]

As part of my ongoing effort to develop stupid shit for Garlicoin, I present you: W-addresses!

“Wait, what?!” I hear you asking? Well…(buckle up, this is another one of my technical posts that goes on, and on…)
For some time now, I have been using native SegWit (Pay-to-Witness-Public-Key-Hash, P2WPKH) transactions for myself. Mostly because they have a 75% fee subsidy on signature data (which comes out on ~50% fee subsidy on the entire transaction, depending on the type of transaction) and I am dutch after all ;-)
It turns out that Garlicoin Core kind of supports them and kind of does not. If you manually register the transaction redeem script to your wallet (using the addwitnessaddress command) it will start recognizing them on the blockchain but gets kind of confused on how to deal with them, so it registers them all as ‘change’ transactions. Still, this means you can receive coins using these types of transactions and pay with them in all ways you can with regular Garlicoins, except your transactions are cheaper.
However, sending coins using native SegWit is quite a hassle. You can basically only do it by creating your own raw transactions (createrawtransaction, edit it to make it native SegWit, fundrawtransaction, signrawtransaction, sendrawtransaction). On top of this, any change address the wallet creates are still legacy/normal Garlicoin addresses, so you will end up with a bunch of unspent transaction outputs (UTXOs) for which you have to pay full fee anyway. I decided we (I) could do better than this.
But first a few steps back. What is this native SegWit anyway and weren’t people already using SegWit? Wasn’t there a user that just after mainnet launched accidentally made a SegWit transaction? So what the hell am I talking about?
To understand this, you will need to know a few things about what SegWit is and how Bitcoin Garlicoin transactions work in general. Note that this bit gets really technical, so if you are not interested, you might want to skip ahead. A lot.
First thing to understand is that addresses are not really a thing if you look at the blockchain. While nodes and explorers will interpret parts of a transaction as addresses, in reality addresses are just an abstraction around Bitcoin Script and an easy way send coins instead of asking people “hey, can you send some coins to the network in such a way that only the private key that corresponds to public key XYZ can unlock them?”. Let’s look at an example: say I ask you to send coins to my address GR1Vcgj2r6EjGQJHHGkAUr1XnidA19MrxC. What ends up happening is that you send coins out a transaction where you say that the coin are locked in the blockchain and can only be unlocked by successfully executing the following script:
OP_DUP OP_HASH160 4e9856671c3abb2f03b7d80b9238e8f5ecd9f050 OP_EQUALVERIFY OP_CHECKSIG
Now, without getting too technical, this means something like this:
As you can see, the address actually represents a well-known piece of script. This start making sense if you look at the decoded address:
26 4E9856671C3ABB2F03B7D80B9238E8F5ECD9F050 F8F1F945
The first byte (0x26, or 38) is the version byte. This tells the clients how the interpret the rest of the script. In our case 38 means Pay-to-Public-Key-Hash (P2PKH), or in other words the script mentioned above. The part after that is just the SHA1 hash of the public key and the final 4 bytes are a checksum to verify you did not make a typo when entering the address.
Enter SegWit. What SegWit exactly is depends on who you are talking to, however it mostly is a different transaction format/protocol. The main change of SegWit is that signature data is not longer included in the transaction (fixing transaction malleability). Instead transaction data is sent separate from the transaction itself and outside of the (main) blocks.
This is not really that much of an issue, except for the fact that people wanted to enable SegWit as a soft-fork instead of a hard-fork. This means that somehow unupgraded nodes needed a way to deal with these new transaction types without being able to verify them.
The solution turned out to be to make use of an implementation detail of Bitcoin Script: if a piece of script executes without any errors, the last bit of data determines whether the transaction is valid (non-zero) or invalid (zero). This is what they used to implement SegWit.
So what does this look like? Well, you might be surprised how simple a P2WPKH (the SegWit way of doing a P2PKH transaction) script looks:
00 4e9856671c3abb2f03b7d80b9238e8f5ecd9f050
Yes. That’s it.
The first byte is the Witness program version byte. I.e. it tells you how the other data should be interpreted (very similar to how addresses work). Then there is the hash of the public key. As you can see, SegWit does not actually use Bitcoin Script. Mostly because it needs old nodes to ‘just accept’ its transactions. However interestingly enough, while the transaction format changed, the transaction data is pretty much the same:
This means that these kind of SegWit transactions need a new way of addressing them. Now, you might think that this is where the ‘3’ addresses on Bitcoin or the ‘M’ addresses on Garlicoin come in. However, that is not the case.
These addresses are what are called Pay-to-Script-Hash (P2SH) addresses. There scrypt is like this:
OP_HASH160 35521b9e015240942ad6b0735c6e7365354b0794 OP_EQUAL
Huh? Yeah, these are a very special type of transactions, that kind of go back to the “hey, can you send some coins to the network in such a way that only the private key that corresponds to public key XYZ can unlock them?” issue.
These transactions are a way to have arbitrary smart contracts (within the limits of Bitcoin Script) to determine whether a transaction output can be spend or not without the sender of the coins having to deal with your scripts. Basically they use a hash of the “real” script, which whoever owns the coins has to provide when they want to spend them, as well as the specific inputs required for a script. This functionality is for example used in multi-signature (MultiSig) wallets, without requiring someone sending money to these wallets having to deal with random bits of information like how many signatures are required, how many private keys belong to the wallet, etc.
This same method is used for so called P2SH-wrapped SegWit transactions (or P2SH-P2WPKH). Consider our earlier SegWit transaction output script:
00 4e9856671c3abb2f03b7d80b9238e8f5ecd9f050
Or 00144e9856671c3abb2f03b7d80b9238e8f5ecd9f050 in low-level hex. The P2SH script for this would be:
OP_HASH160 a059c8385124aa273dd3feaf52f4d94d42f01796 OP_EQUAL
Which would give us address MNX1uHyAQMXsGiGt5wACiyMUgjHn1qk1Kw. This is what is now widely known and used as SegWit. But this is P2SH-wrapper SegWit, not native or "real" SegWit. Native would be using the data-only SegWit script directly.
The reason for using the P2SH variant is mostly about compatibility. While SegWit nodes understand these newer transactions, they were never officially assigned a way to convert them to addresses. Hence, they will show up in blockchain explorers as Unparsed address [0] or something similar. Then there is also the whole thing about old nodes and relaying non-standard transactions, but I will skip that bit for now.
Bitcoin is using/going to use new BECH32 addresses for native SegWit transactions, which looks completely different from the old Base-58 encoded addresses. However, right now, especially on Garlicoin, you cannot really use them and have to use the P2SH variant. But why not use these new cool transaction types without having to deal with all that useless and complex P2SH wrapping, right? Right? …
Well, I went ahead and gave them their (unofficial) address space.
So last thursday I made some changes to Garlicoin Core, to make dealing with these native SegWit transaction a lot easier. In short, the changes consist of:
  • Assigning address version byte 73 to them, in other words addresses starting with a ‘W’ (for ‘witness’).
  • Allowing the use of ‘W’ addresses when sending coins.
  • Make the wallet automatically recognize the SegWit transaction type for any newly generated address.
  • Add the getwitnessaddress command, which decodes a version 38 ‘G’ address and re-encodes the same data as a version 73 ‘W’ address (unfortunately it is not as simple as just changing the first letter). Note that this can be any address, not just your own. (That said, you should not send SegWit transactions to people not expecting them, always use the address given to you.)
  • Added the usewitnesschangeaddress configuration setting, to automatically use the cheaper SegWit transaction outputs for transaction change outputs.
  • (Since using the 'W' address only changes the way coins are sent to you and the private key used for both transaction types is the same:) When receiving coins they show all up under the original ‘G’ address, whether a SegWit or legacy/normal transaction type was used. The idea behind this is that both are actually the same "physical" (?) address, just to the way to coins to it differs. Address book entries are also merged and default to the ‘G’ address type.
Anyway, I don’t expect people to actually use this or it getting merged into mainline or anything. I actually mostly made this for myself, but thought I should share anyway. I guess it was also a nice opportunity to talk a bit about transactions and SegWit. :-)
Btw, I also changed my pool to allow mining to ‘W’ addresses, to make coin consolidation cheaper (due to the SegWit fee subsidy). Right now this is only for instant payout though (as I would have to update the wallet node the pool is using for daily payout, which I haven’t done yet).
Also note that you can actually mine to a ‘W’ address (and therefore use cheaper transactions) even if you are running the official, non-patched version of Garlicoin Core, however:
  • You need to manually convert your ‘G’ address to a ‘W’ address.
  • You need to run the addwitnessaddress command (Help -> Debug Window -> Console) to make the wallet recognize SegWit transactions (you can ignore the ‘M’ address it produces).
  • The wallet might get a bit confused as it does not really understand how it got the coins. This is mostly notable in the ‘Coin Control’ window if you have it enabled. Apart from that everything should still work though.
submitted by nuc1e4r5n4k3 to garlicoin [link] [comments]

How Craig constructed the "message" that he "signed" using Satoshi's key

Craig was a bit clever here. He did not cheat, and did not use modified command line tools. He indeed posted a message signed by Satoshi's key, that validates correctly. This might explain how he fooled a few people. However, that message just so happens to be a hash of an early Bitcoin transaction, not anything proving his identity. Here's how he did it.
First, check out Dan Kaminsky's blogpost for less-stupid instructions and an archive of the files you need (instead of having to transcribe hex from Craig's post). Although Dan concludes that the signature does not validate, that's actually only due to the & vs. && bug in the last bash command. If you run the corrected command, it works:
$ base64 --decode signiture.der > sig.asn1 && openssl dgst -verify sn-pub.pem -signature sig.asn1 sn7-message.txt Verified OK 
What's the signed message? This:
$ xxd sn7-message.txt 00000000: 479f 9dff 0155 c045 da78 4021 7785 5fdb [email protected]!w._. 00000010: 4f0f 396d c0d2 c24f 7376 dd56 e2e6 8b05 O.9m...Osv.V.... 
That's just binary junk. It was really signed by Satoshi though.
We now know that the signature turned out to correspond to a real Bitcoin transaction (credit to JoukeH). Compare its input script with:
$ xxd sig.asn1 00000000: 3045 0221 00c1 2a7d 5497 2f26 d14c b311 0E.!..*}T./&.L.. 00000010: 339b 5122 f8c1 8741 7dde 1e8e fb68 41f5 3.Q"...A}....hA. 00000020: 5c34 220a e002 2066 632c 5cd4 161e fa3a \4"... fc,\....: 00000030: 2837 764e ee9e b849 75dd 54c2 de28 65e9 (7vN...Iu.T..(e. 00000040: 7525 85c5 3e7c ce u%..>|. 
So where did sn7-message.txt come from? To put it together, we need to follow the OP_CHECKSIG documentation. Specifically, the message to be signed is the transaction, but with the input script replaced with the output script of the transaction that sent the coins in the first place, plus the hash type value of '1'.
First we download the two transactions:
$ curl -so send.bin $ curl -so spend.bin 
Then we dike out the script bit from send.bin and insert it into spend.bin, replacing the input script, and append '1' as a 32-bit little endian integer:
$ head -c 41 spend.bin >sig_txn.bin $ dd if=send.bin bs=1 skip=204 count=68 status=none >>sig_txn.bin $ tail -c 161 spend.bin >>sig_txn.bin $ echo -ne '\x01\x00\x00\x00' >>sig_txn.bin 
Take the SHA-256 hash and there you go:
$ sha256sum sig_txn.bin 479f9dff0155c045da78402177855fdb4f0f396dc0d2c24f7376dd56e2e68b05 sig_txn.bin 
You can also validate this against the Signature Hash field in webbtc's script debug view. Bitcoin actually does a double SHA-256 here, once as part of the protocol, and once as part of the elliptic curve code. So apply sha256sum again:
$ sha256sum sn7-message.txt 3ec9cbc0d1aa849c16a1b276b246e057e7232b21926e428cc09b692c14336f44 sn7-message.txt 
... and you get the Signature Hash.
Interestingly, the source address of this transaction (the bit cut out from send.bin) is the same as in the example on the OP_CHECKSIG documentation wiki page - so he was too lazy even to pick another address, although he picked a different spend transaction.
This is what us security guys call a replay attack. Well played, Craig.
Edits: links and spelling.
Edit2: to make it clear, as bedstefar points out, this doesn't prove that Craig is not Satoshi. It only proves that his blog post doesn't prove that he is Satoshi, and anyone could've written a similar blog post.
Edit3: the blog post does claim that the (incompletely displayed, unverifiable) Sartre text hashes to the same hash as my sig_txn.bin. That much is obviously a lie and patent nonsense, unless you believe he's the first person in the world to come up with a SHA-256 preimage attack. He didn't have to doctor any screenshots or tools for that, the lie is that where he says "The contents of this file have been displayed in the figure below." he's displaying the contents of a different file.
Edit4: Wow, thanks for the gold!
submitted by marcan42 to Bitcoin [link] [comments]

BIP 199 HTLC initial stack state

Hey fellow bitcoiners and redditors

I'm trying to understand how HTLCs (Hashed Time-Locked Contracts) can be implemented in Bitcoin and BIP-199 turned out to be the best resource for that purpose.

Question answered!
  1. Does the stack need to feature the secret/image twice in the OP_IF case? => call the script with [pubKey, signature, 1]
  2. How can the OP_ELSE flow ever be executed successfully (since this requires the stack to be empty, but [pubKey, signature] are required for OP_CHECKSIG at the very end of the script )? => call the script with [pubKey, signature, 0]

Full story
This is the example HTLC script I copied from BIP-199:

IF-Case (seller can claim the buyers deposited BTCs)
TL;DR: detailed debug log of this path. Question: Can I avoid providing the preimage twice?

Before running this script, the preimage should be known and the stack should looks:

  • So since the stack is not empty, it will jump into the OP_IF clause.
    • the OP_IF will pop the top value => stack is now: [preimage, pubKey, signature]
  • [HASHOP] will hash the preimage
    • the preimage on the stack will, be replaced by the image => stack: [image, pubKey, signature]
  • digest (a synonym for image) will be pushed
    • => stack: [image, image pubKey, signature]
  • OP_EQUALVERIFY checks the two top items for equality: image == image => true
    • ...and removes them, if they are equal => stack: [pubKey, signature]
  • OP_DUP will duplicate the pubKey, => stack: [pubKey, pubKey, signature]
  • OP_HASH160 will double-hash the pubKey => stack: [p2pkhAddress, pubKey, signature]
  • represents the p2pkhAddress => stack: [p2pkhAddress, p2pkhAddress, pubKey, signature]
  • OP_EQUALVERIFY checks the two top items for equality: p2pkhAddress == p2pkhAddress => true
    • ...and removes them, if they are equal => stack: [pubKey, signature]
  • OP_CHECKSIG checks the signature
  • Done, all fine!
  • Question: This flow requires the secret to be on the stack twice before starting the script; Can I avoid that somehow?

ELSE-Case (buyer claims refund of his/her deposited BTCs)
Since the script runs an OP_CHECKSIG at the very end. This means the stack has to contain at least [pubKey, signature] before the execution pointer moves to OP_IF. However, OP_IF returns true "If the top stack value is not False". So how can the script possibly ever execute the OP_ELSE flow?

  • My mother tongue is not English, please forgive me any mistakes. :)
  • I'm just getting started with BTC scripting, please forgive me any noob mistakes.
  • I also searched the whole stackexchange/search engine/reddit/github universum for this issue, obivously without success.
PS - buy Bitcoin :)
submitted by redditeraya to Bitcoin [link] [comments]

Tìm hiểu về công nghệ blockchain

Tìm hiểu về công nghệ blockchain
Mình sẽ bắt đầu bài viết này với một cái tên rất quen thuộc đối với mọi người trong những năm gần đây, đó là bitcoin. Được tạo ra vào năm 2009 bởi một người (nhóm?) có bí danh Satoshi Nakamoto, bitcoin nhanh chóng trở thành một cái tên hết sức nổi tiếng trong giới công nghệ cũng như trong giới tài chính.
Vậy bitcoin và blockchain có mối liên hệ gì với nhau? Bitcoin và blockchain có phải là một? Không. Tuy nhiên, chúng có mối liên hệ rất chặt chẽ. Khi bitcoin được phát hành dưới dạng mã nguồn mở, blockchain đã được gói cùng với bitcoin trong mã nguồn. Và vì bitcoin là ứng dụng đầu tiên của blockchain nên mọi người thường vô tình sử dụng "bitcoin" để có nghĩa là blockchain. Sự hiểu lầm này vẫn tồn tại phổ biến cho đến bây giờ, khi mà công nghệ blockchain đã được ứng dụng trong rất nhiều các ngành công nghiệp và công nghệ khác.
Lời tác giả (1): Bài viết được thực hiện dựa trên kiến thức cá nhân cũng như thông tin được tổng hợp từ nhiều nguồn (tham khảo nguồn ở cuối bài). Bài viết ảnh hưởng đến mình nhiều nhất là từ nguồn hackernoon, sẽ có rất nhiều thông tin và hình ảnh được trích dẫn, lược dịch từ nguồn này. Một số từ tiếng Anh sẽ không được dịch để đảm bảo ý nghĩa (hoặc người viết không biết dịch thế nào ^^). Trong trường hợp nội dung có sai sót rất mong có được góp ý dưới comment. Lời tác giả (2): Blog này mình viết về công nghệ, đôi khi là góc nhìn cá nhân về một vấn đề nào đó. Bài viết này mình cũng sẽ viết tập trung về công nghệ. Nếu bạn đang tìm một bài nói về việc đầu tư bitcoin thế nào cho có lãi, thị trường bitcoin tương lai ra sao, tham gia thị trường này như thế nào ... thì có lẽ bài viết này không phải là thứ bạn đang mong muốn. Tuy nhiên, nếu bạn là một nhà đầu tư chưa có kiến thức gì về bitcoin, và bạn không muốn đầu tư vào một thứ mà bạn không hiểu gì, mình hi vọng những kiến thức mình chia sẻ sau đây sẽ giúp các bạn có tâm lý tốt hơn khi đầu tư vào thị trường này.

Màn dạo đầu về vấn đề tiền tệ và lòng tin

Bitcoin là chủ đề yêu thích của các phương tiện truyền thông trong thời gian gần đây, lượng người biết đến bitcoin cũng như đầu tư vào thị trường này càng ngày càng nhiều. Ngay cả những người chưa bao giờ hiểu về công nghệ, về kỹ thuật mật mã hay về blockchain ... cũng đang bàn tán về nó.
Bitcoin được tạo ra với ý tưởng về một loại tiền tệ vượt qua kiểm soát của chính phủ và đơn giản hóa các giao dịch trực tuyến bằng cách loại bỏ các bên trung gian để xử lý quá trình giao dịch.
Các giao dịch bitcoin được lưu trữ và thực hiện sử dụng một cuốn sổ cái được phân tán trên mạng ngang hàng. Blockchain là công nghệ nền tảng duy trì sổ cái giao dịch của bitcoin.
Chúng ta sẽ bắt đầu với câu chuyện về blockchain bằng một ví dụ về tiền tệ và giao dịch, dĩ nhiên công nghệ blockchain giải quyết được nhiều vấn đề khác, nhưng rõ ràng ví dụ về tiền thì thường dễ hiểu và nhiều cảm hứng hơn.
Giả sử bạn nợ thằng Joe một khoản và nó thì đang hết tiền, dĩ nhiên là nó sẽ đòi tiền bạn, bạn quyết định sẽ thôi lầy lội và chuyển khoản cho nó. Bạn mở iBanking lên, thực hiện lệnh chuyển tiền, ngân hàng kiểm tra số dư tài khoản, thực hiện việc chuyển tiền. Xong.
Về cơ bản, sẽ có đâu đó một bản ghi như thế này:
Trong trường hợp này, cả bạn và Joe đều tin tưởng vào ngân hàng để quản lý tài khoản của mình. Chẳng ngân hàng nào thực sự cầm tiền của bạn và gửi shipper đem cho Joe cả (ít nhất là ở thời đại này). Tất cả những gì cần thiết là một mục nhập trong sổ đăng ký hoặc cơ sở dữ liệu của ngân hàng mà bạn và Joe đều không kiểm soát hoặc sở hữu.
Tiền là vật ngang giá chung có tính thanh khoản cao nhất dùng để trao đổi lấy hàng hóa và dịch vụ nhằm thỏa mãn bản thân và mang tính dễ thu nhận ... Thông qua việc chứng thực các giá trị này dưới dạng của một vật cụ thể (Ví dụ như tiền giấy hay tiền kim loại) hay dưới dạng văn bản (dữ liệu được ghi nhớ của một tài khoản) mà hình thành một phương tiện thanh toán được một cộng đồng công nhận trong một vùng phổ biến nhất định. - wiki
Như vậy đối với ngân hàng, trên khía cạnh quản lý, tiền của bạn thực sự cũng chỉ là những con số đại diện và chúng ta chấp nhận tin tưởng những con số đó cũng như tin tưởng vào ngân hàng. Nói một cách tổng quát hơn, để thiết lập giao dịch, chúng ta phụ thuộc vào cá nhân thứ ba. Và đó cũng là vấn đề của các hệ thống hiện tại.
Điều gì sẽ xảy ra trong trường hợp "người thứ 3" không đáng tin cậy và cuỗm số tiền thật của chúng ta đi? Nếu cuốn sổ cái chứa thông tin tài khoản của bạn bị mất, bị hư hỏng? Nếu thằng cha nào đó ở ngân hàng vô tình hay hữu ý ghi nhầm 1000$ của bạn thành 100$? Dĩ nhiên, đó là ví dụ, trên thực tế bạn có nhiều cách để chứng thực số tiền với ngân hàng, ở đây, chúng ta nhấn mạnh việc rủi ro khi thực hiện giao dịch thông qua sự tin tưởng ở "người thứ 3".
Như vậy, thứ chúng ta cần là một hệ thống mà chúng ta có thể chuyển tiền không cần ngân hàng. Chúng ta có thể xây dựng được một hệ thống như thế không? Dĩ nhiên là có rồi. Các bạn biết rõ là bài viết đang muốn nói đến blockchain. Tuy nhiên hãy để cho mọi thứ thi vị hơn chút bằng cách đi chầm chậm từ bản chất vấn đề. ^^
Thay vì trao đổi tiền thật, chúng ta cũng cần một hệ thống quản lý những con số, những bản ghi, giống như của ngân hàng.
Bằng công nghệ blockchain, chúng ta có thể tự quản lý cuốn sổ cái chứa tài khoản và giao dịch của mình và mọi người.

Thực hiện giao dịch như thế nào?

Điều mấu chốt ở đây là, muốn thực hiện giao dịch, chúng ta phải giao dịch với những người cùng không tin tưởng vào hệ thống ngân hàng và tạm cho rằng hội, nhóm này có khả năng tự quản lý cuốn sổ cái chung.
Cần bao nhiêu người cho một nhóm như trên? Tối thiểu là 3, dĩ nhiên. Nếu 2 người tin tưởng nhau rồi thì chẳng có chuyện gì để bàn cả.
Giả sử chúng ta có 10 người nhé. Trên cơ sở 1 thỏa thuận chung giữa 10 người, họ có chi tiết về tài khoản của nhau nhưng lại không biết danh tính của người giữ tài khoản đó. Nghe hơi khó hiểu chút nhưng bạn có thể tưởng tượng đơn giản là bạn đang cầm sổ tài khoản của ai đó có mã số NOTE7749 mà không biết đích xác cuốn sổ này là của ai trong 9 người còn lại.

1. Hộp đựng tài liệu rỗng

Mỗi người đều sẽ có một hộp đừng tài liệu rỗng để bắt đầu. Hộp này để khi các giao dịch được thực hiện, mười cá nhân này có thể lưu trữ các trang giấy đã ghi lại giao dịch vào các hộp đựng. Tập hợp các trang này sẽ tạo thành một cuốn sổ cái riêng để theo dõi các giao dịch.

2. Khi thực hiện giao dịch

Tiếp theo, tất cả mọi người ngồi với một trang giấy trắng và một cây bút, sẵn sàng để viết bất kỳ giao dịch xảy ra.
Bây giờ, nếu người số 2 muốn gửi $10 đến số 9. Để thực hiện giao dịch, người số 2 nói với tất cả mọi người: "Tôi muốn chuyển $10 đến số 9. Tất cả mọi người, xin vui lòng ghi vào giấy."
Vậy là tất cả mọi người kiểm tra tài khoản của người có số thứ tự 2, nếu tài khoản đó có đủ tiền, mọi người đồng loạt ghi vào tờ giấy của họ như sau:
Giao dịch hoàn thành.

3. Giao dịch tiếp theo

Khi thời gian trôi qua, số giao dịch được tăng lên. Bất cứ khi nào họ muốn thực hiện một giao dịch, họ thông báo nó cho tất cả mọi người khác và mỗi người sau đó lại cập nhật lại bản ghi của mình.
Giao dịch được thực hiện cho đến khi 'hết giấy'. Giả sử một trang chỉ có chỗ ghi mười giao dịch thì ngay khi giao dịch thứ mười được thực hiện, mọi người đều đang ở dòng cuối cùng.
Để tiếp tục thực hiện giao dịch, tất cả mọi người phải cất hết những tờ giấy cũ vào hộp và chuẩn bị giấy mới.

4. Niêm phong bản ghi cũ

Trước khi đưa những tờ giấy - bản ghi cũ vào hộp, chúng ta cần phải khóa nó với một chìa khóa duy nhất mà tất cả mọi người trong mạng đều đồng ý rằng chìa khóa đó là an toàn. Bằng cách niêm phong nó, chúng ta sẽ đảm bảo rằng không ai có thể thay đổi nội dung của các bản ghi. Một khi trong hộp, nó sẽ luôn luôn ở trong hộp và được niêm phong. Nếu mọi người tin tưởng vào chìa khóa đồng nghĩa với việc mọi người tin tưởng vào nội dung của của các bản ghi được cất trong hộp. Chìa khóa - con dấu ở đây chính là mấu chốt của vấn đề.
Việc niêm phong bản ghi ở trên còn được gọi là 'đào', tuy nhiên ở bài viết này, chúng ta sẽ vẫn gọi là hành động 'niêm phong' hay 'khóa'.
Như vậy, thay vì tin tưởng vào người trung gian để thực hiện giao dịch, bây giờ chúng ta sẽ tin tưởng vào chìa khóa - hay con dấu khi thực hiện giao dịch.

Vấn đề niêm phong các bản ghi

Trước khi chúng ta tìm hiểu làm thế nào chúng ta có thể niêm phong các bản ghi, chúng ta sẽ tìm hiểu cách thức hoạt động của con dấu nói chung.

Chiếc hộp kỳ diệu

Hãy tưởng tượng một chiếc hộp vô cùng bí ẩn. Nếu bạn gửi vào bên trái hộp một vật, nó sẽ đẩy ra bên phải một vật khác.
Bạn có thể biết về 'Hash Function' hay 'hàm băm' hay 'hàm mã hóa' hoặc đại loại thế, tuy nhiên chúng ta sẽ vẫn dùng 'chiếc hộp kỳ diệu' cho dễ hiểu.
Giả sử, chúng ta gửi vào hộp 1 cái xúc xích, con lợn sẽ chạy ra ở bên phải hộp. Làm thế nào để cái xúc xích thành con lợn, chẳng ai biết cả.
Lời người viết (3): Ở bài gốc trên hackernoon dùng các chữ số đầu vào và chữ cái đầu ra, mình không thích thế lắm nên dùng các đồ vật và con vật cho dễ hiểu, sau khi đã có cái nhìn cơ bản, mình sẽ chuyển về với chữ và số giống như trên hackernoon.
Thêm nữa, việc đoán cái gì được đưa vào trong hộp phải là không thể, chúng ta khi thấy con voi chạy ra thì không thể đoán cái gì đã được nhét vào hộp, nhưng cứ khi nào nhét cái xúc xích vào, sẽ vẫn là con lợn chạy ra.
Thử nhét vào cái bút.
Chúng ta có con gà chạy ra.
Bây giờ, chúng ta có một câu hỏi như sau:
Liệu có thể đoán được phải nhét cái gì vào bên trái để có 1 con vật 4 chân chạy ra từ bên phải hộp.
Vấn đề là, chúng ta không thể đoán được khi nhét cái gì vào thì con gì sẽ chạy ra. Cách duy nhất để tìm trả lời được đó là thử tất cả mọi thứ trên đời cho đến khi có một con vật 4 chân chạy ra: chả giò, nem chua, đồng hồ, bút, thước, ba con sói ...
Cứ giả sử, nếu may mắn, sau khi nhét hàng núi đồ vào, con chuột chạy ra và 1 đáp án của chúng ta là cái usb.
Rất khó để tính toán đầu vào cho đầu ra, chúng ta tạm coi việc đó là không thể. Tuy nhiên, rất dễ dàng để xác minh nếu đầu vào cho đầu ra đúng yêu cầu. Bạn nghĩ câu trả lời là gì nếu ta ném cái usb vào? Một con vật 4 chân có chạy ra không? Xác minh rất dễ, chỉ cần ném thử cái usb vào và đếm số chân của con chuột chạy ra.
Thuộc tính quan trọng của chiếc hộp kỳ diệu:
"Cho một đầu ra, rất khó để đoán đầu vào, nhưng rất dễ để xác minh đầu vào có cho ra chính xác thứ ta mong đợi ở đầu ra không"

Sử dụng chiếc hộp kỳ diệu

Bây giờ quay lại vấn đề các bản ghi, các bản ghi thì là chữ và số vì vậy ta tạm rời xa các con vật vậy, hộp kỳ diệu bây giờ sẽ làm việc với những con số.
Hãy tưởng tượng chúng ta có hai hộp chứa bản ghi. Hộp đầu tiên chứa số 20893. Yêu cầu bây giờ là: "Tìm một con số khi kết hợp số trong hộp đầu tiên và cho vào chiếc hộp kỳ diệu sẽ cho chúng ta một dãy bắt đầu bằng ba chữ số 0?"
Bạn còn nhớ cách chúng ta tìm ra chiếc usb? Phải vậy, chúng ta sẽ thử lần lượt từng số cho đến khi tìm được đầu ra đúng yêu cầu. Sau vài nghìn lần thử, có thể hàng vạn hoặc hơn, chúng ta gặp một số, giả sử 21191 đi, mà khi thêm vào 20893 (21191 + 20893 = 42084) và cho vào hộp kỹ diệu thì đầu ra sẽ cho chúng ta một dãy thỏa mãn.
Trong trường hợp này, con số 21191 trở thành con dấu cho số 20893. Giả sử có một trang có số 20893 viết trên đó. Để đóng dấu trang đó (nghĩa là không ai có thể thay đổi nội dung của nó), chúng ta sẽ đặt một khóa có số niêm phong '21191' và khóa nó lại. Việc niêm phong được hoàn thành.
Số niêm phong được gọi là 'Proof Of Work', con số này là bằng chứng cho thấy các nỗ lực đã được tính toán.
Nếu ai đó muốn xác minh xem bản ghi đã bị thay đổi hay không, tất cả những gì người đó phải làm là thêm nội dung của bản ghi với số niêm phong và nhét vào hộp kỳ diệu. Nếu chiếc hộp đưa ra một dãy với bắt đầu với ba chữ số 0 thì tức là nội dung không bị ảnh hưởng. Nếu dãy xuất hiện không đáp ứng được yêu cầu, chúng ta có thể hủy bỏ bản ghi vì nội dung của nó đã bị xâm nhập và không còn hiệu lực.
Chúng ta sẽ sử dụng cơ chế niêm phong tương tự để đóng dấu tất cả các bản ghi và sắp xếp chúng trong các hộp chứa tương ứng.
Ghi chú: Thực ra việc sử dụng "một dãy với bắt đầu với ba chữ số 0" hoàn toàn là để đơn giản hóa vấn đề, trên thực tế mọi thứ phực tạp hơn nhiều lần.
Bây giờ, giả sử ai đó muốn thay đổi nội dung của trang, số niêm phong sẽ cho phép chúng ta biết liệu trang đó có bị thay đổi hay chưa.
Chúng ta sẽ quay lại thời điểm mọi người bắt đầu cất bản ghi vào hộp lưu trữ, khi mà tờ giấy đã ghi đủ 10 giao dịch.
Khi mọi người đều hết giấy, họ sẽ bắt đầu việc đóng dấu bằng cách tính toán con số niêm phong, người đầu tiên tìm được con số này sẽ thông báo cho tất cả mọi người.
Ngay lập tức khi nghe thấy ai đó đọc số niêm phong, mọi người sẽ dừng việc tính toán lại và kiểm tra số niêm phong nghe được, nếu số này hợp lệ, tất cả mọi người sẽ niêm phong tài liệu lại bằng số này.
Vậy điều gì sảy ra nếu ai đó nói ra con số đầu tiên nhưng con số này không hợp lệ? Trường hợp như vậy xảy ra rất thường xuyên với những lý do có thể là:
  • Người đó nghe sai một giao dịch
  • Người đó ghi sai một giao dịch
  • Người đó cố ý làm sai lệch giao dịch
Dù lý do gì đi nữa, để tiếp tục thì người đó chỉ có một cách duy nhất đó là copy lại giấy của người khác. Nếu anh ta không đưa trang của anh vào hộp đựng tài liệu, anh ta không thể tiếp tục viết thêm các giao dịch nữa.
Bất kể con số niêm phong là gì, khi được đa số đồng ý, sẽ trở thành con số niêm phong hợp lệ.
Vậy tại sao tất cả mọi người lại bỏ công sức để tính toán khi họ biết ai đó sẽ tính toán và thông báo cho họ? Tại sao không ngồi im và đợi kết quả của người khác?
Câu trả lời đó là tiền thưởng. Tất cả mọi người là thành viên của nhóm đều đủ điều kiện nhận phần thưởng. Người đầu tiên tính số niêm phong được khen thưởng bằng tiền cho những nỗ lực của anh ta.
Đó là cách bitcoin ra đời và hoạt động như là đơn vị tiền tệ đầu tiên được giao dịch trên blockchain.
Để giữ cho mọi người làm việc, mọi người sẽ được trao thưởng bitcoin.
Coi một trang giấy để ghi giao dịch làm một khối (Block), hộp đựng tài liệu như một danh sách các bản ghi (Chain), chúng ta sẽ có một "BlockChain"
Chưa hết, chúng ta có một vấn đề cần phải giải quyết.
Bây giờ giả sử một ai đó muốn gian lận và quay lại thay đổi thông tin một giao dịch nào đó đã được cất trong hộp, dĩ nhiên con số niêm phong sẽ tố cáo việc bản ghi đã bị thay đổi, nhưng nếu anh ta tính toán lại cả con số niêm phong?
Để tránh việc con số niêm phong bị tính toán lại, thay vì chỉ đưa vào hộp kỳ diệu 2 thông số là mã giao dịch và con số niêm phong hợp lệ, bây giờ ta sẽ yêu cầu phải thêm một thông số nữa vào hộp kỳ diệu, đó là dãy đầu ra được tính toán của giao dịch trước đó.
Với thủ thuật này, chúng ta đảm bảo rằng mọi trang đều bị phụ thuộc vào trang trước của nó. Do đó, nếu ai đó muốn sửa đổi một trang thì cũng phải thay đổi nội dung và con số niêm phong của tất cả các trang sau đó để giữ cho toàn bộ chuỗi là hợp lệ.
Nếu một trong mười người cố lừa dối và sửa đổi nội dung của blockchain (thư mục chứa các trang có danh sách giao dịch), anh ta sẽ phải điều chỉnh rất nhiều trang và tương ứng với việc phải tính toán số niêm phong mới số cho tất cả các trang sau đó, anh ta có thể tạo ra một chuỗi giao dịch khác với mọi người. Tuy nhiên độ khó của việc tìm kiếm số niêm phong khiến cho chuỗi của anh ta sẽ không bao giờ đuổi kịp chuỗi của 9 người còn lại.
Như vậy, chúng ta có thể kết luận:
Chuỗi dài nhất là chuỗi hợp lệ
Vậy, điều gì xảy ra nếu thay vì một người có ý định xấu, có tới 6 người có ý định xấu?
Đây là một điểm yếu và là một lỗ hổng về mặt cấu trúc của bitcoin và blockchain. Khi mà phần lớn các cá nhân trong mạng quyết định không trung thực và ăn gian phần giao dịch còn lại của mạng, toàn bộ giao thức sẽ đổ vỡ.
Về cơ bản, mô hình bitcoin được xây dựng trên giả định rằng đa số đám đông luôn luôn là trung thực. Trong trường hợp một cuộc tấn công như thế diễn ra thành công, chắc chắn sự tin tưởng vào đồng tiền sẽ bị mất và giá trị của một đồng tiền sẽ giảm nhanh chóng.

51% attack - tấn công 51%

Làm thế nào để những người có ý định xấu có toàn quyền kiểm soát mạng?
Không hẳn toàn bộ. 51% mạng là đủ.
Như một hệ quả của mô hình tin tưởng đám đông đã trình bày ở các phần trước đó. Khi một nhóm người nắm được 51% mạng lưới, họ có thể ngăn các giao dịch mà họ chọn không xác nhận, làm cho chúng không hợp lệ, ngăn cản mọi người gửi bitcoin giữa các địa chỉ. Họ cũng có thể đảo ngược các giao dịch mà họ gửi trong thời gian họ kiểm soát được và họ có thể ngăn không cho các thợ mỏ khác tìm thấy bất kỳ khối bitcoin nào trong một khoảng thời gian.
Tuy nhiên họ vẫn không thể đảo ngược được những giao dịch từ đầu hay tạo ra những đồng tiền mới hoặc ăn cắp tiền từ ví của người khác. Dẫu vậy, việc này có thể gây ra một sự hoảng loạn trên thị trường và sẽ trực tiếp đe doạ việc sử dụng bitcoin như là một loại tiền tệ trực tuyến.
Một cuộc tấn công 51% là hoàn toàn khả thi, đặc biệt là với sự gia tăng của các mỏ khai thác bitcoin lớn. Ở mức độ khai thác và độ khó hiện tại, một chính phủ có thể dễ dàng tiến hành một cuộc tấn công 51%.
Trên thực tế thì những trường hợp tương tự đã từng xảy ra. đã nắm hơn 50% sức mạnh tính toán của mạng bitcoin vào tháng 7 năm 2014, sau đó họ có cam kết trong một tuyên bố rằng họ sẽ giảm năng suất xuống và sẽ không đạt 40% năng suất của toàn bộ hệ thống trong tương lai.
Krypton và Shift Krypton và Shift, hai blockchain dựa trên nền tảng ethereum, bị tấn công 51% vào tháng 8 năm 2016.

Genesis block

Tất cả các khối trong mạng lưới đều liên kết tới một khối được giao dịch trước đó. Vậy, khối đầu tiên thì liên kết với cái gì và nó được tạo ra như thế nào?
Thực tế thì các khối đầu tiên này thường được tạo bằng tay (hard-code). Trong trường hợp của bitcoin, khối này được gọi là Genesis Block. Genesis Block hầu như luôn luôn được mã hóa cứng trong các phần mềm. Đây là một khối đặc biệt vì nó không liên kết đến một khối trước nó.
Khối Genesis chứa một thông điệp ẩn trong giao dịch coinbase - nó nói rằng ""The Times 03/Jan/2009 Chancellor on brink of second bailout for banks." Đây rõ ràng là một thông điệp từ Satoshi Nakomoto với dụng ý chỉ ra những vấn đề với chính sách cứu trợ của chính phủ hiện nay đối với ngân hàng quá lớn cũng như vấn đề nguy hiểm về đạo đức.
Về cơ bản nó sẽ giống như sau:
00000000 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00000020 00 00 00 00 3B A3 ED FD 7A 7B 12 B2 7A C7 2C 3E ....;£íýz{.²zÇ,> 00000030 67 76 8F 61 7F C8 1B C3 88 8A 51 32 3A 9F B8 AA gv.a.È.ÈŠQ2:Ÿ¸ª 00000040 4B 1E 5E 4A 29 AB 5F 49 FF FF 00 1D 1D AC 2B 7C K.^J)«_Iÿÿ...¬+| 00000050 01 01 00 00 00 01 00 00 00 00 00 00 00 00 00 00 ................ 00000060 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00000070 00 00 00 00 00 00 FF FF FF FF 4D 04 FF FF 00 1D ......ÿÿÿÿM.ÿÿ.. 00000080 01 04 45 54 68 65 20 54 69 6D 65 73 20 30 33 2F ..EThe Times 03/ 00000090 4A 61 6E 2F 32 30 30 39 20 43 68 61 6E 63 65 6C Jan/2009 Chancel 000000A0 6C 6F 72 20 6F 6E 20 62 72 69 6E 6B 20 6F 66 20 lor on brink of 000000B0 73 65 63 6F 6E 64 20 62 61 69 6C 6F 75 74 20 66 second bailout f 000000C0 6F 72 20 62 61 6E 6B 73 FF FF FF FF 01 00 F2 05 or banksÿÿÿÿ..ò. 000000D0 2A 01 00 00 00 43 41 04 67 8A FD B0 FE 55 48 27 *....CA.gŠý°þUH' 000000E0 19 67 F1 A6 71 30 B7 10 5C D6 A8 28 E0 39 09 A6 .gñ¦q0·.\Ö¨(à9.¦ 000000F0 79 62 E0 EA 1F 61 DE B6 49 F6 BC 3F 4C EF 38 C4 ybàê.aÞ¶Iö¼?Lï8Ä 00000100 F3 55 04 E5 1E C1 12 DE 5C 38 4D F7 BA 0B 8D 57 óU.å.Á.Þ\8M÷º..W 00000110 8A 4C 70 2B 6B F1 1D 5F AC 00 00 00 00 ŠLp+kñ._¬.... 
Còn trong phiên bản ban đầu của bitcoin, nó được miêu tả như sau:
GetHash() = 0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f hashMerkleRoot = 0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b[0].scriptSig = 486604799 4 0x736B6E616220726F662074756F6C69616220646E6F63657320666F206B6E697262206E6F20726F6C6C65636E61684320393030322F6E614A2F33302073656D695420656854 txNew.vout[0].nValue = 5000000000 txNew.vout[0].scriptPubKey = 0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704 OP_CHECKSIG block.nVersion = 1 block.nTime = 1231006505 block.nBits = 0x1d00ffff block.nNonce = 2083236893 CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1) CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0) CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73) CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B) vMerkleTree: 4a5e1e 

Tài Liệu Tham khảo:

Header cover: Forexnewsnow
tags: blockchain, bitcoin
submitted by shibob89 to u/shibob89 [link] [comments]

Please Protect Consumers by Using Stealth Addressing

It's recently been brought to attention that various companies have been heavy handed in their restrictions of how one may spend their purchased coins. I'm writing this up so that people can have a basic understanding of stealth addressing and how it works. If you'd like more details on the cryptography behind stealth addresses, please refer yourself to 13.4.3 of Wiley's Understanding Bitcoin: Cryptography, Engineering and Economics.
A stealth address looks like this: vJmwY32eS5VDC2C4GaZyXt7i4iCjzSMZ1XSd6KbkA7QbGE492akT2eZZMjCwWDqKRSYhnSA8Bgp78KeAYFVCi8ke5mELdoYMBNep7L
When you send funds to a stealth address, you create a data containing (OP_RETURN) output and a normal output to a one-time use Bitcoin address. The latter output contains the money you actually wish to send, while the former output contains some data which looks, to observers of the blockchain, like a bunch of indecipherable garbage.
Here's an example:
Tx hash 6ea5c6f1a97f382f87523d13ef9f2ef17b828607107efdbba42a80b8a6555356
So, when you send money from Bob to Alice using a stealth address, what's basically going on from a privacy perspective?
To everyone else observing, it's impossible to tell that Alice was sent money. The only thing that they can tell is that Bob sent money to a stealth output, and that's if Bob himself didn't receive his funds as the result of stealth output and his address is somehow already known.
Using stealth addresses, it will be impossible for someone to tell where your money is being sent. The only thing obviously visible is the amount sent. In the future, a Bitcoin sidechain, such as that proposed by andytoshi and gmaxwell, may have mandatory stealth addressing as found in altcoins such as Monero; however, the technology is currently available for use in Bitcoin using simple OP_RETURN scripts.
There is a downside to this technology: to receive coins, you need to scan every incoming Bitcoin transaction to see if it might have an output belonging to you. However, I'm sure if you care about the privacy of your customers and their ability to be able to send funds to you in the future, the benefits more than outweigh the costs!
Current software/clients supporting stealth transactions include:
Hopefully, more soon!
Additional, for free references if you don't want have access to the Wiley book:
submitted by therealtacotime to Bitcoin [link] [comments]

Qtum - Quantum Chain Design Document

Serialization: Qtum Foundation Design Document

In this series of articles, the Qtum Quantum Chain Foundation will make public its early design documents for the first time, hoping to help the community understand the design intent of Qtum and the implementation details of key technologies. The article will be based on the original design draft in order to restore the designer's original ideas. Follow-up Qtum project team will be further collation and interpretation, to help readers understand more technical details, so stay tuned.
The topics that may be included in this series include
* Qtum account abstraction layer AAL
* Qtum distributed autonomous protocol DGP
* Qtum wallet (qt, mobile wallet, etc.) and browser
* Add RPC call
* Mutual interest consensus mechanism MPoS
* Add opcode
* Integration of EVM and Qtum blockchain
* Qtum x86 virtual machine
* Others...
The Qtum quantum chain public number will be updated from time to time around the above topics to restore the history of the Qtum project and key technologies from scratch.
Qtum original design document summary -- Qtum new OPCODE
As we all know, Qtum uses the same UTXO model as Bitcoin. The original UTXO script was not compatible with the EVM account model, so Qtum added three OP_CREATE, OP_CALL, and OP_SPEND opcodes to the UTXO transaction script for the purpose of providing operational support for conversions between UTXO and EVM account models. The original names of the three opcodes are OP_EXEC(OP_CREATE), OP_EXEC_ASSIGN(OP_CALL) and OP_TXHASH(OP_SPEND), respectively.
The following is an excerpt of representative original documents for interested readers.
OP_CREATE (or OP_EXEC) is used to create a smart contract. The original design files (with Chinese translation) related to this opcode by the Qtum development team are as follows (ps: QTUM <#> or QTUMCORE<#> in the document numbering internal design documents. ):
QTUMCORE-3:Add EVM and OP_CREATE for contract execution Description:After this story, the EVM should be integrated and a very basic contract should be capable of being executed. There will be a new opcode, OP_CREATE (formerly OP_EXEC), which takes 4 arguments, in push order: 1. VM version (currently 1 is EVM) 2. Gas price (not yet used, anything is valid) 3. Gas limit (not yet used, assume very high limit) 4. bytecodeFor now it is OK that this script format be forced and mandatory for OP_CREATE transactions on the blockchain. (ie, only "standard" allowed on the blockchain) When OP_CREATE is encountered, it should execute the EVM and persist the contract to a database (triedb) Note: Make sure to follow policy for external code (commit vanilla unmodified code first, and then change it as needed) Make the EVM test suite functional as well (someone else can setup continuous integration changes for it though) 
The above document describes the functions required by OP_CREATE and the parameters used.


OP_CALL is used for contract execution and is one of the most commonly used opcodes. There are many descriptions in the original design document.
QTUM6: Implement calling environment info in EVM for OP_EXEC_ASSIGN 
Description: Solidity expects certain information to be pushed onto the stack as part of it's ABI. So, when data is sent into the contract using OP_EXEC_ASSIGN we need to make sure to provide this data. This data includes the Solidity "function selector" as well as ensuring the opcodes CALLER and ORIGIN function properly. This looks to be fairly easy, it should just be transferring some data from the Bitcoin stack to the EVM stack, and setting some fields for the origin info. However, this story should be split into multiple tasks and re-evaluated if it isn't easy. See also: For populating the CALLER and ORIGIN value, the following should be done: OP_EXEC_ASSIGN should take 2 extra arguments, SENDER and SENDER_SIGNATURE. Sender should be a public key. Sender Signature is the signature of all the vins for the current transaction, signed of course using the SENDER value.On the EVM side, CALLER's value will be a public key hash, ie, a hash of the SENDER public key. This public key hash should be compatible with Bitcoin's public key hash for it's standard version 1 addresses. IF the given SENDER_SIGNATURE does not match successfully, then the transaction should be considered invalid. If the SENDER public key is 0, then SENDER_SIGNATURE must also be 0, and the given CALLER opcode etc should just return 0.
The above document describes the OP_EXEC_ASSIGN calling environment information that needs to be implemented in the EVM.
QTUM8: Implement OP_EXEC_ASSIGN for sending money to contracts 
Description: A new opcode should be added, OP_EXEC_ASSIGN. This opcode should take these arguments in push order: # version number (VM version to use, currently just 1)

gas price (can be ignored for now)

gas refund script (can be ignored for now)

data (The data to hand to the smart contract. This will include things like the Solidity ABI Function Selector and other data that will later be available using the CALLERDATA EVM opcode) # smart contract address (txid + vout number)

It should return two values right now, 0 and 0. These are for spendable and out of gas, respectively. Making them spendable and dealing with out of gas will be in a future storyFor this story, the EVM contract does not actually need to be executed. This opcode should only be a placeholder so that the accounting system can determine how much money a contract has control of
The above document describes the OP_EXEC_ASSIGN implementation details.
QTUM15: Execute the relevant contract during OP_EXEC_ASSIGN 
Description: After this story is complete, when OP_EXEC_ASSIGN is reached, it should actually execute the contract whose address was given to it, passing the relevant data from the bitcoin script stack with it. Other data such as the caller and sender can be left for a later story. Making the CALLER, ORIGIN etc opcodes work properly will be fixed with a later story
The above document describes OP_EXEC_ASSIGN how the script runs the relevant contract code.
QTUM40: Allow contracts to send money to pubkeyhash addresses Description: We need to allow contracts to send money back to pubkeyhash addresses, so that people can withdraw their coins from contracts when allowed, etc. This should work similar to how version 0 contract sends work. Instead of using an OP_EXEC_ASSIGN vout though, we need to instead use a standard pubkeyhash script. So, upon spending to a pubkeyhash, the following transaction should be placed on the blockchain: vin: [standard contract OP_EXEC_ASSIGN inputs] ... vout: OP_DUP OP_HASH160 [pubKeyHash] OP_EQUALVERIFY OP_CHECKSIG change output - version 0 OP_EXEC_ASSIGN back to spending contract These outputs should be directly spendable in the wallet with no changes to the wallet code itself 
The above document describes how to allow contracts to send QTUM to pubkeyhash addresses.
QTUMCORE-10:Add ability for contracts to call other deployed contracts Description:Contracts should be capable of calling other contracts using a new opcode, OP_CALL. Arguments in push order:version (32 bit integer) gas price (64 bit integer) gas limit (64 bit integer) contract address (160 bits) data (any length) OP_CALL should ways return false for now. OP_CALL only results in contract execution when used in a vout; Similar to OP_CREATE, it uses the special rule to process the script during vout processing (rather than when spent as is normal in Bitcoin). Contract execution should only be triggered when the transaction script is in this standard format and has no extra opcodes. If OP_CALL is created that uses an invalid contract address, then no contract execution should take place. The transaction should still be valid in the blockchain however. If money was sent with OP_CALL, then that money (minus the gas fees) should result in a refund transaction to send the funds back to vin[0]'s vout script. The "sender" exposed to EVM should be the pubkeyhash spent by vin[0]. If the vout spent by vin[0] is not a pubkeyhash, then the sender should be 0.Funds can be sent to the contract using an OP_CALL vout. These funds will be handled by the account abstraciton layer in a different story, to expose this to the EVM. Multiple OP_CALLS can be used in a single transaction. However, before contract execution, the gas price and gas limit of each OP_CALL vout should be checked to ensure that the transaction provides enough transaction fees to cover the gas. Additionally, this should be verified even when the contract is not executed, such as when it is accepted in the mempool. 
The above document describes how the contract calls other contracts via OP_CALL.


OP_SPEND is used for the cost of the contract balance. Because the contract address is a special address, in order to ensure consensus, the UTXO needs to be specially processed. Therefore, there are more descriptions of the OP_SPEND operation code in the original design document.
QTUM20: Create OP_EXEC_SPEND transaction when a contract spends money 
Description: When a CALL opcode or similar to used from an EVM contract to send another contract money, this should be shown on the blockchain as a new transaction. When a money transfer is done in the contract, the miner should add a new transaction exactly after the currently processing transaction in the block. This transaction should spend an input owned by the contract by using EXEC_SPEND in it's redeemScript. For the purposes of this story, assume change is not something to be worried about and consume as many inputs are needed. Properly picking effecient coins and sending back money to the originating contract will come in a later story. Edge cases to watch for: The transaction for sending money to the contract must come directly after the executing transaction. The outputs should use a version-0 OP_EXEC_ASSIGN vout, so that if the transaction were received out of context, it would still mean to not execute the contract.
The above document describes the timing of creating a OP_SPEND transaction.
QTUM21: Create consensus-critical change and coin-picking algorithm for OP_EXEC_SPEND transactions Description: Building on #20, now a consensus-critical algorithm must be made that picks the most optimal outputs belonging to the contract, and spends them, and also makes a change output that returns the "change" from the transaction back to the contract. All outputs in this case should be using a version-0 OP_EXEC_ASSIGN, to avoid running into the limitation that prevents more than one (version 1) OP_EXEC_ASSIGN transaction from being in a single transaction. The transaction should have as many vins as needed, and exactly 2 vouts. The first vout to go to the target contract, and the second vout to send change back to the source contract. 
QTUM22: Disallow more than one EVM execution per transaction
Description: In order to avoid significant edge cases, for now, disallow more than one EVM execution to take place in a single transaction. This includes both deployment and fund assignment vouts. Instead, such things should be split into multiple transactions If two EVM executions are encountered, the transaction should be treated as completely invalid and not suitable for broadcast nor putting into a block
QTUM23: Add "version 0" OP_EXEC_ASSIGN, which does not execute EVM Description: To counteract problems from #22, we should allow OP_EXEC_ASSIGN to be used to fund a contract without the contract actually being executed. This will be used later for "change" outputs to (multiple) contracts. If the version number passed in for OP_EXEC_ASSIGN is 0, then the contract is not executed. Also, this is only valid if the data provided to OP_EXEC_ASSIGN is just a single byte "0". Multiple version-0 OP_EXEC_ASSIGN vouts should be valid in a transaction, or 1 non-version-0 OP_EXEC_ASSIGN (or an OP_EXEC deployment) and multiple version-0 OP_EXEC_ASSIGN vouts. This will be used for all money spending that is sent from a contract to another contract
The above three documents describe that if the consensus-associated coin-picking algorithm guarantees that the OP_SPEND opcode does not cause a consensus error, the correctness of the change is ensured. At the same time, it describes the situation where the contract does not need to be run and how it is handled.
QTUM34: Disallow OP_EXEC and OP_EXEC_ASSIGN from coinbase transactions Description: Because of problems with coinbase maturity and potential side effects from ordering of gas-refund scripts, it should not be legal for coinbase outputs to be anything which results in EVM execution or directly changing EVM account balances. This includes version 0 OP_EXEC_ASSIGN outputs. 
The above document stipulates that coinbase transactions should not include contract-related scripts.

Other related documents

In addition, there are some documents describing the infrastructure needed for the new operation code.
QTUMCORE-51:Formalize the version field for OP_CREATE and OP_CALL Description:In order to sustain future extensions to the protocol, we need to set some rules for how we will later upgrade and add new VMs by changing the "version" argument to OP_CREATE and OP_CALL. We need a definitive VM version format beyond our current "just increment when doing upgrades". This would allow us to more easily plan upgrades and soft-forks. Proposed fields: 
  1. VM Format (can be increased from 0 to extend this format in the future): 2 bits2. Root VM - The actual VM to use, such as EVM, Lua, JVM, etc: 6 bits
  2. VM Version - The version of the Root VM to use (for upgrading the root VM with backwards compatibility) - 8 bits
  3. Flag options - For flags to the VM execution and AAL: 16 bits Total: 32 bits (4 bytes). Size is important since it will be in every EXEC transaction Flag option bits that control contract creation: (only apply to OP_CREATE) • 0 (reserve) Fixed gas schedule - if true, then this contract chooses to opt-out of allowing different gas schedules. Using OP_CALL with a gas schedule other than the one specified in it's creation will result in an immediate exception and result in an out of gas refund condition • 1 (reserve) Enable contract admin interface (reserve only, this will be implemented later. Will allow contracts to control for themselves what VM versions and such they allow, and allows the values to be changed over the lifecycle of the contract) • 2 (reserve) Disallow version 0 funding - If true, this contract is not capable of receiving money through version 0 OP_CALL, other than as required for the account abstraction layer. • bits 3-15 available for future extensions Flag options that control contract calls: (only apply to OP_CALL) • (none yet) Flag options that control both contract calls and creation: • (none yet) These flags will be implemented in a later story Note that the version field now MUST be a 4 byte push. A standard EVM contract would now use the version number (in hex) "01 00 00 00" Consensus behavior: VM Format must be 0 to be valid in a block Root VM can be any value. 1 is EVM, 0 is no-exec. All other values result in no-exec (allowed, but the no execution, for easier soft-forks later) VM Version can be any value (soft-fork compatibility). If a new version is used than 0 (0 is initial release version), then it will execute using version 0 and ignore the value Flag options can be any value (soft-fork compatibility). (inactive flag fields are ignored) Standard mempool behavior: VM Format must be 0Root VM must be 0 or 1VM Version must be 0Flag options - all valid fields can be set. All fields that are not assigned must be set to 0Defaults for EVM: VM Format: 0Root VM: 1VM Version: 0Flags: 0
The above documents formally identified OP_CREATE and OP_CALL needed version information, paving the way for subsequent multi-virtual machine support for Qtum.
QTUMCORE-52:Contract Admin Interface Description:(note, this isn't a goal for mainnet, though it would be a nice feature to include) It should be possible to manage the lifecycle of a contract internally within the contract itself. Such variables and configuration values that might need to be changed over the course of a contract's lifecycle: • Allowable gas schedules 
• Allowable VM versions (ie, if a future VM version breaks this contract, don't allow it to be used, as well as deprecating past VM versions from being used to interact with this contract) • Creation flags (the version flags in OP_CREATE) All of these variables must be able to be controlled within the contract itself, using decentralized code. For instance, in a DAO scenario, it might be something that participants can vote on within the contract, and then the contract triggers the code that changes these parameters. In addition, a contract should be capable of detecting it's own settings throughout it's execution as well as when it is initially created. I propose implementing this interface as a special pre-compiled contract. For a contract ot interact with it, it would call it using the Solidity ABI like any other contract. Proposed ABI for the contract: • bytes[2048] GasSchedule(int n) • int GasScheduleCount() • int AddGasSchedule(bytes[2048] • bytes[32] AllowedVMVersions() • void SetAllowedVMVersions(bytes[32]) Alternative implementations: There could be a specific Solidity function which is called in order to validate that the contract should allow itself to be called in a particular manner: pragma solidity 0.4.0; contract BlockHashTest {function BlockHashTest() { }function ValidateGasSchedule(bytes32 addr) public returns (bool) {if(addr=="123454") { return true; //allow contract to run }return false; //do not allow contract to run}function ValidateVMVersion(byte version) public returns (bool){if(version >= 2 && version < 10) { return true; //allow to run on versions 2-9. Say for example 1 had a vulnerability in it, and 10 broke the contract }return false; } } In this way a contract is responsible for managing it's own state. The basic way it would work is that when a you use OP_CALL to call a contract, it would first execute these two functions (and their execution would be included in gas costs). If either function returns false, then it immediately triggers an out of gas condition and cancels execution. It's slightly complicated to manage the "ValidateVMVersion" callback however, because we must decide which VM version to use. A bad one could cause this function itself to misbeha`ve.```````
pragma solidity 0.4.0; contract BlockHashTest {function BlockHashTest() { }function ValidateGasSchedule(bytes32 addr) public returns (bool) {if(addr=="123454") { return true; //allow contract to run }return false; //do not allow contract to run}function ValidateVMVersion(byte version) public returns (bool){if(version >= 2 && version < 10) { return true; //allow to run on versions 2-9. Say for example 1 had a vulnerability in it, and 10 broke the contract }return false; }
The above document describes the management interface of the contract, and yes the contract can manage its own status.
QTUMCORE-53:Add opt-out flags to contracts for version 0 sends Description:Some contracts may wish to opt-out of certain features in Qtum that are not present in Ethereum. This way more Ethereum contracts can be ported to Qtum without worrying about new features in the Qtum blockchain Two flag options should be added to the Version field, which only have an effect in OP_CREATE for creating the contract: 2. (1st bit) Disallow "version 0" OP_CALLs to this contract outside of the AAL. (DisallowVersion0)  If this is enabled, then an OP_CALL using "root VM 0" (which causes no execution) is not allowed to be sent to this contract. If money is attempted to be sent to this contract using "version 0" OP_CALL, then it will result in an out of gas exception and the funds should be refunded. Version 0 payments made internally within the Account Abstraction Layer should not be affected by this flag. Along with these new consensus rules, there should also be some standard mempool checks: 
  1. If an OP_CALL tx uses a different gas schedule than the contract creation, and the disallow dynamic gas flag is set, then the transaction should be rejected from the mempool as a non-standard transaction (version 0 payments should not be allowed as standard transactions in the mempool anyway)
The above document describes how to get better EVM compatibility by ignoring certain Qtum specific features in order to port Ethereum contract code. This makes smart contracts in the Ethereum ecosystem more easily compatible with Qtum.


The Qtum original design document presented above describes Qtu's increased opcode associated with the contract run, laying the groundwork for subsequent Qtum's EVM VMs that are compatible with the account model on top of the UTXO model, and also making the account abstraction layer AAL possible. The subsequent Qtum project team will further interpret the key documents. If you have any questions, readers can post comments in the comments area or contact the Qtum project team .
The Qtum quantum chain public number will be updated from time to time around the above topics to restore the history of the Qtum project and key technologies from scratch .
Please note that based on Patrick Dai's translation request, the content in this material is translated to English and published on Reddit.
OP's Qtum Address: QMmYAMEFgvPJGwK9nrwqYw1DHhBkiuEi78
submitted by szhman to Qtum [link] [comments]

How exactly does OP_CHECKSIG verify the signature of a private key to it's corresponding public key?

Reading through the dev-guide and got stuck here.


  1. Alice send Bob 1 btc.
  2. Bob wants to spend it.
  3. Alice's pubkey script runs OP_EQUALVERIFY to verify the pubkey hash decoded from Bob's btc address with the pubkey hash generated from Bob's pubkey.
  4. Alice's pubkey script then runs OP_CHECKSIG which:
In this sentence, how does op_checksig find out if the signature matches with the public key?
I found this but don't understand it. I'm not interested in so much the details but the concept of how it achieves this.
Can anyone help me?
submitted by ecurrencyhodler to Bitcoin [link] [comments]

Make 0-conf double spend infeasable by fixing the r value ahead of time, thereby putting the coins up for grabs when a second transaction is signed

I'm proposing a new kind of transaction that would make double spending 0-conf transactions uneconomical, and thus reducing the risk of double spending for the recipient.
Creating an ECDSA signature involves choosing a random number k. From this number, a value r is derived that is revealed as part of the signature. Quoting from Wikipedia:
As the standard notes, it is crucial to select different k for different signatures, otherwise the equation in step 6 can be solved for d_A, the private key
This is how a while back, coins were stolen from wallets because a bug in their random number generation caused the same k to be used, revealing the private key.
But we can use this to our advantage to discourage double spending. What if embedded in the unspent output is already determined what r value must be used to sign the transaction that spends those coins? That means that signing 2 different transactions that both spend the same output means revealing the private key and putting the coins up for grabs by anyone (effectively the next miner to mine a block).
This does not guarantee the recipient of a 0-conf transaction will receive their coins but it does make double spending uneconomical as the attacker would not get the coins back for themselves. This should reduce the risk of double spending for the recipient.
We could introduce a new operation to the Bitcoin scripting language, similar to OP_CHECKSIG, but with one more input: the r value. When a transaction is created that spends such an output, the specified r must be used in the signature or the transaction is invalid.
One problem is that r must be determine by the recipient of the output while the output is created by the sender. I see 3 potential solutions for this:
  1. Use a P2SH address that has the r value embedded. The problem with this is that each output spent to this address would have to use the same r. So it is crucial that coins are spent to this address no more than once.
  2. When accepting coins, specify the r together with the address that you want to receive the coins to. For example by using the payment protocol BIP 70.
  3. When planning to do a 0-conf transaction, the sender should first move their coins into a new output that fixes the value of r in advance.
To me (2) seems the most promising.
Note: I'm no crypto expert so it would be great if someone could verify and confirm that this would work.
submitted by dskloet to btc [link] [comments]

SCRY.INFO underlying double chain technology sharing

SCRY.INFO underlying double chain technology sharing
In SCRY project, double chain structure is applied in clients. As for signature algorithm, we selected BIP143. In segregated witness, VERSION 0 applied BIP143 signature verification to increase efficiency, but BIP143S algorithm is not applied to general transactions. We have optimized general transaction signature and verification, apply BIP143 signature and verification to increase the efficiency.
1.1Signature algorithm
Bitcoin applied ECDSA (Elliptic Curve Digital Signature Algorithm) as digital signature algorithm. There are 3 use cases of digital signature algorithm in Bitcoin: 1. Signature can verify the owner of private key, the owner of money transferring in that transaction. 2. The proxy verification cannot be denied, that is the transaction cannot be denied. 3. The signature cannot be falsified, that is transaction (or details of transaction) cannot be adjusted by anyone after signature.
There are two parts of digital signature: one is using private key( signature key) to sign the hash of message(transaction), the other one is to allow everyone can verify the signature by provided public key and information.
  • Signature algorithm
The signature algorithm of Bitcoin is as following:
Sig = Fsig( Fhash(m), dA )
dA is private key signature
m is transaction (or part of transaction)
Fhash is hash function
Fsig is signature algorithm
Sig is result signature
There are 2 functions in the whole signature: Fhash and Fsig。
  • Fhash function
Fhash function is to generate Hash of transaction, first serialize the transaction, based on serialized binary data use SHA256 to calculate the transaction Hash. The general transaction (single input and single output) process is as following:
Transaction serialization:
1.nVersion Transaction version
2.InputCount Input count
3.Prevouts Serialize the input UTXO
4.OutputCount Output count
5.outpoint Serialize the output UTXO
6.nLocktime Locked period of transaction
7.Hash Twice SHA256 calculation based on the data above
  • Fsig function
Fsig function signature algorithm is based on ECDSA. There will be a K value every encryption. Based on this K value, the algorithm will generate a temporary public/private key (K,Q), select X axis of public key Q to get a value R, the formula is as following:
S=K-1 *(Hash(m) + dA *R) mod p
K is temporary private key
R is x axis of temporary public key
dA is signature private key
m is transaction data
p is the main sequence of elliptical curve
The function will generate a value S.
In elliptical curve every encryption will generate a K value. Reuse same K value will cause private key exposed, K value should be seriously secured. Bitcoin use FRC6979 TO ensure certainty, use SHA256 to ensure the security of K value. The simple formula is as following:
K =SHA256(dA+HASH(m))
dA is private key,
m is message.
Final signature will be generated with the combination of ( R and S)
  • Signature verification
Verification process is applying signature to generate inverse function, the formula is as following:
P=S-1 *Hash(m)*G +S-1*R*Qa
R and S are signature value
Qa is user(signer)’s public key
m is signed transaction data
G is generator point of elliptical curve
We can see from this formula, based on information (transaction or part of Hash value), public key and signature of signer(R and S value), calculate the P value, the value will be one point on elliptical curve. If the X axis equals R, then the signature is valid.

Bip143 brief introduction

There are 4 ECDSA (Elliptic Curve Digital Signature Algorithm) signature verification code(sigops):CHECKSIG, CHECKSIGVERIFY, CHECKMULTISIG, CHECKMULTISIGVERIFY. One transaction abstract will be SHA256 encryption twice.There are at least 2 disadvantages in Bitcoin original digital signature digest algorithm:
●Hash used for data verification is consistent with transaction bytes. The computation of signature verification is based on O(N2) time complexity, time for verification is too long, BIP143 optimizes digest algorithm by importing some “intermediate state” which can be duplicate, make the time complexity of signature verification turn into O(n).
●The other disadvantages of original signature: There are no Bitcoin amounts included in signature when having the transaction, it is not a disadvantage for nodes, but for offline transaction signature devices (cold wallet), since the importing amount is not available, causing that the exact amount and transaction fees cannot be calculated. BIP143 has included the amount in every transaction in the signature.
BIP143 defines a new kind of task digest algorithm, the standard is as following:
Transaction serialization
1,4,7,9,10 in the list is the same as original SIGHASH algorithm, original SIGHASH type meaning stay the same. The following contains are changed:
  • Serialization method
  • All SIGHASH commit amount for signature
  • FindAndDelete signature is not suitable for scripteCode;
  • AfterOP_CODESEPARATOR(S),OP_CODESEPARATOR will not delete scriptCode( lastOP_CODESEPARATOR will be deleted after every script);
  • SINGLE does not commit input index.When ANYONECANPAY has no setting,the meaning will not be changed,hashPrevouts and outpoint are implicit committed in input index. When SINGLE use ANYONECANPAY, signed input and output will exist in pairs, but have no limitation to index.
2.BIP143 Signature
In go language, we use btcsuite database to finish signature, btcsuite database is an integrated Bitcoin database, it can generate all nodes program of Bitcoin, but we just use btcsuite database public key/private key API, SHA API and sign RFC6979 signature API. In order to avoid redundancy, the following codes have no adjustments to codes.
Transaction HASH generation
Transaction information hash generation, every input in transaction will generate a hash value, if there are multi-input in the transaction, then a hash array will be generated, every hash in the array will be consistent with input in transaction.
Like two transaction input in the image above, every transaction will generate a hash, the transaction above will generate two hash.
  • Fhash function
CalcSignatureHash(script []byte, hashType SigHashType, tx *EMsgTx, idx int)
Script,pubscript is input utxo unlocked script
HashType,signature method or signature type
Tx,details of transaction
Idx,Number of transaction, that is to calculate which transaction hash
The following is Fhash code
For the situation that multi UTXO input in one transaction, for every input, you can deploy it as examples above, then generate a hash array. Before hash generation, you need to clear “SigantureScript”in other inputs, only leave the “SigantureScript” in this input,That is “ScriptSig”field.
The amount for every UTXO is different. You need to pay attention to the 6th step, what you need to input is the amount for every transaction
Multi-input function generation
func txHash(tx msgtx) ( *[][]byte)
Code details
Repeat deploy Fhash function(CalcSignatureHash)then you can generate a hash array.
2.2Sign with HASH
A hash array is generated in the methods above, for every input with a unique hash in the data, we use signRFC6979 signature function to sign the hash, here we deploy functions in btcsuite database directly.
signRFC6979(PrivateKey, hash)
Through this function, we can generate SigantureScript,add this value to every input SigantureScript field in the transaction.
Briefly, multi-sig technology is the question that one UTXO should be signed with how many private keys. There is one condition in script, N public keys are recorded in script, at least M public keys must provide signature to unlock the asset. That is also called M-N method, N is the amount of private keys, M is the signature amount needed for verification
The following is how to realize a 2-2 multisig based on P2SH(Pay-to-Script-Hash) script with go language.
2-2 codes of script function generation:
The function above generated script in the following
Signature function
1. Based on transaction TX,it includes input array []TxIn,generate transaction HASH array,this process is the same as process in general transaction above, deploy the digest function of general transaction above.
func txHash(tx msgtx) ( *[][]byte)
this function generated a hash array, that is every transaction input is consistent with one hash value.
2. Use first public key in redeem script, sign with consistent private key. The process is as general transaction.
signRFC6979(PrivateKey, hash)
After signature, the signature array SignatureScriptArr1 with every single input is generated. Based on this signature value in the array, you can update every input TxIn "SigantureScript" field in transaction TX.
3.Based on updated TX deploy txHash function again, generate new hash array.
func txHash(tx msgtx) ( *[][]byte)
4. Use second public key in redeem script, the consistent private key is used for signature. Use the updated TX in the process above, generate every input hash and sign it.
signRFC6979(PrivateKey, hash)
//Combine the signature generated by first key, signature generated by secondkey and redeem script.
etxscript.EncodeSigScript(&(TX.TxIn[i].SignatureScript),&SigHash2, pkScript)
There are N transactions, so repeat it N times.
The final data is as following:
submitted by StephenCuuuurry to SCRYDDD [link] [comments]

How exactly does OP_CHECKSIG verify the signature of a private key to it's corresponding public key?

Was sent here cuz someone from bitcoin recommended I ask this question here. It's bitcoin related so I apologize in advance if this isn't allowed.


  1. Alice send Bob 1 btc.
  2. Bob wants to spend it.
  3. Alice's pubkey script runs OP_EQUALVERIFY to verify the pubkey hash decoded from Bob's btc address with the pubkey hash generated from Bob's pubkey.
  4. Alice's pubkey script then runs OP_CHECKSIG which:
In this sentence, how does op_checksig find out if the signature matches with the public key?
I found this but don't understand it. I'm not interested in so much the details but the concept of how it achieves this.
Can anyone help me?
submitted by ecurrencyhodler to cryptography [link] [comments]

Why is pay-to-pubkey used for generation transactions?

According to the wiki, generation transactions use pay-to-pubkey, where OP_CHECKSIG is used directly and thus the public key owning the coins is exposed.
In contrast, regular transactions only include the hash of the pubkey as an additional layer of protection. This makes the public key "owning" the bitcoins invisible. This way, even if ECDSA is fully broken, noone can steal the coins unless the output has been used as an input (which discloses the pubkey, and, if change addresses are used, conveniently drains the output so there is nothing left to steal).
Thus, if my understanding is correct, the lack of this protection for generation transactions will allow people to steal all BTC from all addresses ever used as a destination for "raw" mining (does not apply to mining pool payouts) if ECDSA is ever broken.
Does anyone have any idea why this layer of protection was omitted for generation transactions?
submitted by aaaaaaaarrrrrgh to Bitcoin [link] [comments]

BIP Number Request: Open Asset | Nicolas Dorier | May 26 2016

Nicolas Dorier on May 26 2016:
Open Asset is a simple and well known colored coin protocol made by Flavien
Charlon, which has been around for more than two years ago.
Open Asset is OP_RETURN to store coin's color. Since then, the only
modification to the protocol has been for allowing OA data to be into any
push into an OP_RETURN.
The protocol is here:
I asked to Flavien Charlon if he was OK if I submit the protocol to the
mailing list before posting.
Additional BIP number might be required to cover for example the "colored
address" format:
But I will do it in a separate request.
Here is the core of the Open Asset specification:
Title: Open Assets Protocol (OAP/1.0)
Author: Flavien Charlon
Created: 2013-12-12
This document describes a protocol used for storing and transferring
custom, non-native assets on the Blockchain. Assets are represented by
tokens called colored coins.
An issuer would first issue colored coins and associate them with a
formal or informal promise that he will redeem the coins according to
terms he has defined. Colored coins can then be transferred using
transactions that preserve the quantity of every asset.
In the current Bitcoin implementation, outputs represent a quantity of
Bitcoin, secured by an output script. With the Open Assets Protocol,
outputs can encapsulate a quantity of a user-defined asset on top of
that Bitcoin amount.
There are many applications:
could then be traded frictionlessly through the Bitcoin
could withdraw and deposit money in colored coins, and trade those, or
use them to pay for goods and services. The Blockchain becomes a
system allowing to transact not only in Bitcoin, but in any currency.
of colored coins. The door would only open when presented with a
wallet containing that specific coin.
==Protocol Overview==
Outputs using the Open Assets Protocol to store an asset have two new
asset stored on the output.
many units of that asset are stored on the output.
This document describes how the asset ID and asset quantity of an
output are calculated.
Each output in the Blockchain can be either colored or uncolored:
both undefined).
non-null asset ID.
The ID of an asset is the RIPEMD-160 hash of the SHA-256 hash of the
output script referenced by the first input of the transaction that
initially issued that asset (script_hash =
RIPEMD160(SHA256(script))). An issuer can reissue more of an
already existing asset as long as they retain the private key for that
asset ID. Assets on two different outputs can only be mixed together
if they have the same asset ID.
Like addresses, asset IDs can be represented in base 58. They must use
version byte 23 (115 in TestNet3) when represented in base 58. The
base 58 representation of an asset ID therefore starts with the
character 'A' in MainNet.
The process to generate an asset ID and the matching private key is
described in the following example:

The issuer first generates a private key:


He calculates the corresponding address:


Next, he builds the Pay-to-PubKey-Hash script associated to that

address: OP_DUP OP_HASH160
010966776006953D5567439E5E39F86A0D273BEE OP_EQUALVERIFY

The script is hashed: 36e0ea8e93eaa0285d641305f4c81e563aa570a2

Finally, the hash is converted to a base 58 string with checksum

using version byte 23:
The private key from the first step is required to issue assets
identified by the asset ID
ALn3aK1fSuG27N96UGYB1kUYUpGKRhBuBC. This acts as a
digital signature, and gives the guarantee that nobody else but the
original issuer is able to issue assets identified by this specific
asset ID.
==Open Assets Transactions==
Transactions relevant to the Open Assets Protocol must have a special
output called the marker output. This allows clients to recognize such
transactions. Open Assets transactions can be used to issue new
assets, or transfer ownership of assets.
Transactions that are not recognized as an Open Assets transaction are
considered as having all their outputs uncolored.
===Marker output===
The marker output can have a zero or non-zero value. The marker output
starts with the OP_RETURN opcode, and can be followed by any sequence
of opcodes, but it must contain a PUSHDATA opcode containing a
parsable Open Assets marker payload. If multiple parsable PUSHDATA
opcodes exist in the same output, the first one is used, and the other
ones are ignored.
If multiple valid marker outputs exist in the same transaction, the
first one is used and the other ones are considered as regular
outputs. If no valid marker output exists in the transaction, all
outputs are considered uncolored.
The payload as defined by the Open Assets protocol has the following format:
! Field !! Description !! Size
! OAP Marker || A tag indicating that this transaction is an
Open Assets transaction. It is always 0x4f41. || 2 bytes
! Version number || The major revision number of the Open Assets
Protocol. For this version, it is 1 (0x0100). || 2 bytes
! Asset quantity count || A
var-integer] representing the number of items in the asset
quantity list field. || 1-9 bytes
! Asset quantity list || A list of zero or more
[ LEB128-encoded] unsigned integers
representing the asset quantity of every output in order (excluding
the marker output). || Variable
! Metadata length || The
var-integer] encoded length of the metadata field. || 1-9
! Metadata || Arbitrary metadata to be associated with
this transaction. This can be empty. || Variable
Possible formats for the metadata field are outside of
scope of this protocol, and may be described in separate protocol
specifications building on top of this one.
The asset quantity list field is used to determine the
asset quantity of each output. Each integer is encoded using variable
length [ LEB128] encoding (also
used in [
Google Protocol Buffers]). If the LEB128-encoded asset quantity of any
output exceeds 9 bytes, the marker output is deemed invalid. The
maximum valid asset quantity for an output is 263 - 1
If the marker output is malformed, it is considered non-parsable.
Coinbase transactions and transactions with zero inputs cannot have a
valid marker output, even if it would be otherwise considered valid.
If there are less items in the asset quantity list than
the number of colorable outputs (all the outputs except the marker
output), the outputs in excess receive an asset quantity of zero. If
there are more items in the asset quantity list than the
number of colorable outputs, the marker output is deemed invalid. The
marker output is always uncolored.
After the asset quantity list has been used to assign an
asset quantity to every output, asset IDs are assigned to outputs.
Outputs before the marker output are used for asset issuance, and
outputs after the marker output are used for asset transfer.
This example illustrates how a marker output is decoded. Assuming the
marker output is output 1:
Data in the marker output Description ----------------------------- 
0x6a The OP_RETURN opcode. 0x10 The PUSHDATA opcode for a 16 bytes payload. 0x4f 0x41 The Open Assets Protocol tag. 0x01 0x00 Version 1 of the protocol. 0x03 There are 3 items in the asset quantity list. 0xac 0x02 0x00 0xe5 0x8e 0x26 The asset quantity list: - '0xac 0x02' means output 0 has an 
asset quantity of 300.
 - Output 1 is skipped and has an 
asset quantity of 0
 because it is the marker output. - '0x00' means output 2 has an 
asset quantity of 0.
 - '0xe5 0x8e 0x26' means output 3 
has an asset quantity of 624,485.
 - Outputs after output 3 (if any) 
have an asset quantity of 0.
0x04 The metadata is 4 bytes long. 0x12 0x34 0x56 0x78 Some arbitrary metadata. 
===Asset issuance outputs===
All the outputs before the marker output are used for asset issuance.
All outputs preceding the marker output and with a non-zero asset ...[message truncated here by reddit bot]...
submitted by dev_list_bot to bitcoin_devlist [link] [comments]

Time to worry about 80-bit collision attacks or not? | Gavin Andresen | Jan 07 2016

Gavin Andresen on Jan 07 2016:
I'm hoisting this from some private feedback I sent on the segregated
witness BIP:
I said:
"I'd also use RIPEMD160(SHA256()) as the hash function and save the 12
bytes-- a successful preimage attack against that ain't gonna happen before
we're all dead. I'm probably being dense, but I just don't see how a
collision attack is relevant here."
Pieter responded:
"The problem case is where someone in a contract setup shows you a script,
which you accept as being a payment to yourself. An attacker could use a
collision attack to construct scripts with identical hashes, only one of
which does have the property you want, and steal coins.
So you really want collision security, and I don't think 80 bits is
something we should encourage for that. Normal pubkey hashes don't have
that problem, as they can't be constructed to pay to you."
... but I'm unconvinced:
"But it is trivial for contract wallets to protect against collision
attacks-- if you give me a script that is "gavin_pubkey CHECKSIG
arbitrary_data OP_DROP" with "I promise I'm not trying to rip you off, just
ignore that arbitrary data" a wallet can just refuse. Even more likely, a
contract wallet won't even recognize that as a pay-to-gavin transaction.
I suppose it could be looking for some form of "gavin_pubkey
somebody_else_pubkey CHECKMULTISIG ... with the attacker using
somebody_else_pubkey to force the collision, but, again, trivial contract
protocol tweaks ("send along a proof you have the private key corresponding
to the public key" or "everybody pre-commits pubkeys they'll use at
protocol start") would protect against that.
Adding an extra 12 bytes to every segwit to prevent an attack that takes
280 computation and 280 storage, is unlikely to be a problem in practice,
and is trivial to protect against is the wrong tradeoff to make."
20 bytes instead of 32 bytes is a savings of almost 40%, which is
The general question I'd like to raise on this list is:
Should we be worried, today, about collision attacks against RIPEMD160 (our
160-bit hash)?
Mounting a successful brute-force collision attack would require at least
O(280) CPU, which is kinda-sorta feasible (Pieter pointed out that Bitcoin
POW has computed more SHA256 hashes than that). But it also requires
O(280) storage, which is utterly infeasible (there is something on the
order of 235 bytes of storage in the entire world). Even assuming
doubling every single year (faster than Moore's Law), we're four decades
away from an attacker with THE ENTIRE WORLD's storage capacity being able
to mount a collision attack.

Gavin Andresen
-------------- next part --------------
An HTML attachment was scrubbed...
submitted by dev_list_bot to bitcoin_devlist [link] [comments]

Some Questions about bitcoin transactions (specifically - the contents of ScriptSig and ScriptPubKey)

I'm using these pages on the bitcoin wiki to help me understand bitcoin transactions, but I need some clarification:
If we look at a Standard Transaction to Bitcoin address (pay-to-pubkey-hash), the ScriptSig and ScriptPubKey will contain the following:
My understanding is that this script describes what the "receiver" must do to perform the next transaction with the bitcoins included in this transaction. and refer to the public key of this "receiver".
Q1 - and both refer to the "receiver's" public key. So why does OP_CHECKSIG require as an input? Wouldn't be enough?
Q2 - According to the Script wiki page, the signature is a hash on "the entire transaction's outputs, inputs, and script (from the most recently-executed OP_CODESEPARATOR to the end)". When and how is this OP_CODESEPARATOR run?
Q3 - When the signature is computed, it is computed on a "simplified version of the transaction". The parameter must be missing for obvious reasons, but what other parameters are excluded from this "simplified version"?
Thanks in advance. And for those who haven't yet dug into how transactions are formed - it is well worth checking out.
submitted by molodets to Bitcoin [link] [comments]

Blockchain scripting contest, second stage

This blockchain scripting contest is a way to raise awareness about the possibilities and powers of the scripting mechanism integrated in the bitcoin protocol.
Every stage will be about a non-standard transaction output (scriptPubKey) broadcast by me and funded with a given amount. Objective of the stage is to find an appropriate script (scriptSig) that will succesfully resolve the stacked scripts, as requested by the bitcoin protocol. The amount in the tx output is the award of the stage and can be claimed at will.
The difficulty of the stages will increase in each step.
Link to 1st stage and solution
2nd stage
Funding transaction/output: 948aeca2003bf0bdc4f0dc7d61615d05010da8bca744dd9cfa12fb57e2540a2d, n=0
Claimable amount: 5 mBTC !!remember to reserve at least 0.1mBTC for transaction fees!!
scriptPubKey to solve:
OP_DEPTH OP_1 OP_NUMEQUAL OP_IF 6e616d65206f66206e616b616b616d6f746f OP_DROP OP_RIPEMD160 OP_RIPEMD160 9c864b8bb110c05cb9c77381ad5d6868f0fd9f9f OP_EQUAL OP_ELSE OP_DUP OP_HASH160 897b934876ff50bfebe218e30382d7eaa6559a12 OP_EQUALVERIFY OP_CHECKSIG OP_ENDIF 
Difficulty level: medium
State: Unclaimed!
Recommended Toolchain:
Documentation: Transactions, Raw Transactions API, Scripts and OPcodes reference.
Have fun!
PS: Any amount sent to the address 1JHCn9wLLXHc4yfo968FrT259Um2hzeUpy will be used to fund the next stages.
submitted by tartare4562 to Bitcoin [link] [comments]

The ultimate back-up plan: Your private key, stored in the block chain, encrypted

[edit: It is the ultimate back-up, but it doesn't mean it is the safest. I'm too tired to figure that out. I'm just explaining how to store a private key in the block chain, in case it is useful or can be made useful.]
I had that idea if someone is interested, though I guess people won't like it. It's a bit wild. We encrypt the key and put it in the block chain with a trick.
I'm not saying everyone should do this, but it could be useful to know it can be done.
If you trust encryption and your password more than back-ups or a third-party, then it could be nice. I'm no encryption expert but it should be strong enough.
"Instead of taking 1.3 quadrillion years, our magical cracking supercomputer would only need 328 trillion years."
If it's flawed or gets cracked after a billion years, I decline all responsibility. But you can be sneaky about it. I propose a sneaky trick at the end. It's a bit rough on the edges and crazy but I'll put it out there. If people like it, there are always ways to streamline.
Anyway, you can't memorize the key as you can memorize a password. It's true you can put it on paper; then lose the paper. You can encrypt it and keep it on hard drive, then lose the hard drive. Or on a service, and lose the service. The block chain though, is going to stay around as long as you need the key. So I suggest this whole alternative.
You can still put the information on paper if you want. But now, just your memory is enough. Just the password.
The drawback is the infinitesimal odd of someone finding out and spending a lot of years and resources on brute-forcing. I'm not sure what would be the odds of success. Just make it so decades of computing resource cost more than what's inside.
Now I'll explain how to do it from A to Z, for the few interested.
Plan: 0) Vanity 1) Get the key 2) Encrypt the key 3) Put the key in the block chain 4) Retrieval 5) Conclusion
0) Optional: Vanity I recommend a vanity address (choosing the first part of the address). So if worst comes to worst, you find it from memory in the block chain. And also, it's kinda neato. How-to: first, download VanityGen, direct/wiki. Extract it, then Open a console window at the location with shift-right click in the folder, if you have vista/7/8. Then type "vanitygen 1something" in it. It has to start with 1. If it's too long it'll take a lot of time. Ctrl-C to cancel if it's too long. Faster with GPU: oclvanitygen -D 0:0 1something (maybe broken atm) When you have the key, type "importprivkey mykey" in Help->Debug->Console of bitcoin-qt, to add it. Result of this optional step: A beautiful address which can be retrieved from memory if needed (after it has been seen in the block chain with a transaction)
1) Get the key - Download open source Pywallet: direct/profile - Extract somewhere. Shift-right click in the folder and "open a console window" - In the console, type: pywallet --dumpwallet dump.txt If your wallet is encrypted, then add --passphrase=PASSPHRASE Now you find the key in dump.txt. (note: it reads the wallet at C:\Users\x\Bitcoin) Result of this step: the private key; it looks like 51 characters starting with the number 5. (To delete dump.txt, you can use a software so it can't be recovered from HDD, like Recuva it seems)
2) Encrypt the key - Choose an algorithm. Personally, I pick AES-256. - Download a trustworthy program to encrypt text with the algorithm. Here are two with GUI I found. It's open source but I didn't check it, so it's not 100% safe: They're both jar files. Maybe you can click them. Personally I have to go in the console; I'm so tired of that coffee cup. "C:\Program Files (x86)\Java\jre7\bin\java.exe" -jar ImmediateCrypt.jar. It gave me an error though. Not the other. Maybe someone can suggest better. - Choose a good password. It's all about the password (and the software). AES is weak with weak password. And crazy strong with a good password. This is not like websites with protection against brute-force. People can brute-force fully if they find out. I like psycho-pass method which is about a pattern on the keyboard instead of semantics. Side Info: Or a passphrase if you want. Here is a nice table with password entropy: Below 64 bits of entropy, it's too unsafe, it's too weak. We need 128 bits or above, as far as I know. That is 25 random alphanumeric. If you're feeling paranoid, 256 bits. You can check entropy of password roughly here: Remember it is not like websites. There is no "Forgot password?" button. Memorize it permanently; and maybe write it down in your favorite book just in case, I don't know. Result of this step: the encrypted key. It doesn't matter what it looks like as long as it takes you back to the key when you click "Decrypt". (on a different software, preferably)
3) Put the key in the block chain It works by sending some minimum amount to fake addresses, with data encoded in the addresses. Can't try this part because I don't have bitcoins. :[ Only a wallet! If some liked the guide particularly: 1thxd4KJLhBMcfCYaVKYMA8Atv3Dfx9hb :3 I'll follow the method of this great article: (the blog is remarkable!) - We're supposed to split the encrypted key in chunks of 20 characters. Then convert from ASCII to hex. Last chunk we fill with extra zeros. I wrote a little javascript to do it all automatically! If you don't like it, find a software, or do it manually. Not tested much but seems to work for my test. I'll say how to know if it worked. Copy that: encrypted='';har=(encrypted.split ('').map(function(c){return c.charCodeAt(0).toString(16); }));ek="";har.forEach(function(c){ek+=c;});while(ek.length%40!=0)ek+='0';iEK=0;ek2='';while(ek.length>0){ek2+=ek.substr(iEK,iEK+40) + "\n";if(ek.length>=40)ek=ek.substr(40,ek.length-40);else ek='';};ek2;
Check eventual comments to know if it's a hack/broken mess.
I don't do much Javascript, or much anything. Paste the whole thing in the javascript console. To open the console: Chrome, Ctrl-Shift-J. Firefox, Ctrl-Shift-K. IE9, F12. Put your encrypted key between the '' right at the beginning, then enter.
This should display rows of 40-characters chunks of the encrypted key in hex format (numbers, and a to f). I have 6 chunks but it depends on encryption. It should give twice as much characters as the input except for last zeros, and follow this conversion table from Char to Hx column. If it doesn't, call the police. Or use some Ascii to Hex service.
Now we take these chunks one by one and use to convert to BTC addresses.
Send spare money to each one (the strict minimum is suspect and it'd get found easily) in the right order (wait for 1 or 2 confirmations each time to be sure).
And we're done! The information is safe and cozy, in the block chain. Not safe from brute-forcing, but safe from ourselves; and that's safer, isn't it?
4) Retrieval
Alright, how do we go back from the addresses to the encrypted key? I can't try it myself, but apparently, according to the article: 1) Get the transaction ID on, by going to the wallet's profile 2) Go to 3) There will be something like that: "out":[ { "value":"25.08603421", "scriptPubKey":"OP_DUP OP_HASH160 27a1f12771de5cc3b73941664b2537c15316be43 OP_EQUALVERIFY OP_CHECKSIG" } ]
And you need to translate the "27a1f12771de5cc3b73941664b2537c15316be43" part from hex to Unicode. The result should be the chunk of encrypted key, written in hex again. You put all the parts together in order, remove extra zeros. Then use a program to go back from hex bytes to ASCII. Maybe someone can do it or I'll put the javascript one of these days if people are interested; I don't think they'll be. Usually I'm serious and extensive but you can't imagine how tired I am these days, of everything. Anyway, you put that ASCII in the AES program with your password, you click Decrypt.
Then you have your private key.
If you do this, don't lose other back-ups until you have successfully retrieved the key, to know it works.
5) Conclusion I understand that there's a small chance that someone figures the transactions are data, reassembles the parts, has massive luck and breaks the crazy strong encryption with supercomputers and botnets in less than decades, or aliens hack your bitcoins with quantum computers, ect... But I don't know, that seems very unlikely to me; more unlikely than losing personal back-ups or third-parties being untrustworthy.
More importantly, it gives peace of mind of not having to manage back-up stuff. You can format your hard drive and burn your house down if you want without worrying about losing stuff; well, except the house. And maybe the wife. Or you go to prison 20 years, and it'll still be there. If some of you want to go to prison. I know of one.
Here's a complicated idea for the extra-extra-paranoid: You send just one letter by one letter of the encrypted key, into dozens of fake addresses, to which you send bitcoins you got from an exchange and not from the main wallet, and only you know the correct addresses/order with the data, because of a pattern in the other letters. For example, the 2nd letter of the 1st data part is the 1st letter of your password when it's hashed. The 3rd letter of the 2nd data part is the 2nd letter of your hashed password. Ect... And it's not true for the other parts. So you know the order, but not someone without the password. It can go like this for many parts, then maybe if you run out of letters you send through a different wallet. All other characters are misleading except the 1st one, or last one, being the key character. And you also send money to other fake wallets which are purely misleading. Even if a flaw in AES was found and it could be broken instantly, an attacker would have to find the correct combination even before the strong encryption brute-forcing, he can't even know if he has the right combination, and that can be a big number of combinations. You can do the math. It's exponential stuff, I think. That's something I just thought of quickly, and I don't know much about any of that. Someone can find better. (Maybe, or maybe not, there's something about the encryption output which makes it so we can find the order back without password, then we'd need some kind of trick to obfuscate the position or nature of key characters but I won't spend any more time on something likely to be wrong/uninteresting).
tl;dr: "It works by sending some minimum amount to fake addresses, with data encoded in the addresses. "
Point is, once we know we can store data in the block chain, there are plenty of ways to make it so we're never locked out from the main address.
Well, if you can remember the password.
I hope this was useful to someone!
submitted by yemethzi to Bitcoin [link] [comments]

Dissecting a P2PKH Bitcoin Transaction down to the last Byte ep 13: How is bitcoin The Of Bitcoin - Wikipedia Building on Bitcoin - Working with scripts with logical opcodes Bitcoin - Wiki

scriptPubKey: OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG scriptSig: <sig> <pubKey> A Bitcoin address is only a hash, so the sender can't provide a full public key in scriptPubKey. When redeeming coins that have been sent to a Bitcoin address, the recipient provides both the signature and the public key. 42 coin Review []. 42-coin was introduced in early January of 2014 on forum by user named hendo420. His idea was to create a "super rare" coin, with "only 42 coins to be mined". Denoting the meaning of life, according to Douglas Adams’ The Hitchhiker's Guide to The Galaxy, the number 42 in this case relates to the number used by 1950s American baseball player, Jackie Robinson. From Bitcoin Wiki. Jump to: navigation, search. Byte-map of Transaction with each type of TxIn and TxOut. An transaction is a transfer of Bitcoin value that is broadcast to the network and collected into blocks. A transaction typically references previous transaction outputs as new transaction inputs and dedicates all input Bitcoin values to Genesis block is the first block of a blockchain.Modern versions of Bitcoin number it as block 0, though very early versions counted it as block 1.The genesis block is almost always hardcoded into the software of the applications that utilize its blockchain. It is a special case in that it does not reference a previous block, and for Bitcoin and almost all of its derivatives, it produces an Bitcoin transaction confirmation is needed to prevent double-spending of the same money. One of the main advantages of bitcoin is that it avoids the problem of double-spending, i.e. the risk that a digital currency token may be copied and spent more than once.In spite of having no central authority to verify that its tokens are not being duplicated, bitcoin successfully avoids double-spending

[index] [2644] [10091] [12297] [4457] [12803] [2890] [15299] [2997] [5847] [10574]

Dissecting a P2PKH Bitcoin Transaction down to the last Byte

The Of Bitcoin - Wikipedia Here are three actions to help you get started utilizing Bitcoin Money right now: A Bitcoin wallet is an app or program that enables you send and receive BCH. Wallets ... bitcoin wallet bitcoin to usd bitcoin wiki bitcoin market bitcoin forum bitcoin difficulty buy bitcoin bitcoin central bitcoin faucet bitcoin pool earn bitcoins bitcoin mining pool ... Building on Bitcoin conference Lisbon, 3-4 July 2018 Thomas Kerin: Working with scripts with logical opcodes Transcript : CheckSig provides transparent bitcoin custody for institutional investors and high-net-worth individuals. The custody solution is unique as it is based on a public open protocol which rejects ... This is the first part of a more technical talk where Andreas explores Bitcoin script, with examples from the 2nd edition of Mastering Bitcoin, focusing on the use of conditional statements, flow ...