Bitcoin Hash

PSA: Guide on how to recover your lost Segwit coins using Electron Cash

How to get your recovered SegWit funds using Electron Cash

Background

Thousands of BCH on thousands of coins that were accidentally send to Segwit 3xxx addresses were recovered by BTC.TOP in block 582705.
This was a wonderful service to the community. This had to be done quickly as the coins were anyone can spend and needed to be sent somewhere. This all had to be done before thieves could get their dirty paws on them.
So.. How were they recovered? Did BTC.TOP just take the coins for themselves? NO: They were not taken by BTC.TOP. This would be wrong (morally), and would open them up to liability and other shenanigans (legally).
Instead --BTC.TOP acted quickly and did the legally responsible thing with minimal liability. They were sent on to the intended destination address of the SegWit transaction (if translated to BCH normal address).
This means BTC.TOP did not steal your coins and/or does not have custody of your funds!
But this does mean you now need to figure out how to get the private key associated with where they were sent -- in order to unlock the funds. (Which will be covered below).
Discussions on why this was the most responsible thing to do and why it was done this way are available upon request. Or you can search this subreddit to get to them.

Ok, so BTC.TOP doesn't have them -- who does?

You do (if they were sent to you)! Or -- the person / address they were sent to does!

HUH?

The Segwit transactions have a bad/crazy/messed-up format which contains an output (destination) which contains a hash of a public key inside. So they "sort of" contain a regular bitcoin address inside of them, with other Segwit garbage around them. This hash was decoded and translated to a regular BCH address, and the funds were sent there.
Again: The funds were forwarded on to a regular BCH address where they are safe. They are now guarded by a private key -- where they were not before (before they were "anyone can spend"). It can be argued this is the only reasonable thing to have done with them (legally and morally) -- continue to send them to their intended destination. This standard, if it's good enough for the US Post Office and Federal Mail, is good enough here. It's better than them being stolen.

Ok, I get it... they are on a regular BCH address now. The address of the destination of the Tx, is it?

Yes. So now a regular BCH private key (rather than anyone can spend) is needed to spend them further. Thus the Segwit destination address you sent them to initially was effectively translated to a BCH regular address. It's as if you posted a parcel with the wrong ZIP code on it -- but the USPS was nice enough to figure that out and send it to where you intended it to go.

Why do it this way and not return to sender?

Because of the ambiguity present-- it's not entirely clear which sender to return them to. There is too much ambiguity there, and would have led to many inputs not being recovered in a proper manner. More discussion on this is available upon request.

Purpose of this guide

This document explains how to:
Complications to watch out for:

Step 1: Checking where your coins went

To verify if this recovery touched one of your lost coins: look for the transaction that spent your coins and open it on bch.btc.com explorer.

Normal aka "P2PKH"

Let’s take this one for example.
Observe the input says:
P2SH 160014d376cf1baff9eeed943d58551d53c48377adb98c 
And the output says:
P2PKH OP_DUP OP_HASH160 d376cf1baff9eeed943d58551d53c48377adb98c OP_EQUALVERIFY OP_CHECKSIG 
Notice a pattern?
The fact that these two highlighted hexadecimal strings are the same means that the funds were forwarded to the identical public key, and can be spent by the private key (corresponding to that public key) if it is imported into a Bitcoin Cash wallet.

Multisig aka "P2SH"

If the input starts with “P2SH 220020…”, as in this example, then your segwit address is a script -- probably a multisignature. While the input says “P2SH 22002019aa2610492ee2c18605597136294596d4f0f9bc6ce0974ed3a975d65da4ca1e”, the output says “P2SH OP_HASH160 21bdc73fb15b3bb7bd1be365e92447dc2a44e662 OP_EQUAL”. These two strings actually correspond to the same script, but they are different in content and length due to segwit’s design. However, you just need to RIPEMD160 hash the first string and compare to the second -- you can check this by entering the input string (after the 220020 part) into this website’s Binary Hash field and checking the resulting RIPEMD160 hash. The resulting hash is 21bdc73fb15b3bb7bd1be365e92447dc2a44e662, which corresponds to the output hex above, and this means the coins were forwarded to the same spending script but in "non-segwit form". You will need to re-assemble the same multi-signature setup and enough private keys on a Bitcoin Cash wallet. (Sorry for the succinct explanation here. Ask in the comments for more details perhaps.)

No match -- what?!

If the string does not match (identically in the Normal case above, or after properly hashing in the Multisig case above), then your coins were sent elsewhere, possibly even taken by an anonymous miner. :'(

Step 2: How To Do the Recovery

Recover "Normal" address transactions (P2PKH above)

This is for recoveries where the input string started with “160014”.
Option 1 (BIP39 seed):
Option 2 (single key):
Option 3 (xprv -- many keys):
Code:
mkey = "yprvAJ48Yvx71CKa6a6P8Sk78nkSF7iqqaRob1FN7Jxsqm3L52K8XmZ7EtEzPzTUWXAaHNfN4DFAuP4cdM38yrE6j3YifV8i954hyD5rhPyUNVP" from electroncash.bitcoin import DecodeBase58Check, EncodeBase58Check EncodeBase58Check(b'\x04\x88\xad\xe4'+DecodeBase58Check(mkey)[4:]) 
Option 4 (hardware wallet):

How to Recover Multisignature wallets (P2WSH-in-P2SH in segwit parlance)

This is for recoveries where the input string started with "220020.
Please read the above instructions for how to import single keys. You will need to do similar but taking care to reproduce the same set of multisignature keys as you had in the BTC wallet. Note that Electron Cash does not support single-key multisignature, so you need to use the BIP39 / xprv approach.
If you don’t observe the correct address in Electron Cash, then check the list of public keys by right clicking on an address, and compare it to the list seen in your BTC wallet. Also ensure that the number of required signers is identical.
submitted by NilacTheGrim to btc [link] [comments]

BITBOX SDK v7 is live! 100% refactor from Babel to Typescript and much more!

I'm very pleased to announce BITBOX v7 is live! This is a complete refactor from Babel to typescript. Our goal is to create professional-grade software and typescript provides the abstractions to take BITBOX to an entirely new place. Thanks to James_Cramer for helping debug.
All documentation has been updated. All BITBOX scaffolds (angular, react, next, node, vue and websockets) have been updated as well.
Changes include interfaces for all classes and returned data structures. Data types for all method definitions, arguments/parameters and variables. All interfaces are also defined in the docs.
New functionality includes:
Over 2000+ passing tests .
submitted by cgcardona to btc [link] [comments]

Trying to get a deeper understanding of atomic swaps

Hi together,
I'm an IT-student and writing a thesis about atomic swaps on BTC and BTC-like blockchains. For the thesis I decided to use BTC, LTC, BCH and DCR. These chains have a somehow similar codebase and the same scripting language (I'm not a professional, so there might be differences, but they are not that serious). And they all have a high enough marketcap to be relevant for atomic swaps.
So the goal of the thesis is to find hashed timelock contracts (HTLCs) and connect matching HTLCs from different chains to get the atomic swap. Therefore I first searched the web for anything on atomic swaps [1] and analyzed the input script of this transaction [2] to get a basic understanding how atomic swaps work and what they look like.
Then I wrote a go program to search for any script longer than simple P2PKH scripts. This gave me a list of many different scripts which I analyzed by hand to only take the HTLC ones. (Besides many multisig scripts, there is not much to find on BTC^^)
At this point I found multiple different types of HTLCs as listed below. Afterwards I crawled* BTC again saving all transactions with HTLC scripts, storing the interesting data like tx-id, input value, pubKeyHashes, the secrets and their hashes. I found about one hundret HTLCs on BTC so far.
I did the same for LTC and found about 400 HTLCs.
As far as I understood, the secrets of HTLCs have to be the same on both chains. So I wrote another go program to match the found HTLCs from BTC and LTC and got around 30 matches. The next steps would then be to crawl BCH and DCR and also match the HTLCs found there.
* Crawling in this case means that I start to search the blockchain backwards (to get the newest first, the beginning years are not that interesting in this case^^) until the beginning of 2017. So about 18 months. As stated in [1] the first known atomic swap between BTC and LTC was made on 19th April 2017 (or April 19th 2017 or 19.4.2017 or whatever you like). So there is not much sense in crawling any further.
My questions now are the following:
I'm open to any constructive input and hope you have a few answers for me. Thank you in advance.
Type 1: sha256 secret, length=97byte
63 if 82 size 01 data1 20 88 equalverify a8 sha256 20 data32  88 equalverify 76 dup a9 hash160 14 data20  67 else 04 data4  b1 checklocktimeverify 75 drop 76 dup a9 hash160 14 data20  68 endif 88 equalverify ac checksig 
Type 2a: sha256 secret, length=94byte
63 if a8 sha256 20 data32  76 dup a9 hash160 14 data20  88 equalverify ac checksig 67 else 04 data4  b1 checklocktimeverify 75 drop 76 dup a9 hash160 14 data20  88 equalverify ac checksig 68 endif 
Type 2b: sha256 secret, length=93byte
63 if a8 sha256 20 data32  88 equalverify 76 dup a9 hash160 14 data20  67 else 04 data4  b1 checklocktimeverify 75 drop 76 dup a9 hash160 14 data20  68 endif 88 equalverify ac checksig 
Type 3: ripemd160 secret, length=81byte
63 if a6 ripemd160 14 data20  88 equalverify 76 dup a9 hash160 14 data20  67 else 04 data4  b1 checklocktimeverify 75 drop 76 dup a9 hash160 14 data20  68 endif 88 equalverify ac checksig 
Type 4a: hash160 secret, length=86byte
63 if 03 data3  b1 checklocktimeverify 75 drop 76 dup a9 hash160 14 data20  88 equalverify ac checksig 67 else 76 dup a9 hash160 14 data20  88 equalverify ad checksigverify 82 size 01 data1 21 -> 33 88 equalverify a9 hash160 14 data20  87 equal 68 endif 
Type 4b: hash160 secret, length=82byte
63 if 03 data3  b1 checklocktimeverify 75 drop 76 dup a9 hash160 14 data20  88 equalverify ac checksig 67 else 76 dup a9 hash160 14 data20  88 equalverify ad checksigverify a9 hash160 14 data20  87 equal 68 endif 
Type 5a: hash160 secret, length=81byte
63 if a9 hash160 14 data20  88 equalverify 76 dup a9 hash160 14 data20  67 else 04 data4  b2 checksequenceverify 75 drop 76 dup a9 hash160 14 data20  68 endif 88 equalverify ac checksig 
Type 5b: hash160 secret, length=78byte
63 if a9 hash160 14 data20  88 equalverify 76 dup a9 hash160 14 data20  67 else 01 data1  b2 checksequenceverify 75 drop 76 dup a9 hash160 14 data20  68 endif 88 equalverify ac checksig 
Type 6: hash160 secret, length=79byte
63 if 54  b1 checklocktimeverify 75 drop 76 dup a9 hash160 14 data20  88 equalverify ac checksig 67 else 76 dup a9 hash160 14 data20  88 equalverify ad checksigverify a9 hash160 14 data20  87 equal 68 endif 
Type 7: multiple ripemd160 secrets, length=80 + n*23byte
63 if a6 ripemd160 14 data20  88 equalverify a6 ripemd160 14 data20  ... 88 equalverify a6 ripemd160 14 data20  88 equalverify 21 data33  ac checksig 67 else 04 data4  b1 checklocktimeverify 75 drop 21 data33  ac checksig 68 endif 
Type 8: multiple ripemd160 secrets, length=81 + n*23byte
74 depth 60 16 87 equal 63 if a6 ripemd160 14 data20  88 equalverify a6 ripemd160 14 data20  ... 88 equalverify a6 ripemd160 14 data20  88 equalverify 21 data33  67 else 03 data3  b1 checklocktimeverify 75 drop 21 data33  68 endif ac checksig 
[1] http://www.cryptovibes.com/crypto-news/charlie-lees-atomic-swap-between-litecoin-and-bitcoin-was-a-success/
[2] https://insight.bitpay.com/tx/0bb5a53a9c7e84e2c45d6a46a7b72afc2feffb8826b9aeb3848699c6fd856480
submitted by noobWithAComputer to Bitcoin [link] [comments]

This is how we will recover coins sent to the wrong address or an unowned address

Don't worry, I'm NOT advocating that transactions should be reversible.
Many of us have accidentally sent coins to the wrong address or an unowned address, resulting in those coins being permanently unrecoverable and unspendable. I haven't made this mistake (yet), but damn it makes me nervous when I send larger transactions.
Unfortunately, we'll never be able to revert those past mistakes, but with a small change to the bitcoin protocol, we can make it so that we can recover the coins when we make this sort of mistake in the future.
Please let me know your thoughts about my solution below, and if something like this is already in the works.

The solution, conceptually

If everybody knew everyone else's public keys, we could prevent these permanent mistakes with multisig scripts. The change I'm proposing will make it so we can prevent the mistakes without knowing each other's public keys, but I'll explain it in terms of multisig, because the solution is conceptually the same, and easier to explain:
Instead of sending coins directly to a recipient address, send your coins to a 1-of-2 multisig account, shared by both you and the recipient.
This means that effectively, the transaction is "cancellable", but only until the recipient sends the coins to his own account. At that point the coins are irreversibly his.
The downside of this is that when receiving a payment, you must explicitly accept it before the coins are truly yours -- you should not consider the coins as yours until you do this. The upside is that it guarantees that coins are never lost at inactive addresses.

Problems that this solves

  1. Sending to an unowned address (base58Check almost always protects against this)
  2. Sending to an address that was owned, but the private keys were lost and nobody has control of the address anymore
  3. Sending to the wrong (but owned) address, unless the unintended recipient is quick to claim the coins
  4. Sending your coins to the wrong address on an exchange (i.e. an address for a forked blockchain)

Implementation and technical details

We can accomplish the above without knowledge of each others' public keys, if we use a custom pubkey script. Nodes only accept transactions with standard pubkey scripts, so we'd need to define a new standard script.
The typical P2PKH script looks like this:
scriptPubKey: OP_DUP OP_HASH160 OP_DUP  OP_EQUALVERIFY OP_CHECKSIG scriptSig:   
The new standard script I'm proposing is this:
scriptPubKey: OP_DUP OP_HASH160 OP_DUP  OP_EQUAL OP_SWAP  OP_EQUAL OP_ADD OP_VERIFY OP_CHECKSIG ( would be your address, and  would be the recipient's address) scriptSig:   
This script allows the coins to be spent by either the owner of or .
I call this new transaction type Pay To Either Public Key Hash (P2EPKH), or colloquially, "fuck-up protection".
Of course, wallets would have to be able to recognize the new transaction type, and offer controls to claim coins from incoming P2EPKH transactions or to cancel unclaimed P2EPKH transactions.

Feedback, please.

What do you all think? Is this generally a decent idea? Has this idea been floated around before? Is there another solution for this issue in the works? If this is a good idea, how do I get the attention of the devs?
submitted by ransoing to btc [link] [comments]

A reminder why CryptoNote protocol was created...

CryptoNote v 2.0 Nicolas van Saberhagen October 17, 2013
1 Introduction
“Bitcoin” [1] has been a successful implementation of the concept of p2p electronic cash. Both professionals and the general public have come to appreciate the convenient combination of public transactions and proof-of-work as a trust model. Today, the user base of electronic cash is growing at a steady pace; customers are attracted to low fees and the anonymity provided by electronic cash and merchants value its predicted and decentralized emission. Bitcoin has effectively proved that electronic cash can be as simple as paper money and as convenient as credit cards.
Unfortunately, Bitcoin suffers from several deficiencies. For example, the system’s distributed nature is inflexible, preventing the implementation of new features until almost all of the net- work users update their clients. Some critical flaws that cannot be fixed rapidly deter Bitcoin’s widespread propagation. In such inflexible models, it is more efficient to roll-out a new project rather than perpetually fix the original project.
In this paper, we study and propose solutions to the main deficiencies of Bitcoin. We believe that a system taking into account the solutions we propose will lead to a healthy competition among different electronic cash systems. We also propose our own electronic cash, “CryptoNote”, a name emphasizing the next breakthrough in electronic cash.
2 Bitcoin drawbacks and some possible solutions
2.1 Traceability of transactions
Privacy and anonymity are the most important aspects of electronic cash. Peer-to-peer payments seek to be concealed from third party’s view, a distinct difference when compared with traditional banking. In particular, T. Okamoto and K. Ohta described six criteria of ideal electronic cash, which included “privacy: relationship between the user and his purchases must be untraceable by anyone” [30]. From their description, we derived two properties which a fully anonymous electronic cash model must satisfy in order to comply with the requirements outlined by Okamoto and Ohta:
Untraceability: for each incoming transaction all possible senders are equiprobable.
Unlinkability: for any two outgoing transactions it is impossible to prove they were sent to the same person.
Unfortunately, Bitcoin does not satisfy the untraceability requirement. Since all the trans- actions that take place between the network’s participants are public, any transaction can be unambiguously traced to a unique origin and final recipient. Even if two participants exchange funds in an indirect way, a properly engineered path-finding method will reveal the origin and final recipient.
It is also suspected that Bitcoin does not satisfy the second property. Some researchers stated ([33, 35, 29, 31]) that a careful blockchain analysis may reveal a connection between the users of the Bitcoin network and their transactions. Although a number of methods are disputed [25], it is suspected that a lot of hidden personal information can be extracted from the public database.
Bitcoin’s failure to satisfy the two properties outlined above leads us to conclude that it is not an anonymous but a pseudo-anonymous electronic cash system. Users were quick to develop solutions to circumvent this shortcoming. Two direct solutions were “laundering services” [2] and the development of distributed methods [3, 4]. Both solutions are based on the idea of mixing several public transactions and sending them through some intermediary address; which in turn suffers the drawback of requiring a trusted third party. Recently, a more creative scheme was proposed by I. Miers et al. [28]: “Zerocoin”. Zerocoin utilizes a cryptographic one-way accumulators and zero-knoweldge proofs which permit users to “convert” bitcoins to zerocoins and spend them using anonymous proof of ownership instead of explicit public-key based digital signatures. However, such knowledge proofs have a constant but inconvenient size - about 30kb (based on today’s Bitcoin limits), which makes the proposal impractical. Authors admit that the protocol is unlikely to ever be accepted by the majority of Bitcoin users [5].
2.2 The proof-of-work function
Bitcoin creator Satoshi Nakamoto described the majority decision making algorithm as “one- CPU-one-vote” and used a CPU-bound pricing function (double SHA-256) for his proof-of-work scheme. Since users vote for the single history of transactions order [1], the reasonableness and consistency of this process are critical conditions for the whole system.
The security of this model suffers from two drawbacks. First, it requires 51% of the network’s mining power to be under the control of honest users. Secondly, the system’s progress (bug fixes, security fixes, etc...) require the overwhelming majority of users to support and agree to the changes (this occurs when the users update their wallet software) [6].Finally this same voting mechanism is also used for collective polls about implementation of some features [7].
This permits us to conjecture the properties that must be satisfied by the proof-of-work pricing function. Such function must not enable a network participant to have a significant advantage over another participant; it requires a parity between common hardware and high cost of custom devices. From recent examples [8], we can see that the SHA-256 function used in the Bitcoin architecture does not posses this property as mining becomes more efficient on GPUs and ASIC devices when compared to high-end CPUs.
Therefore, Bitcoin creates favourable conditions for a large gap between the voting power of participants as it violates the “one-CPU-one-vote” principle since GPU and ASIC owners posses a much larger voting power when compared with CPU owners. It is a classical example of the Pareto principle where 20% of a system’s participants control more than 80% of the votes.
One could argue that such inequality is not relevant to the network’s security since it is not the small number of participants controlling the majority of the votes but the honesty of these participants that matters. However, such argument is somewhat flawed since it is rather the possibility of cheap specialized hardware appearing rather than the participants’ honesty which poses a threat. To demonstrate this, let us take the following example. Suppose a malevolent individual gains significant mining power by creating his own mining farm through the cheap hardware described previously. Suppose that the global hashrate decreases significantly, even for a moment, he can now use his mining power to fork the chain and double-spend. As we shall see later in this article, it is not unlikely for the previously described event to take place.
2.3 Irregular emission
Bitcoin has a predetermined emission rate: each solved block produces a fixed amount of coins. Approximately every four years this reward is halved. The original intention was to create a limited smooth emission with exponential decay, but in fact we have a piecewise linear emission function whose breakpoints may cause problems to the Bitcoin infrastructure.
When the breakpoint occurs, miners start to receive only half of the value of their previous reward. The absolute difference between 12.5 and 6.25 BTC (projected for the year 2020) may seem tolerable. However, when examining the 50 to 25 BTC drop that took place on November 28 2012, felt inappropriate for a significant number of members of the mining community. Figure 1 shows a dramatic decrease in the network’s hashrate in the end of November, exactly when the halving took place. This event could have been the perfect moment for the malevolent individual described in the proof-of-work function section to carry-out a double spending attack [36]. Fig. 1. Bitcoin hashrate chart (source: http://bitcoin.sipa.be)
2.4 Hardcoded constants
Bitcoin has many hard-coded limits, where some are natural elements of the original design (e.g. block frequency, maximum amount of money supply, number of confirmations) whereas other seem to be artificial constraints. It is not so much the limits, as the inability of quickly changing them if necessary that causes the main drawbacks. Unfortunately, it is hard to predict when the constants may need to be changed and replacing them may lead to terrible consequences.
A good example of a hardcoded limit change leading to disastrous consequences is the block size limit set to 250kb1. This limit was sufficient to hold about 10000 standard transactions. In early 2013, this limit had almost been reached and an agreement was reached to increase the limit. The change was implemented in wallet version 0.8 and ended with a 24-blocks chain split and a successful double-spend attack [9]. While the bug was not in the Bitcoin protocol, but rather in the database engine it could have been easily caught by a simple stress test if there was no artificially introduced block size limit.
Constants also act as a form of centralization point. Despite the peer-to-peer nature of Bitcoin, an overwhelming majority of nodes use the official reference client [10] developed by a small group of people. This group makes the decision to implement changes to the protocol and most people accept these changes irrespective of their “correctness”. Some decisions caused heated discussions and even calls for boycott [11], which indicates that the community and the developers may disagree on some important points. It therefore seems logical to have a protocol with user-configurable and self-adjusting variables as a possible way to avoid these problems.
2.5 Bulky scripts
The scripting system in Bitcoin is a heavy and complex feature. It potentially allows one to create sophisticated transactions [12], but some of its features are disabled due to security concerns and some have never even been used [13]. The script (including both senders’ and receivers’ parts) for the most popular transaction in Bitcoin looks like this: OP DUP OP HASH160 OP EQUALVERIFY OP CHECKSIG. The script is 164 bytes long whereas its only purpose is to check if the receiver possess the secret key required to verify his signature.
Read the rest of the white paper here: https://cryptonote.org/whitepaper.pdf
submitted by xmrhaelan to CryptoCurrency [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]

what is this m i misguided.......

i thought bct bech32 address format is superior with its 128 bit security compare to hash160 based coins with 80 bit security........i concluded bch cashaddress "bitcoincash:q....................." is having 80 bits security.....where as btc native segwit address format "bc1q..........." is 128 bit secure since its base32......then i got this.....
https://news.bitcoin.com/bitcoin-cash-community-prepares-for-change-the-address-day/
i saw bch cashaddress is also bech32......plz help me understand what is correct and what is wrong.......
submitted by newbe567890 to btc [link] [comments]

Seneca Smart Contract Comparison

Seneca Smart Contract Comparison
https://preview.redd.it/6duhj3r1igi11.png?width=405&format=png&auto=webp&s=453e264b8b855b4cbe6e87c7abd607c7cacaea66

Which of these three smart contracts makes the most sense to you?

We wrote Seneca to be an evolution of software development. Those who already know some programming can reuse the concepts that they know to pick up this new idea of public code. Comparatively, languages such as Solidity and Bitcoin Script require extensive knowledge of blockchain and their limitations to use effectively.
For example, this is how you invoke a method on a smart contract in Ethereum:
0xa9059cbb00000000000000000000000071511814fc09ac85b9d5d0d995e78a48049644c5000000000000000000000000000000000000000000000001f0e0a209aad60000 
This payload can be broken up as the following components:
MethodID: 0xa9059cbb [0]: 00000000000000000000000071511814fc09ac85b9d5d0d995e78a48049644c5 [1]: 000000000000000000000000000000000000000000000001f0e0a209aad60000 
For the standard developer, how do you begin to understand what this means? How do you know what the MethodIDcorrelates to? What are the arguments? What are their values? The serialization mechanisms of Ethereum are insanely obtuse.
For Bitcoin Scripts, it's even better. Here is an example of the standard transaction Bitcoin Script (yes, believe it or not, every transaction is actually a smart contract on Bitcoin!):
76a962e907b15cbf27d5425399ebf6f0fb50ebb88f1888ac 
Which translates to the Script of:
OP_DUP OP_HASH160 62e907b15cbf27d5425399ebf6f0fb50ebb88f18 OP_EQUALVERIFY OP_CHECKSIG 
Compare these two methods to Seneca:
import tau tau.send('stu', 100) 
Check out Seneca on Github and let us know what you think!
Telegram (ENG|CHN|NL)

submitted by lamden to lamden [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 https://blockchain.info/tx/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:
https://wiki.unsystem.net/en/index.php/DarkWallet/Stealth
http://sx.dyne.org/stealth.html
submitted by therealtacotime to Bitcoin [link] [comments]

Deep Analysis Of Qtum's Account Abstraction Layer (Qtum AAL)

Analysis of Qtum Account Abstraction Layer (AAL) Implementation
https://mp.weixin.qq.com/s?__biz=MzI2MzM2NDQ2NA==&mid=2247485993&idx=1&sn=57ad353fd13b10ab85b62d693f86b1f5&chksm=eabc4036ddcbc9208ea766274defc543a9238967c5d2c541e615906a25a2962d75c4c6bd2c2b&scene=21#wechat_redirect
Qtum is designed with a bitcoin UTXO-based account model and implements a smart contract that supports the EVM specification, which is done through the Account Abstract Layer (ALA). AAL adapts the UTXO account to the EVM contract account, so that the AAL can use the UTXO transaction output to create a smart contract on the chain, send the transaction to the contract account to trigger the execution of the contract, and the AAL will eventually execute after the execution. The results were processed and adapted to UTXO. Thanks to the AAL, contract developers don't need to care about the UTXO transformation details related to contract operations, they can use the features of EVM to develop and are compatible with existing Ethereum smart contracts. This paper first analyzes the working process of AAL by interpreting the implementation code from UTXO transaction to smart contract execution.
 
1. UTMO transaction added script opcode
Qtum has added three opcodes OP_CREATE, OP_CALL and OP_SPEND for UTXO trading scripts to provide operational support for conversion between UTXO and EVM account models. These opcodes are defined in the opcodetype enumeration type:
 
Enum opcodetype{
......
OP_CREATE = 0xc1,
OP_CALL = 0xc2,
OP_SPEND= 0xc3,
......
}
 
These three opcodes have the following effects:
OP_CREATE is used to create smart contracts;
OP_CALL is used for the execution of the contract;
OP_SPEND is used for the cost of the contract balance.
In order to identify and process the transactions controlled by these opcodes during the block generation process, the HasCreateOrCall() and HasOpSpend() functions are added to the class CTransaction for UTXO model transactions for use in the mempool in the new block. The transaction is processed and the corresponding processing is added to the EvalScript() function of the script opcode parsing.
 
2. Conversion of UTXO transactions to EVM model transactions
When generating new blocks, in addition to regular parameter legality, consensus rules, DDOS attack checks, etc. for UTXO transactions, it is also necessary to use the opcode check function HasCreateOrCall() to determine whether the transaction output contains OP_CREATE or OP_CALL, which respectively correspond to EVM needs to perform contract creation or contract calls. This section has the following processing:
 
2.1 Performing account parameter extraction for EVM model
The contract uses the data, gasPrice, gasLimit, and VM version parameters in the execution of the EVM. These parameters are sent by the RPC call sendtocontract. The sendtocontract generates a UTXO transaction and uses the OP_CALL opcode in the transaction output. Will be broadcast to the blockchain network. The adaptation from UTXO to EVM in AAL is implemented by the QtumTxConverter class, in which the member functions extractQtumTransactions() and parseEthTXParams() of the class complete the parameter extraction for all such UTXO transaction output. The code fragment is as follows:
 
Dev::Address receiveAddress;
Valtype vecAddr;
If (opcode == OP_CALL)
{
vecAddr = stack.back();
Stack.pop_back();
receiveAddress = dev::Address(vecAddr);
}
Valtype code(stack.back());
Stack.pop_back();
Uint64_t gasPrice = CScriptNum::vch_to_uint64(stack.back());
Stack.pop_back();
Uint64_t gasLimit = CScriptNum::vch_to_uint64(stack.back());
Stack.pop_back();
VersionVM version(CScriptNum::vch_to_uint64(stack.back()));
Stack.pop_back();
Return EthTransactionParams{version, dev::u256(gasLimit), dev::u256(gasPrice), code,
receiveAddress }
 
The above code first judges that if the opcode is OP_CALL, the contract with the address vecAddr has been created, so it is directly converted into the address of the EVM format receiveAddress, otherwise it is OP_CREATE, the corresponding contract is created, there is no such field, so no extraction is done. Next, the data, gasPrice, gasLimit, and VM version are extracted in turn, which are all essential parameters for the EVM to execute bytecode.
 
2.2 Transaction conversion of the EVM account model
Transaction conversion is done through the function createEthTX() of the QtumTxConverter class. The QtumTransaction type transaction is created using the parameters extracted in the previous step and the UTXO transaction output vout. Since QtumTransaction is derived from the dev::eth::Transaction class in EVM, the QtumTransaction class is supported by operations related to EVM execution.
 
QtumTransaction txEth;
If ( etp.receiveAddress == dev::Address() ) {
txEth = QtumTransaction(txBit.vout[nOut].nValue, etp.gasPrice, (etp.gasLimit *
Etp.gasPrice),
Etp.code, dev::u256(0));
}
Else{
txEth = QtumTransaction(txBit.vout[nOut].nValue, etp.gasPrice, (etp.gasLimit *
Etp.gasPrice),
etp.receiveAddress, etp.code, dev::u256(0));
}
Dev::Address sender(GetSenderAddress(txBit, view));
txEth.forceSender(sender);
txEth.setHashWith(uintToh256(txBit.GetHash()));
txEth.setNVout(nOut);
 
First, the code etp.receiveAddress == dev::Address() determines whether the contract is not in the EVM state and needs to be newly created or the contract already included in the EVM state. The only difference is the contract address. Then, the QtumTransaction() constructor completes some of the transaction parameter constructs, the next statement extracts the sender of the transaction, and then sets the transaction HASH. A UTXO transaction supports multiple inputs and outputs. Qtum's AAL design takes this into account, so AAL supports a transaction output containing UTXO accounts and contract accounts. The last set nOut indicates that the nOut output of the transaction is sent to the smart contract. , so this output will trigger contract execution. In this way, the transaction conversion is completed according to the EVM account model.
 
3. Contract execution and UTXO conversion of execution results
The execution of the contract changes state (managed by the QtumState class's instantiated object globalState). For the contract state, Qtum follows the EVM definition, so it is compatible with all EVM-compliant smart contracts. But the transfer of the account amount, Qtum made a UTXO conversion, which means that the smart contract and the ordinary UTXO model account can complete the interaction, which is an important part of AAL to achieve UTXO support smart contract. The following is a brief introduction to the conversion process of contract execution and status results.
 
3.1 Contract execution environment construction and contract execution
The execution of the contract is a critical step in the processing of the contract, directly affecting the state of the contract. The implementation of the EVM to the contract bytecode is implemented by the ByteCodeExec class. The main function is performByteCode(). The main process of this step is to use the transaction parameters extracted above to build the virtual machine execution environment, and then complete the execution of the contract, the code is as follows:
 
For(QtumTransaction& tx : txs){
Dev::eth::EnvInfo envInfo(BuildEVMEnvironment());
Std::unique_ptr
Se(dev::eth::ChainParams(dev::eth::genesisInfo(dev::eth::Network::HomesteadTest)).
createSealEngine());
If(!tx.isCreation() && !globalState->addressInUse(tx.receiveAddress())){
Dev::eth::ExecutionResult execRes;
execRes.excepted = dev::eth::TransactionException::Unknown;
Result.push_back(ResultExecute{execRes, dev::eth::TransactionReceipt(dev::h256(),
Dev::u256(), dev::eth::LogEntries()), CTransaction()});
Continue;
}
Result.push_back(globalState->execute(envInfo, *se.get(), tx, type, OnOpFunc()));
}
 
The first is to build a contract execution environment, which is done by BuildEVMEnvironment(). It can be seen that this execution environment is carried out for each independent transaction, so as to minimize the contract execution process of different transactions and avoid the cross-effects in the contract execution process. Then build a new sealEngine class, which is the EVM execution engine, which is done by the createSealEngine() function. In the middle, the possible state exceptions that occur are checked, and then globalState->execute() completes the execution of the contract. Here, the execution environment envInfo and the EVM execution engine se are used.
 
3.2 UTXO conversion of contract execution results
After the completion of the contract execution, the result is stored in vector result. The vector vector records the transfer relationship between EVM accounts generated by each contract execution. AAL completes the transfer from EVM account model to UTXO model by converting these transfers into UTXO transactions. Conversion of the transaction. This processing is implemented by the processingResults() function. The following is a code snippet.
 
ByteCodeExecResult resultBCE;
For(size_t i = 0; i < result.size(); i++){
If(result[i].execRes.excepted != dev::eth::TransactionException::None){
If(txs[i].value() > 0){
CMutableTransaction tx;
Tx.vin.push_back(CTxIn(h256Touint(txs[i].getHashWith()), txs[i].getNVout(), CScript() <<
OP_SPEND));
CScript script(CScript() << OP_DUP << OP_HASH160 << txs[i].sender().asBytes() <<
OP_EQUALVERIFY << OP_CHECKSIG);
Tx.vout.push_back(CTxOut(CAmount(txs[i].value()), script));
resultBCE.valueTransfers.push_back(CTransaction(tx));
}
} else {
resultBCE.usedFee += CAmount(result[i].execRes.gasUsed);
CAmount ref((txs[i].gas() - result[i].execRes.gasUsed) * txs[i].gasPrice());
If(ref > 0){
CScript script(CScript() << OP_DUP << OP_HASH160 << txs[i].sender().asBytes() <<
OP_EQUALVERIFY << OP_CHECKSIG);
resultBCE.refundOutputs.push_back(CTxOut(ref, script));
resultBCE.refundSender += ref;
}
} if(result[i].tx != CTransaction()){
resultBCE.valueTransfers.push_back(result[i].tx);
}}
 
First, the resultBCE variable of type ByteCodeExecResult is defined to save the result of the conversion. Use the opcode OP_SPEND to implement the transaction cost, because the UTXO of Bitcoin uses the private key signature to realize the balance after the transaction input is unlocked, and the EVM implementation involves the transfer between different accounts, so these need to be implemented by OP_SPEND Transfer to UTXO model trading conversion. If execRes.excepted is not None, ie the contract execution exception, the balance is returned to the contract caller. Otherwise, if there is no abnormality, the remaining gas after deducting the consumed gas is returned to the caller of the contract. For the transfer that occurs during contract execution, its UTXO transaction is stored in result[i].tx. Therefore, transactions between different UTXO accounts generated by this process of contract execution are stored in the valueTransfers vector, and eventually these transactions are included in the new block. At this point, the AAL module completes the conversion from EVM transactions to UTXO.
 
4. Summary
AAL assists in the creation, execution, and cost of contracts through the addition of UTXO script opcodes. Before the contract is created and executed, the conversion of the UTXO transaction to the EVM model transaction is required, and then the executed EVM execution environment and engine are used to complete the execution of the contract. AAL finally processed the results of the contract and adapted it from EVM to UTXO, thus implementing a UTXO-based smart contract. AAL makes Qtum compatible with EVM-compliant smart contracts, providing Dapp with a new base platform, while UTXO's advantages allow for advantages such as parallel processing and privacy.
 
Huaming
He is currently a Qtum core developer and researcher. He graduated from Huazhong University of Science and Technology and has a graduate degree from the Chinese Academy of Sciences. Prior to joining Qtum, he has been engaged in the development of algorithms and protocol stacks for many years of wireless networks (including 4G LTE and wireless ad hoc networks); since 2015, he has been in contact with blockchain technology and has participated in the first hackathon competition organized by Wanxiang Blockchain. .
submitted by thisthingismud to Qtum [link] [comments]

Qtum - Quantum Chain Design Document

Serialization: Qtum Foundation Design Document

Foreword
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**)**
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 (or OP_EXEC_ASSIGN)

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: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI 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 (or OP_TXHASH, OP_EXEC_SPEND)

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.

summary

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]

Qtum Quantum Chain Design Document -- Add RPC Calls (Seven)

Qtum original design document summary (7) -- Qtum added RPC call
https://mp.weixin.qq.com/s/JdJLxEIBjD255qey6ITO_g
Qtum's core program, qtumd, runs all core logic including validation and creation of blocks. However, to achieve interaction with qtumd, you need to rely on RPC (Remote Procedure Call). Through RPC, you can interact with qtumd from the outside to implement basic functions such as sending and receiving QTUM and obtaining blockchain information.
The initial version of the Qtum RPC call is compatible with Bitcoin. On this basis, because the Qtum blockchain is different from Bitcoin, and Qtum supports the smart contract function that Bitcoin does not have, it is necessary to add a new RPC or improve the existing RPC to achieve Qtum. Full interaction of nodes.
The following section captures the relevant original design documents (with Chinese translation) for the Qtum RPC call from the early Qtum development team (ps: QTUM<#> or QTUMCORE<#> in the document is the internal design document number):
 
QTUM-35: Add RPC call for off-chain contract execution
Description: In Ethereum there are some contract's that can be executed without needing to be on the blockchain. This is useful especially for retrieving the status and results from a contract, and will make no changes to the on-chain storage or state. We should Add an RPC call to cover this functionality
 
Callcontract [address] [data]
Returns/prints hex encoded return data
 
Task: Add an RPC (Remote Procedure Call) call to run under the chain Description: It is useful to have some contracts in Ethereum that are not working on the blockchain, especially when retrieving the status and results of contracts, and not changing the storage and status of the chain. We should add an RPC call to implement this functionality. Callcontract [address] [data] Return / print hexadecimal encoded return data
 
QTUMCORE-14: Add "callcontract" RPC call for off-chain computations
Description: There should be an RPC call that executes a contract without requiring interaction with the blockchain network, and thus without gas or other fees. Callcontract contract-address data (sender) This should execute the contract locally, and if the contract function returns data, it should be returned/printed by the RPC call. Sender is optional and does not require an owned vout (it can be any valid address)
Task: Add a "callcontract" RPC call for the calculation of the chain Description: There should be an RPC call that does not require interaction with the blockchain network to run the contract, so it does not require gas or other fees. The format is as follows: Callcontract contract-address data (sender) It can run the contract locally, and if the contract function returns data, the RPC call can return/print the data. The sender is optional and does not need to have vout (it can be any valid address).
The above two tasks add a callcontract RPC call interface to implement a local chain call contract, which is convenient for viewing contract status or obtaining contract results without changing any information on the chain.
 
QTUMCORE-7: Add "createcontract" RPC call
 
Description: A new RPC call should be added call "deploycontract" "createcontract". This RPC call will be used to deploy a new smart contract to the Qtum blockchain.
Syntax:
Deploycontract createcontract gas-price gas-limit bytecode [sender-address] [txfee] [broadcast]
If no address is specified, then it should be picked randomly from the wallet. If no outputs exist to spend using that sender-address, then an error should be shown and no transaction created.
Tsfee is optional and if not specified should use the same auto txfee as the rest of the wallet (for example sendtoaddress uses an auto txfee)
Broadcast should default to true. If broadcast is false, then the transaction is created and signed, and then printed to the screen in hex rather than broadcast to the network.
If the sender-address does have an output, but it is not enough to cover the gas costs and tx fees, then any UTXO owned by the wallet should be used by the transaction to cover those fees. (not all funds must come from sender -address, but the sender-address must be vin[0])
After execution, if broadcast is true, it should print the txid and the new contract address.
Task: Add "createcontract" RPC call
Description: Add a "createcontract" RPC call that will be used to deploy a new smart contract on the Qtum blockchain.
grammar:
Createcontract gas-price gas-limit bytecode [sender-address] [txfee] [broadcast]
Among them, sender-address (sender address) is optional. If no address is specified, an address will be randomly selected from the wallet. If there is no output available in the sender-address, an error will be displayed and the transaction will not be created.
Txfee (transaction fee) is optional. If not specified, it should use the same automatic txfee as the rest of the wallet (for example, the automatic txfee used by sendtoaddress)
Broadcast should be true by default. If broadcast is false, the transaction is created and signed, and will be printed to the screen in hexadecimal format instead of being broadcast to the network.
If the sender-address does have an output, but it does not cover the gas charges and transaction fees, then any UTXO owned by the wallet can be used by the transaction to pay for these charges. (Not all funds must come from sender-address, but sender-address must be vin[0])
After running, if broadcast is true, the transaction id and the new contract address are printed.
The above task adds the RPC call createcontract for creating and deploying new smart contracts, and describes the specific meaning of the parameters and their corresponding behavior.
 
QTUMCORE-13: Add "sendtocontract" RPC call
Description: An rpc call should be adding for sending data and (optionally) money to a contract that has been deployed on the blockchain.
The format should be:
Sendtocontract contract-address data (value gaslimit gasprice sender broadcast)
This should create a contract call transaction using OP_CALL.
Value defaults to 0.
If no address is specified, then it should be picked randomly from the wallet. If no outputs exist to spend using that sender-address, then an error should be shown and no transaction created.
Broadcast should default to true. If broadcast is false, then the transaction is created and signed, and then printed to the screen in hex rather than broadcast to the network.
If the sender-address does have an output, but it is not enough to cover the gas costs, tx fees, and value, then any UTXO owned by the wallet should be used by the transaction to cover the remainder. (not all funds must Come from sender-address, but the sender-address must be vin[0])
After execution, if broadcast is true, it should print the txid and the new contract address.
Task: Add "sendtocontract" RPC call
Description: In order to send data or funds to a contract already deployed on the blockchain, an RPC call should be added.
The format should be:
Sendtocontract contract-address data (value gaslimit gasprice sender broadcast)
You can use OP_CALL to create a contract call transaction.
Value defaults to 0.
The sender-address is optional. If no address is specified, an address will be randomly selected from the wallet. If there are no outputs available in the sender-address, an error will be displayed and no transaction will be created.
Broadcast is default to true. If broadcast is false, then the transaction is created and signed and then printed to the screen in hexadecimal format instead of being broadcast to the network.
If the sender-address does have an output, but the output is not sufficient to cover the gas fee, transaction cost, and value, then any UTXO owned by the wallet can be traded to pay the remaining fee. (Not all funds must come from sender-address, but sender-address must be vin[0])
After running, if broadcast is true, the transaction id and the new contract address should be printed.
In order to implement the contract on the chain, the above task adds a sendtocontract RPC call. Its functionality is similar to callcontract and can be used to run contracts. The biggest difference is that sendtocontract implements the chain call, which requires the cost of the Gas, and the running result needs to be verified by the entire network node, and will change the storage state on the contract chain.
 
QTUMCORE-81:create getTransactionReceipt rpc call
Description: We need to create getTransactionReceipt rpc call that returns the same values ​​as here:
https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethgettransactionreceipt
Most important part is the logs. they can either be stored into a separate db or use one of the existing tx or eth related db.
Task: Create getTransactionReceipt RPC call
Description: We need to create a getTransactionReceipt RPC call that returns the same value as in the following link:
https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethgettransactionreceipt
The most important part is the log. They can be stored in a separate database, or they can use existing transactions or Ethereum-related databases.
The above task adds a gettransactionreceipt RPC call to the smart contract log to get the contract transaction related logs, which is very useful for understanding the status of smart contracts.
 
QTUMCORE-90: add searchlogs rpc call
Description: we need to add an rpc call to allow us to search the eth event logs, we need to support similar parameters as eth:
https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethfilter
So it would be: searchlogs(fromBlock, toBlock, address, topics)
fromBlock, toBlock should support latest keyword
Adderss: optional should be an array of one or more addresses
Topics: optional (check the link above)
Unlike eth where you have to call watch, this method should just output the filtered logs
Task: Add searchlogs RPC call
Description: We need to add a PRC call that allows searching for smart contract event logs, and we need to support parameters similar to Ethereum:
https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethfilter
So its form is as follows: searchlogs(fromBlock, toBlock, address, topics)
fromBlock: toBlock should support the latest keywords
Address: an optional array of one or more addresses
Topics: optional (refer to the link above)
Unlike the Ethereum, which needs to call watch, this method only outputs the filtered log.
The above task adds an RPC for retrieving the smart contract event log to facilitate screening of event logs that satisfy the condition. Users can quickly get the contract status they care about.
 
QTUMCORE-92: add getcode and getstorageat rpc calls
Description: We need to implement Qtum equivalent of these 2 rpc calls:
https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethgetcode
https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethgetstorageat
No need to implement callback function for now.
For the default block, we can use block number, or keyword "latest" (default)
Task: Add getcode and getstorageat RPC calls
Description: We need to implement the QTP version of the RPC call equivalent to the following two RPCs:
https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethgetcode
https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethgetstorageat
There is currently no need to implement a callback function.
For the default block, we can use the block number, or the keyword "latest" (default)
The above task implements an equivalent RPC similar to Ethereum for obtaining contract code and storing information.
 
QTUMCORE-97: Change validation of contract rpc calls inputs
Description: Change validation of contract rpc calls inputs to accept only hex
Task: Modify the verification of the input value of the contract RPC call
Description: Modify the validation of the input value of the contract RPC call to accept only hexadecimal.
The above task stipulates that the RPC of the verification contract only accepts the hexadecimal data parameters, so that the rpc interface is as consistent as possible.
 
QTUMCORE-123: Add "excepted": to gettransactionreceipt
Description: We need to add the "excepted": field to gettransactionreceipt rpc call which lists "None" if no exception occured, or lists the actual exception that happened.
The same lessons is in callcontract call.
We need the change to be backward compatible, which means it should not break the current logs db, but people who want to see exceptions would have to recreate/reindex the logs db
Task: Add "excepted": field in gettransactionreceipt
Description: We need to add the "excepted": field to the gettransactionreceipt RPC call. If no exception occurs, it will display "None", otherwise it will list the actual exception.
The same is true for Callcontract calls.
We need to modify it to be forward compatible, which means it can't break the current log database, but if you want to see these exceptions, you must rebuild/reindex the log database.
The above tasks enable a number of RPCs associated with smart contracts to throw exceptions that are convenient for the user to understand the wrong running state of the contract and also help developers debug the code.
 
QTUMCORE-124:Add "changeToSender" to sendtoaddress and make sure the "Don't use change address" option also affects sendtoaddress
Description: We need to add "changeToSender" parameter to sendtoaddress rpc call, same as we did for sendtocontract.
Also we need to make sure the "Don't use change address" also affects sendtoaddress
Task: Add "changeToSender" to sendtoaddress and make sure the "Don't use change address" option is also valid for sendtoaddress
Description: We need to add the "changeToSender" parameter to the sendtoaddress RPC call, which is also added to the sendtocontract.
We also need to make sure that the "Don't use change address" option is also valid for sendtoaddress.
Due to the UTXO model, the change of the contract call is easy to confuse the user. Therefore, the above task adds the option of "do not use the change address" for the sendtoaddressRPC, from which the user can choose to return to the original address.
 
QTUMCORE-125: Add callcontract support to "createrawtransaction" rpc call
Description: As requested by some exchanges, which use "createrawtransaction" to create raw transactions before signing on a cold wallet, we need to add
1- raw contract data support to "createrawtransaction" rpc call.
Currently "createrawtransaction" supports two types of outputs in the outputs arguments:
First is "address": x.xxx which created a standard P2PKH output
The second is "data": "hex" which creates an OP_RETURN output
We need to add:
1- "callcontract":
{contractAddress:"address", data:"data", amount:"amount", gasLimit:"gaslimit", gasPrice:"gasPrice"}
Where:
contractAddress: a valid contract address (valid hash160 hex data)
Data: the hex data to add in the OP_CALL output (should validate it's hex data, you can check the validation done in sendtocontract)
Amount (optional): the value of the output (value in QTUM to send with the call), should be a valid amount, default 0
gasLimit (optional): the gas limit for the transaction (same as in sendtocontract), defaults to the default/DGP value
GasPrice (optional): the gas price for the transaction (same as in sendtocontract), defaults to the default/DGP value
After parsing and validation all the values ​​an OP_CALL output should be constructed
Similar to this:
CScript scriptPubKey = CScript() << CScriptNum(VersionVM::GetEVMDefault().toRaw()) << CScriptNum(nGasLimit) << CScriptNum(nGasPrice) << ParseHex(datahex) << ParseHex(contractaddress) << OP_CALL;
Task: Make the "createrawtransaction" RPC call support callcontract
Description: Before some transactions are signed on the cold wallet, use "createrawtransaction" to create the original transaction. At the request of these exchanges, we should add:
1 -- original contract data support for "createrawtransaction" RPC calls
Currently, for the outputs parameter, "createrawtransaction" supports two types of outputs:
The first type is "address": x.xxx, which creates a standard P2PKH output
The second type is "data": "hexadecimal", creating an OP_RETURN output
We need to add:
1 -- "callcontract":
{contractAddress:"address", data:"data", amount:"amount", gasLimit:"gaslimit", gasPrice:"gasPrice"}
among them,
contractAddress: a valid contract address (valid hash 160 hex data)
Data: hexadecimal data added in OP_CALL output (should be verified as hexadecimal data, you can check if it is verified in sendtocontract)
Amount (optional): The value of output (the value in QTUM, sent with this call), should be a valid value, the default is 0
gasLimit (optional): the gas limit of the transaction (same as sendtocontract), the default is the default/DGP value
gasPrice (optional): the gas price of the transaction (same as sendtocontract), defaults to the default/DGP value
After parsing and verifying all the values, you should build an OP_CALL output.
The build method is similar to the following:
CScript scriptPubKey = CScript() << CScriptNum(VersionVM::GetEVMDefault().toRaw()) << CScriptNum(nGasLimit) << CScriptNum(nGasPrice) << ParseHex(datahex) << ParseHex(contractaddress) << OP_CALL;
Prior to the above task, the createrawtransaction RPC call was consistent with Bitcoin and could only be used to send standard transactions. Qtum extends it to compatible contract transactions. From then on, the RPC can be used to create original contract transactions for developers or exchanges.
Summary
The RPC call is the most important way to interact with the qtumd core program. It provides a call interface for getting all kinds of information on the blockchain and local. It is the basis for many applications such as wallets, browsers, and exchanges. A good RPC interface design enables developers to get more accurate information and develop more feature-rich applications. Qtum provides developers with sophisticated RPC calls, making it possible for many third-party applications, such as predicting market projects, Bodhi.
submitted by thisthingismud to Qtum [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:
https://github.com/OpenAssets/open-assets-protocol/blob/mastespecification.mediawiki
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:
https://github.com/OpenAssets/open-assets-protocol/blob/masteaddress-format.mediawiki
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
==Abstract==
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.
==Motivation==
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
infrastructure.
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
characteristics:
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:

18E14A7B6A307F426A94F8114701E7C8E774E7F9A47E2C2035DB29A206321725.

He calculates the corresponding address:

16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM.

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

address: OP_DUP OP_HASH160
010966776006953D5567439E5E39F86A0D273BEE OP_EQUALVERIFY
OP_CHECKSIG.

The script is hashed: 36e0ea8e93eaa0285d641305f4c81e563aa570a2

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

using version byte 23:
ALn3aK1fSuG27N96UGYB1kUYUpGKRhBuBC.
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
[https://en.bitcoin.it/wiki/Protocol_specification#Variable_length_integer
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
[http://en.wikipedia.org/wiki/LEB128 LEB128-encoded] unsigned integers
representing the asset quantity of every output in order (excluding
the marker output). || Variable
|-
! Metadata length || The
[https://en.bitcoin.it/wiki/Protocol_specification#Variable_length_integer
var-integer] encoded length of the metadata field. || 1-9
bytes
|-
! 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 [http://en.wikipedia.org/wiki/LEB128 LEB128] encoding (also
used in [https://developers.google.com/protocol-buffers/docs/encoding#varints
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
units.
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.
====Example====
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]...
original: https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2016-May/012741.html
submitted by dev_list_bot to bitcoin_devlist [link] [comments]

Economic majority vote by splitting coins | Tier Nolan | Aug 20 2015

Tier Nolan on Aug 20 2015:
The economic majority is defined as the will of those who actually use
Bitcoin as a payment system.
No matter what the miners want, if users and merchants refuse to accept
their fork, then the fork loses and cannot be considered the "true" bitcoin
fork.
The problem is that it is easy to measure a miner vote. The economic
majority is not so easy.
The relative value of two forks could be compared by adding a system
similar colored coins.
These contracts could be added with a soft fork like the P2SH one.
OP_IF
 OP_DROP OP_DROP OP_HASH160 
OP_EQUAL
OP_ENDIF
OP_IF
 OP_DROP OP_HASH160 OP_EQUAL 
OP_ENDIF
This works like P2SH and is template matching. You can have as many
entries as you want.
In the example, the output can be spent on fork 1 and fork 2 by the owner
of and can be spent on fork 3 by the owner of .
Until the deadline, the value on each fork must be preserved when spending
the output. If you provide the key(s), you are allowed to consolidate
entries. You can also consolidate multiple outputs to the same key even if
you don't have the key.
This means that split outputs are a little more hassle to use and the
transactions are larger. This doesn't matter much, since measuring the
relative value of the two sub-coins only requires some of them to be traded.
If someone wants to propose a hard fork, they create a new fork id and
deadline and release software that implements the hard fork at the given
deadline (no miner vote needed).
To prevent spam, there could be a cost to create a fork-id (BTC paid to
OP_RETURN) and the deadline could have a max time in the future (say 2
years).
After the deadline, core will allow conversion of outputs that pay to the
core fork-id (probably 1) to be converted into unencumbered outputs by the
person with the core-id script. Likewise, the fork software will allow
outputs that pay to the fork id to be converted. Legacy bitcoin that
haven't been "split" will be spendable on both sides equally.
This means that users can convert x legacy bitcoin into x fork-bitcoins and
x core-bitcoins in advance of the fork.
This means that Exchanges could support trading between the two. The side
that trades with the most value is the one that is supported by the
economic majority.
As it becomes clear which side is going to win, the price of coins on the
losing side should drop. It is unlikely that the two would stay at exactly
the same value without one side winning.
Users who want to to use the losing rules are free to do so but the
economic majority will have made its decision.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.linuxfoundation.org/pipermail/bitcoin-dev/attachments/20150820/4e500973/attachment.html>
original: http://lists.linuxfoundation.org/pipermail/bitcoin-dev/2015-August/010501.html
submitted by bitcoin-devlist-bot to bitcoin_devlist [link] [comments]

Segregated Witness features wish list | jl2012 at xbt.hk | Dec 10 2015

jl2012 at xbt.hk on Dec 10 2015:
It seems the current consensus is to implement Segregated Witness. SW
opens many new possibilities but we need a balance between new features
and deployment time frame. I'm listing by my priority:
1-2 are about scalability and have highest priority
  1. Witness size limit: with SW we should allow a bigger overall block
size. It seems 2MB is considered to be safe for many people. However,
the exact size and growth of block size should be determined based on
testing and reasonable projection.
  1. Deployment time frame: I prefer as soon as possible, even if none of
the following new features are implemented. This is not only a technical
issue but also a response to the community which has been waiting for a
scaling solution for years
3-6 promote safety and reduce level of trust (higher priority)
  1. SIGHASH_WITHINPUTVALUE [1]: there are many SIGHASH proposals but this
one has the highest priority as it makes offline signing much easier.
  1. Sum of fee, sigopcount, size etc as part of the witness hash tree:
for compact proof of violations in these parameters. I prefer to have
this feature in SWv1. Otherwise, that would become an ugly softfork in
SWv2 as we need to maintain one more hash tree
  1. Height and position of an input as part of witness will allow compact
proof of non-existing UTXO. We need this eventually. If it is not done
in SWv1, we could softfork it nicely in SWv2. I prefer this earlier as
this is the last puzzle for compact fraud proof.
  1. BIP62 and OP_IF malleability fix [2] as standardness rules:
involuntary malleability may still be a problem in the relay network and
may make the relay less efficient (need more research)
7-15 are new features and long-term goals (lower priority)
  1. Enable OP_CAT etc:
OP_CAT will allow tree signatures described by [3]. Even without Schnorr
signature, m-of-n multisig will become more efficient if m < n.
OP_SUBSTOP_LEFT/OP_RIGHT will allow people to shorten a payment
address, while sacrificing security.
I'm not sure how those disabled bitwise logic codes could be useful
Multiplication and division may still considered to be risky and not
very useful?
  1. Schnorr signature: for very efficient multisig [3] but could be
introduced later.
  1. Per-input lock-time and relative lock-time: define lock-time and
relative lock-time in witness, and signed by user. BIP68 is not a very
ideal solution due to limited lock time length and resolution
  1. OP_PUSHLOCKTIME and OP_PUSHRELATIVELOCKTIME: push the lock-time and
relative lock-time to stack. Will allow more flexibility than OP_CLTV
and OP_CSV
  1. OP_RETURNTURE which allows softfork of any new OP codes [4]. It is
not really necessary with the version byte design but with OP_RETURNTURE
we don't need to pump the version byte too frequently.
  1. OP_EVAL (BIP12), which enables Merkleized Abstract Syntax Trees
(MAST) with OP_CAT [5]. This will also obsolete BIP16. Further
restrictions should be made to make it safe [6]:
a) We may allow at most one OP_EVAL in the scriptPubKey
b) Not allow any OP_EVAL in the serialized script, nor anywhere else in
the witness (therefore not Turing-complete)
c) In order to maintain the ability to statically analyze scripts, the
serialized script must be the last push of the witness (or script
fails), and OP_EVAL must be the last OP code in the scriptPubKey
  1. Combo OP codes for more compact scripts, for example:
OP_MERKLEHASH160, if executed, is equivalent to OP_SWAP OP_IF OP_SWAP
OP_ENDIF OP_CAT OP_HASH160 [3]. Allowing more compact tree-signature and
MAST scripts.
OP_DUPTOALTSTACK, OP_DUPFROMALTSTACK: copy to / from alt stack without
removing the item
  1. UTXO commitment: good but not in near future
  2. Starting as a softfork, moving to a hardfork? SW Softfork is a quick
but dirty solution. I believe a hardfork is unavoidable in the future,
as the 1MB limit has to be increased someday. If we could plan it ahead,
we could have a much cleaner SW hardfork in the future, with codes
pre-announced for 2 years.
[1] https://bitcointalk.org/index.php?topic=181734.0
[2]
https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2015-Novembe011679.html
[3] https://blockstream.com/2015/08/24/treesignatures/
[4] https://bitcointalk.org/index.php?topic=1106586.0
[5]
https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2015-Septembe010977.html
[6] https://bitcointalk.org/index.php?topic=58579.msg690093#msg690093
original: http://lists.linuxfoundation.org/pipermail/bitcoin-dev/2015-Decembe011935.html
submitted by dev_list_bot to bitcoin_devlist [link] [comments]

[uncensored-r/BitcoinMarkets] Bitcoin Tech Rant - Happy New Year: Atomic Cross Chain Swaps

The following post by L14dy is being replicated because some comments within the post(but not the post itself) have been silently removed.
The original post can be found(in censored form) at this link:
np.reddit.com/ BitcoinMarkets/comments/7n5dwi
The original post's content was as follows:
Hola,
I didnt have much success with the last Tech Rant, so I decided to do another. Please provide feedback.
So the topic for this tech rant is Cross Chain Swaps. They’re pretty simple, but require a bit of understanding of Bitcoin Script. I will start off with on-chain swaps.
So, let’s assume I want to swap testnet BTC for mainnet BTC with you (for instance if someone wants millions of testnet coins and is willing to pay 0.01 BTC for them). How would you be able to pay me and ensure that you actually get the testnet coins? Well, the easiest way is for us to agree that u/jaderadej will be our escrow. We both trust him, so we he generates an address and provides this address to the both of us. We then each generate a new address and provide it to u/jaderadej. At this point we both send our coins to the address he generated. One tx on testnet and the other on mainnet. As soon as u/jaderadej receives the coins from both of us, he does the swap (minus his “fee”). If I send coins but you dont, then he sends them back to me. If you send coins but I dont, then he sends them back to you.
Now, this works fine as long as we both trust u/jaderadej, and we do, but what if the only person willing to do it is u/pineconecandle. Well, I dont trust u/pineconecandle ;), so why would I do this deal? I wouldn’t. Hence, we need to do it without a third party. And this is possible in Bitcoin.
The first thing you need to understand is how OP_IF works. Basically OP_IF allows you to create a conditional branch of your PubKey Script. The second thing you need to udnerstand is how OP_CLTV works: OP_CLTV stands for Check Lock-Time Verify. It is an OP_Code that accepts an integer as input, which is either interpreted as a unix timestamp or as a block number (there is a convention on when the integer is interpreted as which, you can google it if you care). So now we can create a PubKey Script on a UTXO that has one PubKeyScript branch OP_IF OP_CLTV {Script1} OP_ELSE {Script2}
Ok, so enough with the preliminaries. On to the actual protocol.
I have testnet coins and you want to buy them. So what you do is you generate a random byte string (some random sequence of bits with enough entropy to ensure I cant brute force it before the lock-time we agree upon is up. If you use a cryptographically strong random number generator that will be fine. You generate this random number and hash it, i.e. OP_SHA256 or OP_RIPEMD160, whichever of the two is fine. Usually you would SHA.
I generate an address and provide you with the hash of my public key.
You then also generate a new address and send both the hash and the new hash of the public key to me. You now spend you 0.01 BTC to an output with a PubKey Script like the one above where Script 1 is just a normal P2PKH for your new address and Script 2 is a simple pre-image check combined with a P2PKH for my address, i.e. first hash the first element in the SigScript, compare that it matches the commitment value for the hash and finally check the standard P2PKH Script, i.e. soemthing like
{Script1}: OP_DUP OP_HASH160 OP_EQUALVERIFY OP_CHECKSIG
{Script2}: OP_SHA256 OP_EQUALVERIFY OP_DUP OP_HASH160 OP_EQUALVERIFY OP_CHECKSIG
Now, eventually I will see this transaction show up on the mainnet blockchain. Since you are the one looking to buy from me, you pony up the cash. Now, if I change my mind and walk away your coins are not gone. Once the lock-time is up, you can just use you knowledge of the private key to your address to create a SigScript that satisfies Script 1 above. So far no trust needed... you will NOT lose your coins.
Ok, but I want to sell my testnet coins, so I decide to Pony up the testnet coins. I spend them to an output with the same PubKeyScript, only that I reverse the roles of our public key hashes AND more importantly, I cut the lock-time in half. Since you have the hash, I want to make sure I get my coins back before you can take your BTC back, otherwise you could take both.
So now I spend to that and you see it show up on the testnet blockchain. If you decide to walk away, thats fine. I can just get my testnet coins back in half the time you can. Again, no trust needed. Why? Well, even though you know the secret random number, since you dont control the private key associated to my address, you wont be able to satisfy the pubKey Script to take your BTC back and you cant take my testnet coins without revealing the secret random number in the SigScript of the spending transaction. Since all SigScripts are public information, you cant spend my testnet coins if you want to keep the random number secret.
Let’s assume we went through all this hassle to actually do the deal. So, now you spend the testnet coins to a new address that you control (P2PKH) by revealing the random number and providing a SigScript for the address you control in the OP_ELSE branch of the PubKeyScript.
As soon as you do that, I see the random number, and I can now spend your 0.01 BTC to an address I control using the Secret Random Number You revealed to me, along with the SigScript for the P2PKH of the address I control.
And voila. We just exchanges testnet BTC for mainnet BTC in a trustless fashion with no trusted third party using some pretty simple Cryptographic primitives. Done deal.
Now, notice a few things:
  1. You need to wait a bunch of confs before this can be done, because you want to avoid double spending of your counterparty (whom you do not trust)
  2. Tetsnet is kinda a stupid example, because its pretty easy to reorg the chain. I just didn’t wanna mention another coin.
  3. In Lightning this can be done instantly. No need to wait for confs and no need to wait too long for lock-times to expire. Basically it is achieved by routing the payment to yourself on the Lightning Network. You can also combine on-chain swaps with off-chain swaps. Pretty cool stuff. This is basically how decentralized exchanges would work on Lightning.
Ok, done. Hope you like it!
submitted by censorship_notifier to noncensored_bitcoin [link] [comments]

Relative CHECKLOCKTIMEVERIFY (was CLTV proposal) | Matt Corallo | Mar 16 2015

Matt Corallo on Mar 16 2015:
In building some CLTV-based contracts, it is often also useful to have a
method of requiring, instead of locktime-is-at-least-N,
locktime-is-at-least-N-plus-the-height-of-my-input. ie you could imagine
an OP_RELATIVECHECKLOCKTIMEVERIFY that reads (does not pop) the top
stack element, adds the height of the output being spent and then has
identical semantics to CLTV.
A slightly different API (and different name) was described by maaku at
http://www.reddit.com/Bitcoin/comments/2z2l91/time_to_lobby_bitcoins_core_devs_sf_bitcoin_devs/cpgc154
which does a better job of saving softfork-available opcode space.
There are two major drawbacks to adding such an operation, however.
1) More transaction information is exposed inside the script (prior to
CLTV we only had the sigchecking operation exposed, with a CLTV and
RCLTV/OP_CHECK_MATURITY_VERIFY we expose two more functions).
2) Bitcoin Core's mempool invariant of "all transactions in the mempool
could be thrown into one overside block and aside from block size, it
would be valid" becomes harder to enforce. Currently, during reorgs,
coinbase spends need checked (specifically, anything spending THE
coinbase 100 blocks ago needs checked) and locktime transactions need
checked. With such a new operation, any script which used this new
opcode during its execution would need to be re-evaluated during reorgs.
I think both of these requirements are reasonable and not particularly
cumbersome, and the value of such an operation is quite nice for some
protocols (including settings setting up a contest interval in a
sidechain data validation operation).
Thoughts?
Matt
On 10/01/14 13:08, Peter Todd wrote:
I've written a reference implementation and BIP draft for a new opcode,
CHECKLOCKTIMEVERIFY. The BIP, reproduced below, can be found at:
https://github.com/petertodd/bips/blob/checklocktimeverify/bip-checklocktimeverify.mediawiki
The reference implementation, including a full-set of unittests for the
opcode semantics can be found at:
https://github.com/petertodd/bitcoin/compare/checklocktimeverify

BIP:
Title: OP_CHECKLOCKTIMEVERIFY
Author: Peter Todd <pete at petertodd.org>
Status: Draft
Type: Standards Track
Created: 2014-10-01

==Abstract==
This BIP describes a new opcode (OP_CHECKLOCKTIMEVERIFY) for the Bitcoin
scripting system that allows a transaction output to be made unspendable until
some point in the future.
==Summary==
CHECKLOCKTIMEVERIFY re-defines the existing NOP2 opcode. When executed it
compares the top item on the stack to the nLockTime field of the transaction
containing the scriptSig. If that top stack item is greater than the transation
nLockTime the script fails immediately, otherwise script evaluation continues
as though a NOP was executed.
The nLockTime field in a transaction prevents the transaction from being mined
until either a certain block height, or block time, has been reached. By
comparing the argument to CHECKLOCKTIMEVERIFY against the nLockTime field, we
indirectly verify that the desired block height or block time has been reached;
until that block height or block time has been reached the transaction output
remains unspendable.
==Motivation==
The nLockTime field in transactions makes it possible to prove that a
transaction output can be spent in the future: a valid signature for a
transaction with the desired nLockTime can be constructed, proving that it is
possible to spend the output with that signature when the nLockTime is reached.
An example where this technique is used is in micro-payment channels, where the
nLockTime field proves that should the receiver vanish the sender is guaranteed
to get all their escrowed funds back when the nLockTime is reached.
However the nLockTime field is insufficient if you wish to prove that
transaction output ''can-not'' be spent until some time in the future, as there
is no way to prove that the secret keys corresponding to the pubkeys controling
the funds have not been used to create a valid signature.
===Escrow===
If Alice and Bob jointly operate a business they may want to
ensure that all funds are kept in 2-of-2 multisig transaction outputs that
require the co-operation of both parties to spend. However, they recognise that
in exceptional circumstances such as either party getting "hit by a bus" they
need a backup plan to retrieve the funds. So they appoint their lawyer, Lenny,
to act as a third-party.
With a standard 2-of-3 CHECKMULTISIG at any time Lenny could conspire with
either Alice or Bob to steal the funds illegitimately. Equally Lenny may prefer
not to have immediate access to the funds to discourage bad actors from
attempting to get the secret keys from him by force.
However with CHECKLOCKTIMEVERIFY the funds can be stored in scriptPubKeys of
the form:
IF  CHECKLOCKTIMEVERIFY DROP  CHECKSIGVERIFY 1 ELSE 2 ENDIF   2 CHECKMULTISIG 
At any time the funds can be spent with the following scriptSig:
  0 
After 3 months have passed Lenny and one of either Alice or Bob can spend the
funds with the following scriptSig:
  1 
===Non-interactive time-locked refunds===
There exist a number of protocols where a transaction output is created that
the co-operation of both parties to spend the output. To ensure the failure of
one party does not result in the funds becoming lost refund transactions are
setup in advance using nLockTime. These refund transactions need to be created
interactively, and additionaly, are currently vulnerable to transaction
mutability. CHECKLOCKTIMEVERIFY can be used in these protocols, replacing the
interactive setup with a non-interactive setup, and additionally, making
transaction mutability a non-issue.
====Two-factor wallets====
Services like GreenAddress store Bitcoins with 2-of-2 multisig scriptPubKey's
such that one keypair is controlled by the user, and the other keypair is
controlled by the service. To spend funds the user uses locally installed
wallet software that generates one of the required signatures, and then uses a
2nd-factor authentication method to authorize the service to create the second
SIGHASH_NONE signature that is locked until some time in the future and sends
the user that signature for storage. If the user needs to spend their funds and
the service is not available, they wait until the nLockTime expires.
The problem is there exist numerous occasions the user will not have a valid
signature for some or all of their transaction outputs. With
CHECKLOCKTIMEVERIFY rather than creating refund signatures on demand
scriptPubKeys of the following form are used instead:
IF  CHECKSIGVERIFY ELSE  CHECKLOCKTIMEVERIFY DROP ENDIF  CHECKSIG 
Now the user is always able to spend their funds without the co-operation of
the service by waiting for the expiry time to be reached.
====Micropayment Channels====
Jeremy Spilman style micropayment channels first setup a deposit controlled by
2-of-2 multisig, tx1, and then adjust a second transaction, tx2, that spends
the output of tx1 to payor and payee. Prior to publishing tx1 a refund
transaction is created, tx3, to ensure that should the payee vanish the payor
can get their deposit back. The process by which the refund transaction is
created is currently vulnerable to transaction mutability attacks, and
additionally, requires the payor to store the refund. Using the same
scriptPubKey from as in the Two-factor wallets example solves both these issues.
===Trustless Payments for Publishing Data===
The PayPub protocol makes it possible to pay for information in a trustless way
by first proving that an encrypted file contains the desired data, and secondly
crafting scriptPubKeys used for payment such that spending them reveals the
encryption keys to the data. However the existing implementation has a
significant flaw: the publisher can delay the release of the keys indefinitely.
This problem can be solved interactively with the refund transaction technique;
with CHECKLOCKTIMEVERIFY the problem can be non-interactively solved using
scriptPubKeys of the following form:
IF HASH160  EQUALVERIFY  CHECKSIG ELSE  CHECKLOCKTIMEVERIFY DROP  CHECKSIG ENDIF 
The buyer of the data is now making a secure offer with an expiry time. If the
publisher fails to accept the offer before the expiry time is reached the buyer
can cancel the offer by spending the output.
===Proving sacrifice to miners' fees===
Proving the sacrifice of some limited resource is a common technique in a
variety of cryptographic protocols. Proving sacrifices of coins to mining fees
has been proposed as a ''universal public good'' to which the sacrifice could
be directed, rather than simply destroying the coins. However doing so is
non-trivial, and even the best existing technqiue - announce-commit sacrifices
create outputs that are provably spendable by anyone (thus to mining fees
assuming miners behave optimally and rationally) but only at a time
sufficiently far into the future that large miners profitably can't sell the
sacrifices at a discount.
===Replacing the nLockTime field entirely===
As an aside, note how if the SignatureHash() algorithm could optionally cover
part of the scriptSig the signature could require that the scriptSig contain
CHECKLOCKTIMEVERIFY opcodes, and additionally, require that they be executed.
(the CODESEPARATOR opcode came very close to making this possible in v0.1 of
Bitcoin) This per-signature capability could replace the per-transaction
nLockTime field entirely as a valid signature would now be the proof that a
transaction output ''can'' be spent.
==Detailed Specification==
Refer to the reference implementation, reproduced below, for the precise
semantics and detailed rationale for those semantics.
case OP_NOP2: { // CHECKLOCKTIMEVERIFY // // (nLockTime -- nLockTime ) if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) break; // not enabled; treat as a NOP if (stack.size() < 1) return false; // Note that elsewhere numeric opcodes are limited to // operands in the range -2**31+1 to 2**31-1, however it is // legal for opcodes to produce results exceeding that // range. This limitation is implemented by CScriptNum's // default 4-byte limit. // // If we kept to that limit we'd have a year 2038 problem, // even though the nLockTime field in transactions // themselves is uint32 which only becomes meaningless // after the year 2106. // // Thus as a special case we tell CScriptNum to accept up // to 5-byte bignums, which are good until 2**32-1, the // same limit as the nLockTime field itself. const CScriptNum nLockTime(stacktop(-1), 5); // In the rare event that the argument may be < 0 due to // some arithmetic being done first, you can always use // 0 MAX CHECKLOCKTIMEVERIFY. if (nLockTime < 0) return false; // There are two times of nLockTime: lock-by-blockheight // and lock-by-blocktime, distinguished by whether // nLockTime < LOCKTIME_THRESHOLD. // // We want to compare apples to apples, so fail the script // unless the type of nLockTime being tested is the same as // the nLockTime in the transaction. if (!( (txTo.nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) || (txTo.nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD) )) return false; // Now that we know we're comparing apples-to-apples, the // comparison is a simple numeric one. if (nLockTime > (int64_t)txTo.nLockTime) return false; // Finally the nLockTime feature can be disabled and thus // CHECKLOCKTIMEVERIFY bypassed if every txin has been // finalized by setting nSequence to maxint. The // transaction would be allowed into the blockchain, making // the opcode ineffective. // // Testing if this vin is not final is sufficient to // prevent this condition. Alternatively we could test all // inputs, but testing just this input minimizes the data // required to prove correct CHECKLOCKTIMEVERIFY execution. if (txTo.vin[nIn].IsFinal()) return false; break; } 
https://github.com/petertodd/bitcoin/commit/ab0f54f38e08ee1e50ff72f801680ee84d0f1bf4
==Upgrade and Testing Plan==
TBD
==Credits==
Thanks goes to Gregory Maxwell for suggesting that the argument be compared
against the per-transaction nLockTime, rather than the current block height and
time.
==References==
PayPub - https://github.com/unsystem/paypub
Jeremy Spilman Micropayment Channels - http://www.mail-archive.com/bitcoin-development%40lists.sourceforge.net/msg02028.html
==Copyright==
This document is placed in the public domain.
Meet PCI DSS 3.0 Compliance Requirements with EventLog Analyzer
Achieve PCI DSS 3.0 Compliant Status with Out-of-the-box PCI DSS Reports
Are you Audit-Ready for PCI DSS 3.0 Compliance? Download White paper
Comply to PCI DSS 3.0 Requirement 10 and 11.5 with EventLog Analyzer
http://pubads.g.doubleclick.net/gampad/clk?id=154622311&iu=/4140/ostg.clktrk
Bitcoin-development mailing list
Bitcoin-development at lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/bitcoin-development
original: http://lists.linuxfoundation.org/pipermail/bitcoin-dev/2015-March/007714.html
submitted by bitcoin-devlist-bot to bitcoin_devlist [link] [comments]

HashFlare Ethereum mining 2016 Base58Check to Hash160 conversion with Python Blockchain New Unconfirmed Transaction Hack Script UPDATE 2020 Bitcoin: ScriptSig And ScriptPubKey Terminology - Part11 10 Convert Bitcoin address to Hash160 address

Getting Hash160 bitcoin address in python . Getting Hash160 bitcoin address in python. 0 votes. I'm trying to figure out, how transactions work in bitcoin. When I choose inputs for a new tx I want to make sure they belong to a specific address. However, existing txs do not specify previous outputs' addresses, but instead they contain address's hash. e.g.: >> bx fetch-tx ... YFI Reclaims Support Post Coinbase Listing, New All-Time Highs In Sight News BTC Bitcoin Analysis March 8, 2018 March 14, 2018 Your Ultimate Bitcoin and Cryptocurrency Resource site and How to Make Money with Bitcoin by Trading and Mining this Online Digital Currency. I have all 150GB Bitcoin blocks now what? How to open them and read them in Python? I need to extract all used hash160 so far. I tried to open them with Berkeley DB but no success it seems these files aren't Berkeley DB and what is the difference between blkxxxxx.dat and revxxxxx.dat files anyway? it seems revxxxxx.dat files got some improvement in file size Detailed information about bitcoin transaction 274d51c18b86e4b77d367c0a74e260a64215dff73ad0f6b89b27803959bf7473.

[index] [43729] [34051] [14129] [37379] [34464] [13275] [20701] [50844] [22568] [28544]

HashFlare Ethereum mining 2016

Hye, Friend's Welcome To Bitcoin Script. Blockchain New #Unconfirmed Transaction Hack Script (#Earn_Bitcoin) #2020 Bitcoin #Hack #4BTC Download the script use the *Script Buy Here (1) ... In this video, we go over the terminology needed to understand scriptsig and scriptpubkey. We go over public key, private key, public key hash, public address, digital signature and hash160. Commands: $ sudo apt-get update $ sudo apt-get -y upgrade $ sudo apt-get install -y python3-pip $ sudo apt-get install build-essential libssl-dev libffi-dev python-dev $ sudo apt-get install -y ... #bitcoin #twitter #crypto #interest #stockmarket #recession #bearmarket #bullmarket #davincij15 #mmcrypto #btc #bitcoinprice #bitcointoday #crash #economy #inflation #ecb #fed #federalreserve # ... Copy bitcoin receiver address and paste on alert box and press ENTER. 7. On Unconfirmed Transactions address copy Hash 160 key and paste on alert box and press ENTER.

#