From 70345d7c9ccc03a5d083c61eab2962074fe9a363 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20V=C3=ADtor?= Date: Thu, 31 May 2018 06:20:14 -0300 Subject: [PATCH 01/12] micropayment channel example with two chapters --- docs/solidity-by-example.rst | 340 ++++++++++++++++++++++++++++++++++- 1 file changed, 339 insertions(+), 1 deletion(-) diff --git a/docs/solidity-by-example.rst b/docs/solidity-by-example.rst index 2b3d4b484..870415c7d 100644 --- a/docs/solidity-by-example.rst +++ b/docs/solidity-by-example.rst @@ -645,4 +645,342 @@ Safe Remote Purchase Micropayment Channel ******************** -To be written. +Creating and verifying signatures +================================= + +Signatures are used to authorize transactions, and they're a general tool that's available to smart contracts. In this chapter we'll use it to prove to a smart contract that a certain account approved a certain message. We'll build a simple smart contract that lets me transmit ether, but in a unsual way, instead of calling a function myself to initiate a payment, I'll let the receiver of the payment do that, and therefore pay the transaction fee. All this using cryptographics signatures that I'll make and send off-chain (e.g. via email). We'll call our contract as ReceiverPays, it will works a lot like writing a check. Our contract will works like that: + + 1. The owner deploys ReceiverPays, attaching enough ether to cover the payments that will be made. + 2. The owner authorizes a payment by signing a message with their private key. + 3. The owner sends the cryptographically signed message to the designated recipient. The message does not need to be kept secret (you'll understand it later), and the mechanism for sending it doesn't matter. + 4. The recipient claims their payment by presenting the signed message to the smart contract, it verifies the authenticity of the message and then releases the funds. + +Creating the signature +---------------------- + +We don't need the to interact with Ethereum network to do that. The proccess is completely offline, and the every major programming language has the libraries to do it. The signature algorithm Ethereum has the support for is the `Elliptic Curve Signature Algorithm(EDCSA) `_. In this tutorial, we'll signing messages in the web browser using web3.js and MetaMask. We can sign messages in too many ways, but some of them are incompatible. We'll use the new standard way to do that `EIP-762 `_, it provides a number of other security benefits. Is recommended to stick with the most standard format of signing, as specified by the `eth_sign JSON-RPC method `_ In MetaMask, this algorithm is followed best by the web3.js function `web3.personal.sign`, doing it using: + +:: + + // Hashing first makes a few things easier + var hash = web3.sha3("message to sign"); + web3.personal.sign(hash, web3.eth.defaultAccount, function () {...}); + +:: + +Remind that the prefix includes the length of the message. Hashing first means the message will always be 32 bytes long, which means the prefix is always the same, this makes everything easier. + +What to Sign +------------ + +For a contract that fulfills payments, the signed message must include: + + 1. The recipient's address + 2. The amount to be transferred + 3. An additional data to protects agains replay attacks + +To avoid replay attacks we'll use the same as in Ethereum transactions themselves, a nonce. And our smart contract will check if that nonce is reused. + +:: + + mapping(uint256 => bool) usedNonces; + + function claimPayment(uint256 amount, uint256 nonce, bytes signature) public { + require(!usedNonces[nonce]); + usedNonces[nonce] = true; + + // ... + } + +:: + +There's another type of replay attacks, it occurs when the owner deploy a ReceiverPays smart contract, make some payments, and then destroy the contract. Later, he decide to deploy the RecipientPays smart contract again, but the new contract doesn't know the nonces used in the previous deployment, so the attacker can use the old messages again. We can protect agains it including the contract's address in our message, and only accepting the messages containing contract's address itself. + +Packing arguments +----------------- + +Now that we have identified what information to include in the signed message, we're ready to put the message together, hash it, and sign it. Solidity's `keccak256/sha3 function `_ hashes by first concatenating them in a tightly packed form. For the hash generated on the client match the one generated in the smart contract, the arguments must be concatenated in the same way. The [ethereumjs-aby]() library provides a function called `soliditySHA3` that mimics the behavior of Solidity's `keccak256` function. Putting it all together, here's a JavaScript function that creates the proper signature for the `ReceiverPays` example: + +:: + + // recipient is the address that should be paid. + // amount, in wei, specifies how much ether should be sent. + // nonce can be any unique number, do you remind the replay attacks? we are preventing them here + // contractAddress do you remind the cross-contract replay attacks? + function signPayment(recipient, amount, nonce, contractAddress, callback) { + var hash = "0x" + ethereumjs.ABI.soliditySHA3( + ["address", "uint256", "uint256", "address"], + [recipient, amount, nonce, contractAddress] + ).toString("hex"); + + web3.personal.sign(hash, web3.eth.defaultAccount, callback); + } + +:: + +Recovering the Message Signer in Solidity +----------------------------------------- + +In general, ECDSA signatures consist of two parameters, *r* and *s*. Signatures in Ethereum include a thir parameter *v*, that can be used to recover which account's private key was used to sign in the message, the transaction's sender. Solidity provides a built-in function `ecrecover `_ that accepts a message along with the *r*, *s* and *v* parameters and returns the address that was used to sign the message. + +Extracting the Signature Parameters +----------------------------------- + +Signatures produced by web3.js are the concatenation of *r*, *s* and *v*, so the 1st step is sppliting those parameters back out. It can be done on the client, but doing it inside the smart contract means only one signature parameter needs to be sent rather than three. Sppliting apart a bytes array into component parts is a little messy. We'll use the `inline assembly `_ to do the job: + +:: + + function splitSignature(bytes sig) + internal + pure + returns (uint8, bytes32, bytes32) + { + require(sig.length == 65); + + bytes32 r; + bytes32 s; + uint8 v; + + assembly { + // first 32 bytes, after the length prefix + r := mload(add(sig, 32)) + // second 32 bytes + s := mload(add(sig, 64)) + // final byte (first byte of the next 32 bytes) + v := byte(0, mload(add(sig, 96))) + } + return (v, r, s); + } + +:: + +Here's a brief explanation of the code: + + * Dynamically-sized arrays are represented in a memory by a 32-byte length followed by the actual data. The code here starts reading data at byte 32 to skip past that length. The `require` at the top of the function ensures the signature is the correct length. + * *r* and *s* are 32 bytes each and together make up the first 64 bytes of the signature. + * *v* is the 65th byte, which can be found at byte offset 96 (32 bytes for the length, 64 bytes for *r* and *s*). The `mload` opcode loads 32 bytes at a time, so the function then needs to extract just the first byte of the word that was read. This is what `byte(0, ...)` does. + +Computing the Message Hash +-------------------------- + +The smart contract needs to know exactly what parameters were signed, and so it must recreate the message from the parameters and use that for signature verification: + +:: + + // builds a prefixed hash to mimic the behavior of eth_sign. + function prefixed(bytes32 hash) internal pure returns(bytes32) { + return keccak256("\x19Ethereum Signed Message:\n32", hash); + } + + function claimPayment(uint256 amount, uint256 nonce, bytes sig) public { + require(!usedNonces[nonce]); + usedNonces[nonce] = true; + + // this recreates the message that was signed on the client. + bytes32 message = prefixed(keccak256(msg.sender, amount, nonce, this)); + + require(recoverSigner(message, sig) == owner); + + msg.sender.transfer(amount); + } + +:: + +Our implementation of `recoverSigner`: + +:: + + function recoverSigner(bytes32 message, bytes sig) + internal + pure + returns (address) + { + uint8 v; + bytes32 r; + bytes32 s; + + (v, r, s) = splitSignature(sig); + + return ecrecover(message, v, r, s); + } + +:: + +Writing a Simple Payment Channel +================================ + +We'll build a simple, but complete, implementation of a payment channel. Payment channels use cryptographic signatures to make repeated transfers of ether securely, instantaneously, and without transaction fees. but... + +What is a Payment Channel? +-------------------------- + +Payment channels allow participants to make repeated transfers of ether without using transactions. This means that the delays and fees associated with transactions can be avoided. We're going to explore a simple unidirectional payment channel between two parties. Using it involves three steps: + + 1. The sender funds a smart contract with ether. This "opens" the payment channel. + 2. The sender signs messages that specify how much of that ether is owed to the recipient. This step is repeated for each payment. + 3. The recipient "closes" the payment channel, withdrawing their portion of the ether and sending the remainder back to the sender. + +A note: only steps 1 and 3 require Ethereum transactions, the step 2 means that the sender a cryptographic signature to the recipient via off chain ways (e.g. email). This means only two transactions are required to support any number of transfers. + +The recipient is guaranteed to receive their funds because the smart contract escrows the ether and honors a valid signed message. The smart contract also enforces a timeout, so the sender is guaranteed to eventually recover their funds even if the recipient refuses to close the channel. It's up to the participants in a payment channel to decide how long to keep it open. For a short-lived transaction, such as paying an internet cafe for each minute of network access, or for a longer relationship, such as paying an employee an hourly wage, a payment could last for months or years. + +Opening the Payment Channel +--------------------------- + +To open the payment channel, the sender deploys the smart contract, attaching the ether to be escrowed and specifying the intendend recipient and a maximum duration for the channel to exist. + +:: + + contract SimplePaymentChannel { + address public sender; // The account sending payments. + address public recipient; // The account receiving the payments. + uint256 public expiration; // Timeout in case the recipient never closes. + + function SimplePaymentChannel(address _recipient, uint256 duration) + public + payable + { + sender = msg.sender; + recipient = _recipient; + expiration = now + duration; + } + } + +:: + +Making Payments +--------------- + +The sender makes payments by sending messages to the recipient. This step is performed entirely outside of the Ethereum network. Messages are cryptographically signed by the sender and then transmitted directly to the recipient. + +Each message includes the following information: + + * The smart contract's address, used to prevent cross-contract replay attacks. + * The total amount of ether that is owed the recipient so far. + +A payment channel is closed just once, at the of a series of transfers. Because of this, only one of the messages sent will be redeemed. This is why each message specifies a cumulative total amount of ether owed, rather than the amount of the individual micropayment. The recipient will naturally choose to redeem the most recent message because that's the one with the highest total. We don't need anymore the nonce per-message, because the smart contract will only honor a single message. The address of the smart contract is still used to prevent a message intended for one payment channel from being used for a different channel. + +Here's the modified code to cryptographic a message from the previous chapter: + +:: + + function constructPaymentMessage(contractAddress, amount) { + return ethereumjs.ABI.soliditySHA3( + ["address", "uint256"], + [contractAddress, amount] + ); + } + + function signMessage(message, callback) { + web3.personal.sign( + "0x" + message.toString("hex"), + web3.eth.defaultAccount, + callback + ); + } + + // contractAddress is used to prevent cross-contract replay attacks. + // amount, in wei, specifies how much ether should be sent. + + function signPayment(contractAddress, amount, callback) { + var message = constructPaymentMessage(contractAddress, amount); + signMessage(message, callback); + } + +:: + +Verifying Payments +------------------ + +Unlike in our previous chapter, messages in a payment channel aren't redeemed right away. The recipient keeps track of the latest message and redeems it when it's time to close the payment channel. This means it's critical that the recipient perform their own verification of each message. Otherwise there is no guarantee that the recipient will be able to get paid +in the end. + +The recipient should verify each message using the following process: + + 1. Verify that the contact address in the message matches the payment channel. + 2. Verify that the new total is the expected amount. + 3. Verify that the new total does not exceed the amount of ether escrowed. + 4. Verify that the signature is valid and comes from the payment channel sender. + +We'll use the `ethereumjs-util `_ library to write this verifications. The following code borrows the `constructMessage` function from the signing code above: + +:: + + // this mimics the prefixing behavior of the eth_sign JSON-RPC method. + function prefixed(hash) { + return ethereumjs.ABI.soliditySHA3( + ["string", "bytes32"], + ["\x19Ethereum Signed Message:\n32", hash] + ); + } + + function recoverSigner(message, signature) { + var split = ethereumjs.Util.fromRpcSig(signature); + var publicKey = ethereumjs.Util.ecrecover(message, split.v, split.r, split.s); + var signer = ethereumjs.Util.pubToAddress(publicKey).toString("hex"); + return signer; + } + + function isValidSignature(contractAddress, amount, signature, expectedSigner) { + var message = prefixed(constructPaymentMessage(contractAddress, amount)); + var signer = recoverSigner(message, signature); + return signer.toLowerCase() == + ethereumjs.Util.stripHexPrefix(expectedSigner).toLowerCase(); + } + +:: + +Closing the Payment Channel +--------------------------- + +When the recipient is ready to receive their funds, it's time to close the payment channel by calling a *close* function on the smart contract. Closing the channel pays the recipient the ether they're owed and destroys the contract, sending any remaining ether back to the sender. To close the channel, the recipient needs to share a message signed by the sender. + +The smart contract must verify that the message contains a valid signature from the sender. The process for doing this verification is the same as the process the recipient uses. The Solidity functions *isValidSignature* and *recoverSigner* work just like their JavaScript counterparts in the previous section. The latter is borrowed from the *ReceiverPays* contract in the previous chapter. + +:: + + function isValidSignature(uint256 amount, bytes signature) + internal + view + returns (bool) + { + bytes32 message = prefixed(keccak256(this, amount)); + + // check that the signature is from the payment sender. + return recoverSigner(message, signature) == sender; + } + + // the recipient can close the channel at any time by presentating a signed + // amount from the sender. The recipient will be sent that amount, + // and the reaminder will go back to the sender. + function close(uint256 amount, bytes signature) public { + require(msg.sender == recipient); + require(isValidSignature(amount, signature)); + + recipient.transafer(amount); + selfdesctruct(sender); + } + +:: + +The *close* function can only be called by the payment channel recipient, who will naturally pass the most recent payment message because that message carries the highest total owed. If the sender were allowed to call this function, they could provide a message with a lower amount and cheat the recipient out of what they're owed. + +The function verifies the signed message matches the given parameters. If everything checks out, the recipient is sent their portion of the ether, and the sender is sent the rest via a *selfdesctruct*. + +Channel Expriration +------------------- + +The recipient can close the payment channel at any time, but if they fail to do so, the sender needs a way to recover their escrowed funds. An *expiration* time was set at the time of contract deployment. Once that time is reached, the sender can call *claimTimeout* to recover their funds. + +:: + + // if the timeout is reached without the recipient closing the channel then, + // the ether is released back to the sender. + function claimTimeout() public { + require(now >= expiration); + selfdestruct(sender); + } + +:: + +After this function is called, the recipient can no longer receive any ether, so it's important that the recipient close the channel before the expiration is reached. From 61454f574a0371b4c56f3d82b3bd62dc951f925a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20V=C3=ADtor?= Date: Thu, 31 May 2018 11:03:42 -0300 Subject: [PATCH 02/12] split long lines --- docs/solidity-by-example.rst | 154 +++++++++++++++++++++++++++++------ 1 file changed, 129 insertions(+), 25 deletions(-) diff --git a/docs/solidity-by-example.rst b/docs/solidity-by-example.rst index 870415c7d..558f35398 100644 --- a/docs/solidity-by-example.rst +++ b/docs/solidity-by-example.rst @@ -648,17 +648,42 @@ Micropayment Channel Creating and verifying signatures ================================= -Signatures are used to authorize transactions, and they're a general tool that's available to smart contracts. In this chapter we'll use it to prove to a smart contract that a certain account approved a certain message. We'll build a simple smart contract that lets me transmit ether, but in a unsual way, instead of calling a function myself to initiate a payment, I'll let the receiver of the payment do that, and therefore pay the transaction fee. All this using cryptographics signatures that I'll make and send off-chain (e.g. via email). We'll call our contract as ReceiverPays, it will works a lot like writing a check. Our contract will works like that: +Signatures are used to authorize transactions, +and they're a general tool that's available to +smart contracts. In this chapter we'll use it to +prove to a smart contract that a certain account +approved a certain message. We'll build a simple +smart contract that lets me transmit ether, but +in a unsual way, instead of calling a function myself +to initiate a payment, I'll let the receiver of +the payment do that, and therefore pay the transaction +fee. All this using cryptographics signatures that I'll +make and send off-chain (e.g. via email). We'll call our +contract as ReceiverPays, it will works a lot like +writing a check.Our contract will works like that: 1. The owner deploys ReceiverPays, attaching enough ether to cover the payments that will be made. 2. The owner authorizes a payment by signing a message with their private key. 3. The owner sends the cryptographically signed message to the designated recipient. The message does not need to be kept secret (you'll understand it later), and the mechanism for sending it doesn't matter. 4. The recipient claims their payment by presenting the signed message to the smart contract, it verifies the authenticity of the message and then releases the funds. - + Creating the signature ---------------------- -We don't need the to interact with Ethereum network to do that. The proccess is completely offline, and the every major programming language has the libraries to do it. The signature algorithm Ethereum has the support for is the `Elliptic Curve Signature Algorithm(EDCSA) `_. In this tutorial, we'll signing messages in the web browser using web3.js and MetaMask. We can sign messages in too many ways, but some of them are incompatible. We'll use the new standard way to do that `EIP-762 `_, it provides a number of other security benefits. Is recommended to stick with the most standard format of signing, as specified by the `eth_sign JSON-RPC method `_ In MetaMask, this algorithm is followed best by the web3.js function `web3.personal.sign`, doing it using: +We don't need the to interact with Ethereum network to +do that. The proccess is completely offline, and the +every major programming language has the libraries to do it. +The signature algorithm Ethereum has the support for is the +`Elliptic Curve Signature Algorithm(EDCSA) `_. +In this tutorial, we'll signing messages in the web browser +using web3.js and MetaMask. We can sign messages in too many ways, +but some of them are incompatible. We'll use the new standard +way to do that `EIP-762 `_, +it provides a number of other security benefits. +Is recommended to stick with the most standard format of signing, +as specified by the `eth_sign JSON-RPC method `_ +In MetaMask, this algorithm is followed best by the web3.js function `web3.personal.sign`, +doing it using: :: @@ -668,7 +693,9 @@ We don't need the to interact with Ethereum network to do that. The proccess is :: -Remind that the prefix includes the length of the message. Hashing first means the message will always be 32 bytes long, which means the prefix is always the same, this makes everything easier. +Remind that the prefix includes the length of the message. +Hashing first means the message will always be 32 bytes long, +which means the prefix is always the same, this makes everything easier. What to Sign ------------ @@ -679,7 +706,8 @@ For a contract that fulfills payments, the signed message must include: 2. The amount to be transferred 3. An additional data to protects agains replay attacks -To avoid replay attacks we'll use the same as in Ethereum transactions themselves, a nonce. And our smart contract will check if that nonce is reused. +To avoid replay attacks we'll use the same as in Ethereum transactions +themselves, a nonce. And our smart contract will check if that nonce is reused. :: @@ -694,12 +722,29 @@ To avoid replay attacks we'll use the same as in Ethereum transactions themselve :: -There's another type of replay attacks, it occurs when the owner deploy a ReceiverPays smart contract, make some payments, and then destroy the contract. Later, he decide to deploy the RecipientPays smart contract again, but the new contract doesn't know the nonces used in the previous deployment, so the attacker can use the old messages again. We can protect agains it including the contract's address in our message, and only accepting the messages containing contract's address itself. +There's another type of replay attacks, it occurs when the +owner deploy a ReceiverPays smart contract, make some payments, +and then destroy the contract. Later, he decide to deploy the +RecipientPays smart contract again, but the new contract doesn't +know the nonces used in the previous deployment, so the attacker +can use the old messages again. We can protect agains it including +the contract's address in our message, and only accepting the +messages containing contract's address itself. Packing arguments ----------------- -Now that we have identified what information to include in the signed message, we're ready to put the message together, hash it, and sign it. Solidity's `keccak256/sha3 function `_ hashes by first concatenating them in a tightly packed form. For the hash generated on the client match the one generated in the smart contract, the arguments must be concatenated in the same way. The [ethereumjs-aby]() library provides a function called `soliditySHA3` that mimics the behavior of Solidity's `keccak256` function. Putting it all together, here's a JavaScript function that creates the proper signature for the `ReceiverPays` example: +Now that we have identified what information to include in the +signed message, we're ready to put the message together, hash it, +and sign it. Solidity's `keccak256/sha3 function `_ +hashes by first concatenating them in a tightly packed form. +For the hash generated on the client match the one generated in the smart contract, +the arguments must be concatenated in the same way. The +`ethereumjs-abi `_ library provides +a function called `soliditySHA3` that mimics the behavior +of Solidity's `keccak256` function. +Putting it all together, here's a JavaScript function that +creates the proper signature for the `ReceiverPays` example: :: @@ -721,12 +766,22 @@ Now that we have identified what information to include in the signed message, w Recovering the Message Signer in Solidity ----------------------------------------- -In general, ECDSA signatures consist of two parameters, *r* and *s*. Signatures in Ethereum include a thir parameter *v*, that can be used to recover which account's private key was used to sign in the message, the transaction's sender. Solidity provides a built-in function `ecrecover `_ that accepts a message along with the *r*, *s* and *v* parameters and returns the address that was used to sign the message. +In general, ECDSA signatures consist of two parameters, *r* and *s*. +Signatures in Ethereum include a thir parameter *v*, that can be used +to recover which account's private key was used to sign in the message, +the transaction's sender. Solidity provides a built-in function `ecrecover `_ +that accepts a message along with the *r*, *s* and *v* parameters and +returns the address that was used to sign the message. Extracting the Signature Parameters ----------------------------------- -Signatures produced by web3.js are the concatenation of *r*, *s* and *v*, so the 1st step is sppliting those parameters back out. It can be done on the client, but doing it inside the smart contract means only one signature parameter needs to be sent rather than three. Sppliting apart a bytes array into component parts is a little messy. We'll use the `inline assembly `_ to do the job: +Signatures produced by web3.js are the concatenation of *r*, *s* and *v*, +so the 1st step is sppliting those parameters back out. It can be done on the client, +but doing it inside the smart contract means only one signature parameter +needs to be sent rather than three. +Sppliting apart a bytes array into component parts is a little messy. +We'll use the `inline assembly `_ to do the job: :: @@ -763,7 +818,9 @@ Here's a brief explanation of the code: Computing the Message Hash -------------------------- -The smart contract needs to know exactly what parameters were signed, and so it must recreate the message from the parameters and use that for signature verification: +The smart contract needs to know exactly what parameters were signed, +and so it must recreate the message from the parameters and use that +for signature verification: :: @@ -809,25 +866,40 @@ Our implementation of `recoverSigner`: Writing a Simple Payment Channel ================================ -We'll build a simple, but complete, implementation of a payment channel. Payment channels use cryptographic signatures to make repeated transfers of ether securely, instantaneously, and without transaction fees. but... +We'll build a simple, but complete, implementation of a payment channel. +Payment channels use cryptographic signatures to make repeated transfers +of ether securely, instantaneously, and without transaction fees. but... What is a Payment Channel? -------------------------- -Payment channels allow participants to make repeated transfers of ether without using transactions. This means that the delays and fees associated with transactions can be avoided. We're going to explore a simple unidirectional payment channel between two parties. Using it involves three steps: +Payment channels allow participants to make repeated transfers of ether without +using transactions. This means that the delays and fees associated with transactions +can be avoided. We're going to explore a simple unidirectional payment channel between +two parties. Using it involves three steps: 1. The sender funds a smart contract with ether. This "opens" the payment channel. 2. The sender signs messages that specify how much of that ether is owed to the recipient. This step is repeated for each payment. 3. The recipient "closes" the payment channel, withdrawing their portion of the ether and sending the remainder back to the sender. -A note: only steps 1 and 3 require Ethereum transactions, the step 2 means that the sender a cryptographic signature to the recipient via off chain ways (e.g. email). This means only two transactions are required to support any number of transfers. +A note: only steps 1 and 3 require Ethereum transactions, the step 2 means that +the sender a cryptographic signature to the recipient via off chain ways (e.g. email). +This means only two transactions are required to support any number of transfers. -The recipient is guaranteed to receive their funds because the smart contract escrows the ether and honors a valid signed message. The smart contract also enforces a timeout, so the sender is guaranteed to eventually recover their funds even if the recipient refuses to close the channel. It's up to the participants in a payment channel to decide how long to keep it open. For a short-lived transaction, such as paying an internet cafe for each minute of network access, or for a longer relationship, such as paying an employee an hourly wage, a payment could last for months or years. +The recipient is guaranteed to receive their funds because the smart contract escrows +the ether and honors a valid signed message. The smart contract also enforces a timeout, +so the sender is guaranteed to eventually recover their funds even if the recipient refuses +to close the channel. +It's up to the participants in a payment channel to decide how long to keep it open. +For a short-lived transaction, such as paying an internet cafe for each minute of network access, +or for a longer relationship, such as paying an employee an hourly wage, a payment could last for months or years. Opening the Payment Channel --------------------------- -To open the payment channel, the sender deploys the smart contract, attaching the ether to be escrowed and specifying the intendend recipient and a maximum duration for the channel to exist. +To open the payment channel, the sender deploys the smart contract, +attaching the ether to be escrowed and specifying the intendend recipient +and a maximum duration for the channel to exist. :: @@ -851,14 +923,23 @@ To open the payment channel, the sender deploys the smart contract, attaching th Making Payments --------------- -The sender makes payments by sending messages to the recipient. This step is performed entirely outside of the Ethereum network. Messages are cryptographically signed by the sender and then transmitted directly to the recipient. +The sender makes payments by sending messages to the recipient. +This step is performed entirely outside of the Ethereum network. +Messages are cryptographically signed by the sender and then transmitted directly to the recipient. Each message includes the following information: * The smart contract's address, used to prevent cross-contract replay attacks. * The total amount of ether that is owed the recipient so far. -A payment channel is closed just once, at the of a series of transfers. Because of this, only one of the messages sent will be redeemed. This is why each message specifies a cumulative total amount of ether owed, rather than the amount of the individual micropayment. The recipient will naturally choose to redeem the most recent message because that's the one with the highest total. We don't need anymore the nonce per-message, because the smart contract will only honor a single message. The address of the smart contract is still used to prevent a message intended for one payment channel from being used for a different channel. +A payment channel is closed just once, at the of a series of transfers. +Because of this, only one of the messages sent will be redeemed. This is why +each message specifies a cumulative total amount of ether owed, rather than the +amount of the individual micropayment. The recipient will naturally choose to +redeem the most recent message because that's the one with the highest total. +We don't need anymore the nonce per-message, because the smart contract will +only honor a single message. The address of the smart contract is still used +to prevent a message intended for one payment channel from being used for a different channel. Here's the modified code to cryptographic a message from the previous chapter: @@ -892,7 +973,11 @@ Here's the modified code to cryptographic a message from the previous chapter: Verifying Payments ------------------ -Unlike in our previous chapter, messages in a payment channel aren't redeemed right away. The recipient keeps track of the latest message and redeems it when it's time to close the payment channel. This means it's critical that the recipient perform their own verification of each message. Otherwise there is no guarantee that the recipient will be able to get paid +Unlike in our previous chapter, messages in a payment channel aren't +redeemed right away. The recipient keeps track of the latest message and +redeems it when it's time to close the payment channel. This means it's +critical that the recipient perform their own verification of each message. +Otherwise there is no guarantee that the recipient will be able to get paid in the end. The recipient should verify each message using the following process: @@ -902,7 +987,9 @@ The recipient should verify each message using the following process: 3. Verify that the new total does not exceed the amount of ether escrowed. 4. Verify that the signature is valid and comes from the payment channel sender. -We'll use the `ethereumjs-util `_ library to write this verifications. The following code borrows the `constructMessage` function from the signing code above: +We'll use the `ethereumjs-util `_ +library to write this verifications. +The following code borrows the `constructMessage` function from the signing code above: :: @@ -933,9 +1020,17 @@ We'll use the `ethereumjs-util `_ Closing the Payment Channel --------------------------- -When the recipient is ready to receive their funds, it's time to close the payment channel by calling a *close* function on the smart contract. Closing the channel pays the recipient the ether they're owed and destroys the contract, sending any remaining ether back to the sender. To close the channel, the recipient needs to share a message signed by the sender. +When the recipient is ready to receive their funds, it's time to +close the payment channel by calling a *close* function on the smart contract. +Closing the channel pays the recipient the ether they're owed and destroys the contract, +sending any remaining ether back to the sender. +To close the channel, the recipient needs to share a message signed by the sender. -The smart contract must verify that the message contains a valid signature from the sender. The process for doing this verification is the same as the process the recipient uses. The Solidity functions *isValidSignature* and *recoverSigner* work just like their JavaScript counterparts in the previous section. The latter is borrowed from the *ReceiverPays* contract in the previous chapter. +The smart contract must verify that the message contains a valid signature from the sender. +The process for doing this verification is the same as the process the recipient uses. +The Solidity functions *isValidSignature* and *recoverSigner* work just like their +JavaScript counterparts in the previous section. The latter is borrowed from the +*ReceiverPays* contract in the previous chapter. :: @@ -963,14 +1058,22 @@ The smart contract must verify that the message contains a valid signature from :: -The *close* function can only be called by the payment channel recipient, who will naturally pass the most recent payment message because that message carries the highest total owed. If the sender were allowed to call this function, they could provide a message with a lower amount and cheat the recipient out of what they're owed. +The *close* function can only be called by the payment channel recipient, +who will naturally pass the most recent payment message because that message +carries the highest total owed. If the sender were allowed to call this function, +they could provide a message with a lower amount and cheat the recipient out of what they're owed. -The function verifies the signed message matches the given parameters. If everything checks out, the recipient is sent their portion of the ether, and the sender is sent the rest via a *selfdesctruct*. +The function verifies the signed message matches the given parameters. +If everything checks out, the recipient is sent their portion of the ether, +and the sender is sent the rest via a *selfdesctruct*. Channel Expriration ------------------- -The recipient can close the payment channel at any time, but if they fail to do so, the sender needs a way to recover their escrowed funds. An *expiration* time was set at the time of contract deployment. Once that time is reached, the sender can call *claimTimeout* to recover their funds. +The recipient can close the payment channel at any time, but if they fail to do so, +the sender needs a way to recover their escrowed funds. An *expiration* time was set +at the time of contract deployment. Once that time is reached, the sender can call +*claimTimeout* to recover their funds. :: @@ -983,4 +1086,5 @@ The recipient can close the payment channel at any time, but if they fail to do :: -After this function is called, the recipient can no longer receive any ether, so it's important that the recipient close the channel before the expiration is reached. +After this function is called, the recipient can no longer receive any ether, +so it's important that the recipient close the channel before the expiration is reached. From 1dca223e7713459d0588f4ab605b7e25f23b0127 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20V=C3=ADtor?= Date: Thu, 31 May 2018 11:13:14 -0300 Subject: [PATCH 03/12] fix code syntax --- docs/solidity-by-example.rst | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/docs/solidity-by-example.rst b/docs/solidity-by-example.rst index 558f35398..3b6b4cb91 100644 --- a/docs/solidity-by-example.rst +++ b/docs/solidity-by-example.rst @@ -691,7 +691,6 @@ doing it using: var hash = web3.sha3("message to sign"); web3.personal.sign(hash, web3.eth.defaultAccount, function () {...}); -:: Remind that the prefix includes the length of the message. Hashing first means the message will always be 32 bytes long, @@ -720,7 +719,6 @@ themselves, a nonce. And our smart contract will check if that nonce is reused. // ... } -:: There's another type of replay attacks, it occurs when the owner deploy a ReceiverPays smart contract, make some payments, @@ -760,8 +758,7 @@ creates the proper signature for the `ReceiverPays` example: web3.personal.sign(hash, web3.eth.defaultAccount, callback); } - -:: + Recovering the Message Signer in Solidity ----------------------------------------- @@ -807,7 +804,6 @@ We'll use the `inline assembly Date: Sun, 3 Jun 2018 12:31:46 -0300 Subject: [PATCH 04/12] write the full contracts --- docs/solidity-by-example.rst | 422 ++++++++++++++++++++--------------- 1 file changed, 243 insertions(+), 179 deletions(-) diff --git a/docs/solidity-by-example.rst b/docs/solidity-by-example.rst index 3b6b4cb91..cc2bdd734 100644 --- a/docs/solidity-by-example.rst +++ b/docs/solidity-by-example.rst @@ -687,7 +687,7 @@ doing it using: :: - // Hashing first makes a few things easier + /// Hashing first makes a few things easier var hash = web3.sha3("message to sign"); web3.personal.sign(hash, web3.eth.defaultAccount, function () {...}); @@ -707,19 +707,6 @@ For a contract that fulfills payments, the signed message must include: To avoid replay attacks we'll use the same as in Ethereum transactions themselves, a nonce. And our smart contract will check if that nonce is reused. - -:: - - mapping(uint256 => bool) usedNonces; - - function claimPayment(uint256 amount, uint256 nonce, bytes signature) public { - require(!usedNonces[nonce]); - usedNonces[nonce] = true; - - // ... - } - - There's another type of replay attacks, it occurs when the owner deploy a ReceiverPays smart contract, make some payments, and then destroy the contract. Later, he decide to deploy the @@ -728,6 +715,8 @@ know the nonces used in the previous deployment, so the attacker can use the old messages again. We can protect agains it including the contract's address in our message, and only accepting the messages containing contract's address itself. +You can see this function reading the *first two lines* in the *claimPayment()* function in the full contract, +it is at the end of this chapter. Packing arguments ----------------- @@ -741,15 +730,15 @@ the arguments must be concatenated in the same way. The `ethereumjs-abi `_ library provides a function called `soliditySHA3` that mimics the behavior of Solidity's `keccak256` function. -Putting it all together, here's a JavaScript function that +Putting it all together, here's a **JavaScript function** that creates the proper signature for the `ReceiverPays` example: :: - // recipient is the address that should be paid. - // amount, in wei, specifies how much ether should be sent. - // nonce can be any unique number, do you remind the replay attacks? we are preventing them here - // contractAddress do you remind the cross-contract replay attacks? + /// recipient is the address that should be paid. + /// amount, in wei, specifies how much ether should be sent. + /// nonce can be any unique number, do you remind the replay attacks? we are preventing them here + /// contractAddress do you remind the cross-contract replay attacks? function signPayment(recipient, amount, nonce, contractAddress, callback) { var hash = "0x" + ethereumjs.ABI.soliditySHA3( ["address", "uint256", "uint256", "address"], @@ -758,7 +747,6 @@ creates the proper signature for the `ReceiverPays` example: web3.personal.sign(hash, web3.eth.defaultAccount, callback); } - Recovering the Message Signer in Solidity ----------------------------------------- @@ -778,84 +766,97 @@ so the 1st step is sppliting those parameters back out. It can be done on the cl but doing it inside the smart contract means only one signature parameter needs to be sent rather than three. Sppliting apart a bytes array into component parts is a little messy. -We'll use the `inline assembly `_ to do the job: +We'll use the `inline assembly `_ to do the job +in the *splitSignature* function, it is the 3rd function in the full contract, this is at the end of this +chapter. -:: - - function splitSignature(bytes sig) - internal - pure - returns (uint8, bytes32, bytes32) - { - require(sig.length == 65); - - bytes32 r; - bytes32 s; - uint8 v; - - assembly { - // first 32 bytes, after the length prefix - r := mload(add(sig, 32)) - // second 32 bytes - s := mload(add(sig, 64)) - // final byte (first byte of the next 32 bytes) - v := byte(0, mload(add(sig, 96))) - } - return (v, r, s); - } - - -Here's a brief explanation of the code: - - * Dynamically-sized arrays are represented in a memory by a 32-byte length followed by the actual data. The code here starts reading data at byte 32 to skip past that length. The `require` at the top of the function ensures the signature is the correct length. - * *r* and *s* are 32 bytes each and together make up the first 64 bytes of the signature. - * *v* is the 65th byte, which can be found at byte offset 96 (32 bytes for the length, 64 bytes for *r* and *s*). The `mload` opcode loads 32 bytes at a time, so the function then needs to extract just the first byte of the word that was read. This is what `byte(0, ...)` does. - Computing the Message Hash -------------------------- The smart contract needs to know exactly what parameters were signed, and so it must recreate the message from the parameters and use that -for signature verification: +for signature verification. We need the functions *prefixed* and +*recoverSigner* to do it, in function *claimPayment* you can see the +use of that functions. + + +The full contract +----------------- :: - // builds a prefixed hash to mimic the behavior of eth_sign. - function prefixed(bytes32 hash) internal pure returns(bytes32) { - return keccak256("\x19Ethereum Signed Message:\n32", hash); - } - - function claimPayment(uint256 amount, uint256 nonce, bytes sig) public { - require(!usedNonces[nonce]); - usedNonces[nonce] = true; - - // this recreates the message that was signed on the client. - bytes32 message = prefixed(keccak256(msg.sender, amount, nonce, this)); - - require(recoverSigner(message, sig) == owner); - - msg.sender.transfer(amount); + pragma solidity ^0.4.20; + + contract ReceiverPays { + address owner = msg.sender; + + mapping(uint256 => bool) usedNonces; + + function ReceiverPays() public payable {} + + function claimPayment(uint256 amount, uint256 nonce, bytes signature) public { + require(!usedNonces[nonce]); + usedNonces[nonce] = true; + + // this recreates the message that was signed on the client + bytes32 message = prefixed(keccak256(msg.sender, amount, nonce, this)); + + require(recoverSigner(message,sig) == owner); + + msg.sender.transfer(amount); + } + + /// destroy the contract and reclaim the leftover funds. + function kill() public { + require(msg.sender == owner); + selfdestruct(msg.sender); + } + + /// signature methods. + function splitSignature(bytes sig) + internal + pure + returns (uint8, bytes32, bytes32) + { + require(sig.length == 65); + + bytes32 r; + bytes32 s; + uint8 v; + + assembly { + // first 32 bytes, after the length prefix. + r := mload(add(sig,32)) + // second 32 bytes. + s := mload(add(sig,64)) + // final byte (first byte of the next 32 bytes). + v := byte(0, mload(add(sig, 96))) + } + + return (v, r, s); + } + + function recoverSigner(bytes32 message, bytes sig) + internal + pure + returns (address) + { + uint8; + bytes32 r; + bytes32 s; + + (v, r, s) = splitSignature(sig); + + return ecrecover(message, v, r, s); + } + + /// builds a prefixed hash to mimic the behavior of eth_sign. + function prefixed(bytes32 hash) internal pure return (bytes32) { + return keccak256("\x19Ethereum Signed Message:\n32", hash); + } } -Our implementation of `recoverSigner`: - -:: - - function recoverSigner(bytes32 message, bytes sig) - internal - pure - returns (address) - { - uint8 v; - bytes32 r; - bytes32 s; - - (v, r, s) = splitSignature(sig); - - return ecrecover(message, v, r, s); - } - Writing a Simple Payment Channel ================================ @@ -893,25 +894,8 @@ Opening the Payment Channel To open the payment channel, the sender deploys the smart contract, attaching the ether to be escrowed and specifying the intendend recipient -and a maximum duration for the channel to exist. - -:: - - contract SimplePaymentChannel { - address public sender; // The account sending payments. - address public recipient; // The account receiving the payments. - uint256 public expiration; // Timeout in case the recipient never closes. - - function SimplePaymentChannel(address _recipient, uint256 duration) - public - payable - { - sender = msg.sender; - recipient = _recipient; - expiration = now + duration; - } - } - +and a maximum duration for the channel to exist. It is the function +*SimplePaymentChannel* in the contract, that is at the end of this chapter. Making Payments --------------- @@ -934,7 +918,7 @@ We don't need anymore the nonce per-message, because the smart contract will only honor a single message. The address of the smart contract is still used to prevent a message intended for one payment channel from being used for a different channel. -Here's the modified code to cryptographic a message from the previous chapter: +Here's the modified **javascript code** to cryptographic a message from the previous chapter: :: @@ -960,6 +944,155 @@ Here's the modified code to cryptographic a message from the previous chapter: var message = constructPaymentMessage(contractAddress, amount); signMessage(message, callback); } + +Closing the Payment Channel +--------------------------- + +When the recipient is ready to receive their funds, it's time to +close the payment channel by calling a *close* function on the smart contract. +Closing the channel pays the recipient the ether they're owed and destroys the contract, +sending any remaining ether back to the sender. +To close the channel, the recipient needs to share a message signed by the sender. + +The smart contract must verify that the message contains a valid signature from the sender. +The process for doing this verification is the same as the process the recipient uses. +The Solidity functions *isValidSignature* and *recoverSigner* work just like their +JavaScript counterparts in the previous section. The latter is borrowed from the +*ReceiverPays* contract in the previous chapter. + +The *close* function can only be called by the payment channel recipient, +who will naturally pass the most recent payment message because that message +carries the highest total owed. If the sender were allowed to call this function, +they could provide a message with a lower amount and cheat the recipient out of what they're owed. + +The function verifies the signed message matches the given parameters. +If everything checks out, the recipient is sent their portion of the ether, +and the sender is sent the rest via a *selfdestruct*. +You can see the *close* function in the full contract. + +Channel Expriration +------------------- + +The recipient can close the payment channel at any time, but if they fail to do so, +the sender needs a way to recover their escrowed funds. An *expiration* time was set +at the time of contract deployment. Once that time is reached, the sender can call +*claimTimeout* to recover their funds. You can see the *claimTimeout* function in the +full contract. + +After this function is called, the recipient can no longer receive any ether, +so it's important that the recipient close the channel before the expiration is reached. + + +The full contract +----------------- + +:: + + pragma solidity ^0.4.20; + + contract SimplePaymentChannel { + address public sender; // The account sending payments. + address public recipient; // The account receiving the payments. + uint256 public expiration; // Timeout in case the recipient never closes. + + function SimplePaymentChannel(address _recipient, uint256 duration) + public + payable + { + sender = msg.sender; + recipient = _recipient; + expiration = now + duration; + } + + function isValidSignature(uint256 amount, bytes signature) + internal + view + returns (bool) + { + bytes32 message = prefixed(keccak256(this, amount)); + + // check that the signature is from the payment sender + return recoverSigner(message, signature) == sender; + } + + /// the recipient can close the channel at any time by presenting a + /// signed amount from the sender. the recipient will be sent that amount, + /// and the remainder will go back to the sender + function close(uint256 amount, bytes signature) public { + require(msg.sender == recipient); + require(isValidSignature(amount, signature)); + + recipient.transfer(amount); + selfdestruct(sender); + } + + /// the sender can extend the expiration at any time + function extend(uint256 newExpiration) public { + require(msg.sender == sender); + require(newExpiration > expiration); + + expiration = newExpiration; + } + + /// if the timeout is reached without the recipient closing the channel, + /// then the ether is realeased back to the sender. + funtion clainTimeout() public { + require(now >= expiration); + selfdestruct(sender); + } + + /// from here to the end of this contract, all the functions we already wrote, in + /// the 'creating and verifying signatures' chapter, so if you already know what them + /// does, you can skip it. + + /// the same functions we wrote in the 'creating and verifying signatures' chapter, + /// you can go there to find the full explanations + + function splitSignature(bytes sig) + internal + pure + returns (uint8, bytes32, bytes32) + { + require(sig.length == 65); + + bytes32 r; + bytes32 s; + uint8 v; + + assembly { + // first 32 bytes, after the length prefix + r := mload(add(sig, 32)) + // second 32 bytes + s := mload(add(sig, 64)) + // final byte (first byte of the next 32 bytes) + v := byte(0, mload(add(sig, 96))) + } + + return (v, r, s); + } + + function recoverSigner(bytes32 message, bytes sig) + internal + pure + returns (address) + { + uint8 v; + bytes32 r; + bytes32 s; + + (v, r, s) = splitSignature(sig); + + return ecrecover(message, v, r, s); + } + + /// builds a prefixed hash to mimic the behavior of eth_sign. + function prefixed(bytes32 hash) internal pure returns (bytes32) { + return keccak256("\x19Ethereum Signed Message:\n32", hash); + } + } + + + Verifying Payments @@ -980,8 +1113,10 @@ The recipient should verify each message using the following process: 4. Verify that the signature is valid and comes from the payment channel sender. We'll use the `ethereumjs-util `_ -library to write this verifications. -The following code borrows the `constructMessage` function from the signing code above: +library to write this verifications. The final step can be done a number of ways, +but if it's being done in **JavaScript**. +The following code borrows the `constructMessage` function from the signing **JavaScript code** +above: :: @@ -1006,74 +1141,3 @@ The following code borrows the `constructMessage` function from the signing code return signer.toLowerCase() == ethereumjs.Util.stripHexPrefix(expectedSigner).toLowerCase(); } - - -Closing the Payment Channel ---------------------------- - -When the recipient is ready to receive their funds, it's time to -close the payment channel by calling a *close* function on the smart contract. -Closing the channel pays the recipient the ether they're owed and destroys the contract, -sending any remaining ether back to the sender. -To close the channel, the recipient needs to share a message signed by the sender. - -The smart contract must verify that the message contains a valid signature from the sender. -The process for doing this verification is the same as the process the recipient uses. -The Solidity functions *isValidSignature* and *recoverSigner* work just like their -JavaScript counterparts in the previous section. The latter is borrowed from the -*ReceiverPays* contract in the previous chapter. - -:: - - function isValidSignature(uint256 amount, bytes signature) - internal - view - returns (bool) - { - bytes32 message = prefixed(keccak256(this, amount)); - - // check that the signature is from the payment sender. - return recoverSigner(message, signature) == sender; - } - - // the recipient can close the channel at any time by presentating a signed - // amount from the sender. The recipient will be sent that amount, - // and the reaminder will go back to the sender. - function close(uint256 amount, bytes signature) public { - require(msg.sender == recipient); - require(isValidSignature(amount, signature)); - - recipient.transafer(amount); - selfdesctruct(sender); - } - - -The *close* function can only be called by the payment channel recipient, -who will naturally pass the most recent payment message because that message -carries the highest total owed. If the sender were allowed to call this function, -they could provide a message with a lower amount and cheat the recipient out of what they're owed. - -The function verifies the signed message matches the given parameters. -If everything checks out, the recipient is sent their portion of the ether, -and the sender is sent the rest via a *selfdesctruct*. - -Channel Expriration -------------------- - -The recipient can close the payment channel at any time, but if they fail to do so, -the sender needs a way to recover their escrowed funds. An *expiration* time was set -at the time of contract deployment. Once that time is reached, the sender can call -*claimTimeout* to recover their funds. - -:: - - // if the timeout is reached without the recipient closing the channel then, - // the ether is released back to the sender. - function claimTimeout() public { - require(now >= expiration); - selfdestruct(sender); - } - - -After this function is called, the recipient can no longer receive any ether, -so it's important that the recipient close the channel before the expiration is reached. From e89d6350459343bd213f5525b9993194ce7e8edb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20V=C3=ADtor?= Date: Sun, 3 Jun 2018 13:20:49 -0300 Subject: [PATCH 05/12] fix a word --- docs/solidity-by-example.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/solidity-by-example.rst b/docs/solidity-by-example.rst index cc2bdd734..e87dea97d 100644 --- a/docs/solidity-by-example.rst +++ b/docs/solidity-by-example.rst @@ -970,7 +970,7 @@ If everything checks out, the recipient is sent their portion of the ether, and the sender is sent the rest via a *selfdestruct*. You can see the *close* function in the full contract. -Channel Expriration +Channel Expiration ------------------- The recipient can close the payment channel at any time, but if they fail to do so, From 6bd82428d2e766893fda8c89eb512e37a1d2ba1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20V=C3=ADtor?= Date: Sun, 3 Jun 2018 17:36:28 -0300 Subject: [PATCH 06/12] fix clainTimeout() function --- docs/solidity-by-example.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/solidity-by-example.rst b/docs/solidity-by-example.rst index e87dea97d..cad652dc6 100644 --- a/docs/solidity-by-example.rst +++ b/docs/solidity-by-example.rst @@ -1036,7 +1036,7 @@ The full contract /// if the timeout is reached without the recipient closing the channel, /// then the ether is realeased back to the sender. - funtion clainTimeout() public { + function clainTimeout() public { require(now >= expiration); selfdestruct(sender); } From 94381c67b9c070d7580ccdda015b375e0495a3ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20V=C3=ADtor?= Date: Sun, 3 Jun 2018 17:57:15 -0300 Subject: [PATCH 07/12] fix returns --- docs/solidity-by-example.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/solidity-by-example.rst b/docs/solidity-by-example.rst index cad652dc6..b1bc11d9f 100644 --- a/docs/solidity-by-example.rst +++ b/docs/solidity-by-example.rst @@ -851,7 +851,7 @@ The full contract } /// builds a prefixed hash to mimic the behavior of eth_sign. - function prefixed(bytes32 hash) internal pure return (bytes32) { + function prefixed(bytes32 hash) internal pure returns (bytes32) { return keccak256("\x19Ethereum Signed Message:\n32", hash); } } From 1db78a1660313ab0aa5228094e690de881e1128f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20V=C3=ADtor?= Date: Sun, 3 Jun 2018 18:20:53 -0300 Subject: [PATCH 08/12] fix recoverSigner function --- docs/solidity-by-example.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/solidity-by-example.rst b/docs/solidity-by-example.rst index b1bc11d9f..52beb862b 100644 --- a/docs/solidity-by-example.rst +++ b/docs/solidity-by-example.rst @@ -792,7 +792,7 @@ The full contract mapping(uint256 => bool) usedNonces; - function ReceiverPays() public payable {} + constructor() public payable {} function claimPayment(uint256 amount, uint256 nonce, bytes signature) public { require(!usedNonces[nonce]); @@ -801,7 +801,7 @@ The full contract // this recreates the message that was signed on the client bytes32 message = prefixed(keccak256(msg.sender, amount, nonce, this)); - require(recoverSigner(message,sig) == owner); + require(recoverSigner(message, signature) == owner); msg.sender.transfer(amount); } @@ -841,7 +841,7 @@ The full contract pure returns (address) { - uint8; + uint8 v; bytes32 r; bytes32 s; From 48e6bb51fb39736cf0d95f7860682fb44528ca60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20V=C3=ADtor?= Date: Thu, 7 Jun 2018 16:37:14 -0300 Subject: [PATCH 09/12] update micropayment channel example --- docs/solidity-by-example.rst | 145 +++++++++++++++++++---------------- 1 file changed, 78 insertions(+), 67 deletions(-) diff --git a/docs/solidity-by-example.rst b/docs/solidity-by-example.rst index 52beb862b..aa084483c 100644 --- a/docs/solidity-by-example.rst +++ b/docs/solidity-by-example.rst @@ -645,42 +645,48 @@ Safe Remote Purchase Micropayment Channel ******************** +In this section we will learn how to build a simple implementation +of a payment channel. It use cryptographics signatures to make +repeated transfers of Ether securely, instantaneously, and +without transaction fees. To do it we need to understand how to +sign and verify signatures, and setup the payment channel. + Creating and verifying signatures ================================= +Imagine the Alice wants to send a quantity in Ether to the Bob, +Alice is the sender and the Bob is the recipient. +So all that Alice will do now is using cryptographics signatures +that she will make and send off-chain (e.g. via email) to the Bob. +She will call the contract as ReceiverPays, it will works a lot like +writing a check. Signatures are used to authorize transactions, -and they're a general tool that's available to -smart contracts. In this chapter we'll use it to -prove to a smart contract that a certain account -approved a certain message. We'll build a simple -smart contract that lets me transmit ether, but -in a unsual way, instead of calling a function myself -to initiate a payment, I'll let the receiver of -the payment do that, and therefore pay the transaction -fee. All this using cryptographics signatures that I'll -make and send off-chain (e.g. via email). We'll call our -contract as ReceiverPays, it will works a lot like -writing a check.Our contract will works like that: +and they are a general tool that is available to +smart contracts. Alice will build a simple +smart contract that lets her transmit Ether, but +in a unusual way, instead of calling a function herself +to initiate a payment, she will let Bob +does that, and therefore pay the transaction fee. +The contract will works like that: - 1. The owner deploys ReceiverPays, attaching enough ether to cover the payments that will be made. - 2. The owner authorizes a payment by signing a message with their private key. - 3. The owner sends the cryptographically signed message to the designated recipient. The message does not need to be kept secret (you'll understand it later), and the mechanism for sending it doesn't matter. - 4. The recipient claims their payment by presenting the signed message to the smart contract, it verifies the authenticity of the message and then releases the funds. + 1. The Alice deploys ReceiverPays, attaching enough Ether to cover the payments that will be made. + 2. The Alice authorizes a payment by signing a message with their private key. + 3. The Alice sends the cryptographically signed message to Bob. The message does not need to be kept secret (you will understand it later), and the mechanism for sending it doesn't matter. + 4. The Bob claims their payment by presenting the signed message to the smart contract, it verifies the authenticity of the message and then releases the funds. Creating the signature ---------------------- -We don't need the to interact with Ethereum network to -do that. The proccess is completely offline, and the +The Alice don't need to interact with Ethereum network to +sign the transaction. The proccess is completely offline, and the every major programming language has the libraries to do it. -The signature algorithm Ethereum has the support for is the -`Elliptic Curve Signature Algorithm(EDCSA) `_. -In this tutorial, we'll signing messages in the web browser -using web3.js and MetaMask. We can sign messages in too many ways, -but some of them are incompatible. We'll use the new standard -way to do that `EIP-762 `_, -it provides a number of other security benefits. -Is recommended to stick with the most standard format of signing, +The `Elliptic Curve Signature Algorithm(ECDCSA) `_ +is the signature algorithm Ethereum has to do it. +In this tutorial, we will signing messages in the web browser +using web3.js and MetaMask. We can sign messages in too many ways. +We will use the standard way provided in `EIP-762 `_, +as it provides a number of other security benefits. +Is recommended to keep with the most standard format of signing, as specified by the `eth_sign JSON-RPC method `_ In MetaMask, this algorithm is followed best by the web3.js function `web3.personal.sign`, doing it using: @@ -692,7 +698,7 @@ doing it using: web3.personal.sign(hash, web3.eth.defaultAccount, function () {...}); -Remind that the prefix includes the length of the message. +Note: Remind that the prefix includes the length of the message. Hashing first means the message will always be 32 bytes long, which means the prefix is always the same, this makes everything easier. @@ -703,16 +709,20 @@ For a contract that fulfills payments, the signed message must include: 1. The recipient's address 2. The amount to be transferred - 3. An additional data to protects agains replay attacks + 3. An additional data to protects against replay attacks -To avoid replay attacks we'll use the same as in Ethereum transactions -themselves, a nonce. And our smart contract will check if that nonce is reused. -There's another type of replay attacks, it occurs when the +A replay attack is when a signature is reused to claim authorization for +a second action. +To avoid replay attacks we will use the same as in Ethereum transactions +themselves, a nonce. A nonce is the number of transactions sent by an +account. +And the Alice's smart contract will check if that nonce is reused. +There is another type of replay attacks, it occurs when the owner deploy a ReceiverPays smart contract, make some payments, and then destroy the contract. Later, he decide to deploy the RecipientPays smart contract again, but the new contract doesn't know the nonces used in the previous deployment, so the attacker -can use the old messages again. We can protect agains it including +can use the old messages again. The Alice can protect against it including the contract's address in our message, and only accepting the messages containing contract's address itself. You can see this function reading the *first two lines* in the *claimPayment()* function in the full contract, @@ -722,7 +732,7 @@ Packing arguments ----------------- Now that we have identified what information to include in the -signed message, we're ready to put the message together, hash it, +signed message, we are ready to put the message together, hash it, and sign it. Solidity's `keccak256/sha3 function `_ hashes by first concatenating them in a tightly packed form. For the hash generated on the client match the one generated in the smart contract, @@ -730,7 +740,7 @@ the arguments must be concatenated in the same way. The `ethereumjs-abi `_ library provides a function called `soliditySHA3` that mimics the behavior of Solidity's `keccak256` function. -Putting it all together, here's a **JavaScript function** that +Putting it all together, here is a **JavaScript function** that creates the proper signature for the `ReceiverPays` example: :: @@ -766,7 +776,7 @@ so the 1st step is sppliting those parameters back out. It can be done on the cl but doing it inside the smart contract means only one signature parameter needs to be sent rather than three. Sppliting apart a bytes array into component parts is a little messy. -We'll use the `inline assembly `_ to do the job +We will use the `inline assembly `_ to do the job in the *splitSignature* function, it is the 3rd function in the full contract, this is at the end of this chapter. @@ -861,59 +871,60 @@ The full contract Writing a Simple Payment Channel ================================ -We'll build a simple, but complete, implementation of a payment channel. +Do you remember Alice and Bob? They are here again. +The Alice will build a simple, but complete, implementation of a payment channel. Payment channels use cryptographic signatures to make repeated transfers -of ether securely, instantaneously, and without transaction fees. but... +of Ether securely, instantaneously, and without transaction fees. but... What is a Payment Channel? -------------------------- -Payment channels allow participants to make repeated transfers of ether without +Payment channels allow participants to make repeated transfers of Ether without using transactions. This means that the delays and fees associated with transactions -can be avoided. We're going to explore a simple unidirectional payment channel between -two parties. Using it involves three steps: +can be avoided. We are going to explore a simple unidirectional payment channel between +two parties (Alice and Bob). Using it involves three steps: - 1. The sender funds a smart contract with ether. This "opens" the payment channel. - 2. The sender signs messages that specify how much of that ether is owed to the recipient. This step is repeated for each payment. - 3. The recipient "closes" the payment channel, withdrawing their portion of the ether and sending the remainder back to the sender. + 1. The Alice funds a smart contract with Ether. This "opens" the payment channel. + 2. The Alice signs messages that specify how much of that Ether is owed to the recipient. This step is repeated for each payment. + 3. The Bob "closes" the payment channel, withdrawing their portion of the ether and sending the remainder back to the sender. A note: only steps 1 and 3 require Ethereum transactions, the step 2 means that the sender a cryptographic signature to the recipient via off chain ways (e.g. email). This means only two transactions are required to support any number of transfers. -The recipient is guaranteed to receive their funds because the smart contract escrows -the ether and honors a valid signed message. The smart contract also enforces a timeout, -so the sender is guaranteed to eventually recover their funds even if the recipient refuses +The Bob is guaranteed to receive their funds because the smart contract escrows +the Ether and honors a valid signed message. The smart contract also enforces a timeout, +so the Alice is guaranteed to eventually recover their funds even if the recipient refuses to close the channel. -It's up to the participants in a payment channel to decide how long to keep it open. +It is up to the participants in a payment channel to decide how long to keep it open. For a short-lived transaction, such as paying an internet cafe for each minute of network access, or for a longer relationship, such as paying an employee an hourly wage, a payment could last for months or years. Opening the Payment Channel --------------------------- -To open the payment channel, the sender deploys the smart contract, -attaching the ether to be escrowed and specifying the intendend recipient +To open the payment channel, the Alice deploys the smart contract, +attaching the Ether to be escrowed and specifying the intendend recipient and a maximum duration for the channel to exist. It is the function *SimplePaymentChannel* in the contract, that is at the end of this chapter. Making Payments --------------- -The sender makes payments by sending messages to the recipient. +The Alice makes payments by sending signed messages to the Bob. This step is performed entirely outside of the Ethereum network. Messages are cryptographically signed by the sender and then transmitted directly to the recipient. Each message includes the following information: * The smart contract's address, used to prevent cross-contract replay attacks. - * The total amount of ether that is owed the recipient so far. + * The total amount of Ether that is owed the recipient so far. A payment channel is closed just once, at the of a series of transfers. Because of this, only one of the messages sent will be redeemed. This is why -each message specifies a cumulative total amount of ether owed, rather than the +each message specifies a cumulative total amount of Ether owed, rather than the amount of the individual micropayment. The recipient will naturally choose to -redeem the most recent message because that's the one with the highest total. +redeem the most recent message because that is the one with the highest total. We don't need anymore the nonce per-message, because the smart contract will only honor a single message. The address of the smart contract is still used to prevent a message intended for one payment channel from being used for a different channel. @@ -938,7 +949,7 @@ Here's the modified **javascript code** to cryptographic a message from the prev } // contractAddress is used to prevent cross-contract replay attacks. - // amount, in wei, specifies how much ether should be sent. + // amount, in wei, specifies how much Ether should be sent. function signPayment(contractAddress, amount, callback) { var message = constructPaymentMessage(contractAddress, amount); @@ -948,11 +959,11 @@ Here's the modified **javascript code** to cryptographic a message from the prev Closing the Payment Channel --------------------------- -When the recipient is ready to receive their funds, it's time to +When the Bob is ready to receive their funds, it is time to close the payment channel by calling a *close* function on the smart contract. -Closing the channel pays the recipient the ether they're owed and destroys the contract, -sending any remaining ether back to the sender. -To close the channel, the recipient needs to share a message signed by the sender. +Closing the channel pays the recipient the Ether they're owed and destroys the contract, +sending any remaining Ether back to the Alice. +To close the channel, the Bob needs to share a message signed by the Alice. The smart contract must verify that the message contains a valid signature from the sender. The process for doing this verification is the same as the process the recipient uses. @@ -963,24 +974,24 @@ JavaScript counterparts in the previous section. The latter is borrowed from the The *close* function can only be called by the payment channel recipient, who will naturally pass the most recent payment message because that message carries the highest total owed. If the sender were allowed to call this function, -they could provide a message with a lower amount and cheat the recipient out of what they're owed. +they could provide a message with a lower amount and cheat the recipient out of what they are owed. The function verifies the signed message matches the given parameters. -If everything checks out, the recipient is sent their portion of the ether, +If everything checks out, the recipient is sent their portion of the Ether, and the sender is sent the rest via a *selfdestruct*. You can see the *close* function in the full contract. Channel Expiration ------------------- -The recipient can close the payment channel at any time, but if they fail to do so, -the sender needs a way to recover their escrowed funds. An *expiration* time was set -at the time of contract deployment. Once that time is reached, the sender can call +The Bob can close the payment channel at any time, but if they fail to do so, +the Alice needs a way to recover their escrowed funds. An *expiration* time was set +at the time of contract deployment. Once that time is reached, the Alice can call *claimTimeout* to recover their funds. You can see the *claimTimeout* function in the full contract. -After this function is called, the recipient can no longer receive any ether, -so it's important that the recipient close the channel before the expiration is reached. +After this function is called, the Bob can no longer receive any Ether, +so it is important that the Bob close the channel before the expiration is reached. The full contract @@ -1035,7 +1046,7 @@ The full contract } /// if the timeout is reached without the recipient closing the channel, - /// then the ether is realeased back to the sender. + /// then the Ether is realeased back to the sender. function clainTimeout() public { require(now >= expiration); selfdestruct(sender); @@ -1109,7 +1120,7 @@ The recipient should verify each message using the following process: 1. Verify that the contact address in the message matches the payment channel. 2. Verify that the new total is the expected amount. - 3. Verify that the new total does not exceed the amount of ether escrowed. + 3. Verify that the new total does not exceed the amount of Ether escrowed. 4. Verify that the signature is valid and comes from the payment channel sender. We'll use the `ethereumjs-util `_ From 6ec61e283c598be5ee4bb9124366f2631912ff00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20V=C3=ADtor?= Date: Mon, 11 Jun 2018 20:14:17 -0300 Subject: [PATCH 10/12] update code version --- docs/solidity-by-example.rst | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/docs/solidity-by-example.rst b/docs/solidity-by-example.rst index aa084483c..e55b11b19 100644 --- a/docs/solidity-by-example.rst +++ b/docs/solidity-by-example.rst @@ -795,7 +795,7 @@ The full contract :: - pragma solidity ^0.4.20; + pragma solidity ^0.4.24; contract ReceiverPays { address owner = msg.sender; @@ -809,7 +809,7 @@ The full contract usedNonces[nonce] = true; // this recreates the message that was signed on the client - bytes32 message = prefixed(keccak256(msg.sender, amount, nonce, this)); + bytes32 message = prefixed(keccak256(abi.encodePacked(msg.sender, amount, nonce, this))); require(recoverSigner(message, signature) == owner); @@ -862,12 +862,11 @@ The full contract /// builds a prefixed hash to mimic the behavior of eth_sign. function prefixed(bytes32 hash) internal pure returns (bytes32) { - return keccak256("\x19Ethereum Signed Message:\n32", hash); + return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } - Writing a Simple Payment Channel ================================ @@ -999,14 +998,14 @@ The full contract :: - pragma solidity ^0.4.20; + pragma solidity ^0.4.24; contract SimplePaymentChannel { address public sender; // The account sending payments. address public recipient; // The account receiving the payments. uint256 public expiration; // Timeout in case the recipient never closes. - function SimplePaymentChannel(address _recipient, uint256 duration) + constructor (address _recipient, uint256 duration) public payable { @@ -1020,7 +1019,7 @@ The full contract view returns (bool) { - bytes32 message = prefixed(keccak256(this, amount)); + bytes32 message = prefixed(keccak256(abi.encodePacked(this, amount))); // check that the signature is from the payment sender return recoverSigner(message, signature) == sender; @@ -1098,7 +1097,7 @@ The full contract /// builds a prefixed hash to mimic the behavior of eth_sign. function prefixed(bytes32 hash) internal pure returns (bytes32) { - return keccak256("\x19Ethereum Signed Message:\n32", hash); + return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } From 7ffdad4ae36042d81d0d8738e6f915648bc8fb44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20V=C3=ADtor?= Date: Mon, 25 Jun 2018 19:06:44 -0300 Subject: [PATCH 11/12] add explanation about the splitSignature function --- docs/solidity-by-example.rst | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/solidity-by-example.rst b/docs/solidity-by-example.rst index e55b11b19..5f09446b8 100644 --- a/docs/solidity-by-example.rst +++ b/docs/solidity-by-example.rst @@ -1056,7 +1056,8 @@ The full contract /// does, you can skip it. /// the same functions we wrote in the 'creating and verifying signatures' chapter, - /// you can go there to find the full explanations + /// you can go there to find the full explanations. + /// please read the notes below this contract. function splitSignature(bytes sig) internal @@ -1102,6 +1103,9 @@ The full contract } +Note: The function *splitSignature* uses the code from the `gist `_. In +a real implementation should be used a more tested library, such as the +openzepplin's fork of the original code, `library `_. From 15283e8535c6d1cedfe5d47f7bb1fbe03c77e207 Mon Sep 17 00:00:00 2001 From: chriseth Date: Tue, 10 Jul 2018 00:45:00 +0200 Subject: [PATCH 12/12] Some copy-editing. --- docs/solidity-by-example.rst | 236 ++++++++++++++++------------------- 1 file changed, 106 insertions(+), 130 deletions(-) diff --git a/docs/solidity-by-example.rst b/docs/solidity-by-example.rst index 5f09446b8..7e3d77378 100644 --- a/docs/solidity-by-example.rst +++ b/docs/solidity-by-example.rst @@ -647,49 +647,43 @@ Micropayment Channel In this section we will learn how to build a simple implementation of a payment channel. It use cryptographics signatures to make -repeated transfers of Ether securely, instantaneously, and +repeated transfers of Ether between the same parties secure, instantaneous, and without transaction fees. To do it we need to understand how to sign and verify signatures, and setup the payment channel. Creating and verifying signatures ================================= -Imagine the Alice wants to send a quantity in Ether to the Bob, +Imagine Alice wants to send a quantity of Ether to Bob, i.e. Alice is the sender and the Bob is the recipient. -So all that Alice will do now is using cryptographics signatures -that she will make and send off-chain (e.g. via email) to the Bob. -She will call the contract as ReceiverPays, it will works a lot like -writing a check. +Alice only needs to send cryptographically signed messages off-chain +(e.g. via email) to Bob and it will be very similar to writing checks. + Signatures are used to authorize transactions, and they are a general tool that is available to smart contracts. Alice will build a simple smart contract that lets her transmit Ether, but in a unusual way, instead of calling a function herself to initiate a payment, she will let Bob -does that, and therefore pay the transaction fee. -The contract will works like that: +do that, and therefore pay the transaction fee. +The contract will work as follows: - 1. The Alice deploys ReceiverPays, attaching enough Ether to cover the payments that will be made. - 2. The Alice authorizes a payment by signing a message with their private key. - 3. The Alice sends the cryptographically signed message to Bob. The message does not need to be kept secret (you will understand it later), and the mechanism for sending it doesn't matter. - 4. The Bob claims their payment by presenting the signed message to the smart contract, it verifies the authenticity of the message and then releases the funds. + 1. Alice deploys the ``ReceiverPays`` contract, attaching enough Ether to cover the payments that will be made. + 2. Alice authorizes a payment by signing a message with their private key. + 3. Alice sends the cryptographically signed message to Bob. The message does not need to be kept secret + (you will understand it later), and the mechanism for sending it does not matter. + 4. Bob claims their payment by presenting the signed message to the smart contract, it verifies the + authenticity of the message and then releases the funds. Creating the signature ---------------------- -The Alice don't need to interact with Ethereum network to -sign the transaction. The proccess is completely offline, and the -every major programming language has the libraries to do it. -The `Elliptic Curve Signature Algorithm(ECDCSA) `_ -is the signature algorithm Ethereum has to do it. -In this tutorial, we will signing messages in the web browser -using web3.js and MetaMask. We can sign messages in too many ways. -We will use the standard way provided in `EIP-762 `_, +Alice does not need to interact with Ethereum network to +sign the transaction, the proccess is completely offline. +In this tutorial, we will sign messages in the browser +using ``web3.js`` and ``MetaMask``. +In particular, we will use the standard way described in `EIP-762 `_, as it provides a number of other security benefits. -Is recommended to keep with the most standard format of signing, -as specified by the `eth_sign JSON-RPC method `_ -In MetaMask, this algorithm is followed best by the web3.js function `web3.personal.sign`, -doing it using: :: @@ -698,9 +692,9 @@ doing it using: web3.personal.sign(hash, web3.eth.defaultAccount, function () {...}); -Note: Remind that the prefix includes the length of the message. -Hashing first means the message will always be 32 bytes long, -which means the prefix is always the same, this makes everything easier. +Note that the ``web3.personal.sign`` prepends the length of the message to the signed data. +Since we hash first, the message will always be exactly 32 bytes long, +and thus this length prefix is always the same, making everything easier. What to Sign ------------ @@ -709,46 +703,48 @@ For a contract that fulfills payments, the signed message must include: 1. The recipient's address 2. The amount to be transferred - 3. An additional data to protects against replay attacks + 3. Protection against replay attacks -A replay attack is when a signature is reused to claim authorization for +A replay attack is when a signed message is reused to claim authorization for a second action. To avoid replay attacks we will use the same as in Ethereum transactions -themselves, a nonce. A nonce is the number of transactions sent by an +themselves, a so-called nonce, which is the number of transactions sent by an account. -And the Alice's smart contract will check if that nonce is reused. +The smart contract will check if a nonce is used multiple times. + There is another type of replay attacks, it occurs when the -owner deploy a ReceiverPays smart contract, make some payments, -and then destroy the contract. Later, he decide to deploy the -RecipientPays smart contract again, but the new contract doesn't +owner deploys a ``ReceiverPays`` smart contract, performs some payments, +and then destroy the contract. Later, she decides to deploy the +``RecipientPays`` smart contract again, but the new contract does not know the nonces used in the previous deployment, so the attacker -can use the old messages again. The Alice can protect against it including -the contract's address in our message, and only accepting the -messages containing contract's address itself. -You can see this function reading the *first two lines* in the *claimPayment()* function in the full contract, -it is at the end of this chapter. +can use the old messages again. + +Alice can protect against it including +the contract's address in the message, and only +messages containing contract's address itself will be accepted. +This functionality can be found in the first two lines of the ``claimPayment()`` function in the full contract +at the end of this chapter. Packing arguments ----------------- Now that we have identified what information to include in the signed message, we are ready to put the message together, hash it, -and sign it. Solidity's `keccak256/sha3 function `_ -hashes by first concatenating them in a tightly packed form. -For the hash generated on the client match the one generated in the smart contract, -the arguments must be concatenated in the same way. The +and sign it. For simplicity, we just concatenate the data. +The `ethereumjs-abi `_ library provides -a function called `soliditySHA3` that mimics the behavior -of Solidity's `keccak256` function. -Putting it all together, here is a **JavaScript function** that -creates the proper signature for the `ReceiverPays` example: +a function called ``soliditySHA3`` that mimics the behavior +of Solidity's ``keccak256`` function applied to arguments encoded +using ``abi.encodePacked``. +Putting it all together, here is a JavaScript function that +creates the proper signature for the ``ReceiverPays`` example: :: - /// recipient is the address that should be paid. - /// amount, in wei, specifies how much ether should be sent. - /// nonce can be any unique number, do you remind the replay attacks? we are preventing them here - /// contractAddress do you remind the cross-contract replay attacks? + // recipient is the address that should be paid. + // amount, in wei, specifies how much ether should be sent. + // nonce can be any unique number to prevent replay attacks + // contractAddress is used to prevent cross-contract replay attacks function signPayment(recipient, amount, nonce, contractAddress, callback) { var hash = "0x" + ethereumjs.ABI.soliditySHA3( ["address", "uint256", "uint256", "address"], @@ -761,33 +757,34 @@ creates the proper signature for the `ReceiverPays` example: Recovering the Message Signer in Solidity ----------------------------------------- -In general, ECDSA signatures consist of two parameters, *r* and *s*. -Signatures in Ethereum include a thir parameter *v*, that can be used +In general, ECDSA signatures consist of two parameters, ``r`` and ``s``. +Signatures in Ethereum include a third parameter called ``v``, that can be used to recover which account's private key was used to sign in the message, -the transaction's sender. Solidity provides a built-in function `ecrecover `_ -that accepts a message along with the *r*, *s* and *v* parameters and +the transaction's sender. Solidity provides a built-in function +`ecrecover `_ +that accepts a message along with the ``r``, ``s`` and ``v`` parameters and returns the address that was used to sign the message. Extracting the Signature Parameters ----------------------------------- -Signatures produced by web3.js are the concatenation of *r*, *s* and *v*, -so the 1st step is sppliting those parameters back out. It can be done on the client, +Signatures produced by web3.js are the concatenation of ``r``, ``s`` and ``v``, +so the first step is splitting those parameters back out. It can be done on the client, but doing it inside the smart contract means only one signature parameter needs to be sent rather than three. -Sppliting apart a bytes array into component parts is a little messy. -We will use the `inline assembly `_ to do the job -in the *splitSignature* function, it is the 3rd function in the full contract, this is at the end of this -chapter. +Splitting apart a byte array into component parts is a little messy. +We will use `inline assembly `_ to do the job +in the ``splitSignature`` function (the third function in the full contract +at the end of this chapter). Computing the Message Hash -------------------------- The smart contract needs to know exactly what parameters were signed, and so it must recreate the message from the parameters and use that -for signature verification. We need the functions *prefixed* and -*recoverSigner* to do it, in function *claimPayment* you can see the -use of that functions. +for signature verification. The functions ``prefixed`` and +``recoverSigner`` do this and their use can be found in the +``claimPayment`` function. The full contract @@ -826,19 +823,15 @@ The full contract function splitSignature(bytes sig) internal pure - returns (uint8, bytes32, bytes32) + returns (uint8 v, bytes32 r, bytes32 s) { require(sig.length == 65); - bytes32 r; - bytes32 s; - uint8 v; - assembly { // first 32 bytes, after the length prefix. - r := mload(add(sig,32)) + r := mload(add(sig, 32)) // second 32 bytes. - s := mload(add(sig,64)) + s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes). v := byte(0, mload(add(sig, 96))) } @@ -851,11 +844,7 @@ The full contract pure returns (address) { - uint8 v; - bytes32 r; - bytes32 s; - - (v, r, s) = splitSignature(sig); + (uint8 v, bytes32 r, bytes32 s) = splitSignature(sig); return ecrecover(message, v, r, s); } @@ -870,10 +859,9 @@ The full contract Writing a Simple Payment Channel ================================ -Do you remember Alice and Bob? They are here again. -The Alice will build a simple, but complete, implementation of a payment channel. +Alice will now build a simple but complete implementation of a payment channel. Payment channels use cryptographic signatures to make repeated transfers -of Ether securely, instantaneously, and without transaction fees. but... +of Ether securely, instantaneously, and without transaction fees. What is a Payment Channel? -------------------------- @@ -883,17 +871,17 @@ using transactions. This means that the delays and fees associated with transact can be avoided. We are going to explore a simple unidirectional payment channel between two parties (Alice and Bob). Using it involves three steps: - 1. The Alice funds a smart contract with Ether. This "opens" the payment channel. - 2. The Alice signs messages that specify how much of that Ether is owed to the recipient. This step is repeated for each payment. - 3. The Bob "closes" the payment channel, withdrawing their portion of the ether and sending the remainder back to the sender. + 1. Alice funds a smart contract with Ether. This "opens" the payment channel. + 2. Alice signs messages that specify how much of that Ether is owed to the recipient. This step is repeated for each payment. + 3. Bob "closes" the payment channel, withdrawing their portion of the Ether and sending the remainder back to the sender. -A note: only steps 1 and 3 require Ethereum transactions, the step 2 means that -the sender a cryptographic signature to the recipient via off chain ways (e.g. email). +Not ethat only steps 1 and 3 require Ethereum transactions, step 2 means that +the sender transmits a cryptographically signed message to the recipient via off chain ways (e.g. email). This means only two transactions are required to support any number of transfers. -The Bob is guaranteed to receive their funds because the smart contract escrows +Bob is guaranteed to receive their funds because the smart contract escrows the Ether and honors a valid signed message. The smart contract also enforces a timeout, -so the Alice is guaranteed to eventually recover their funds even if the recipient refuses +so Alice is guaranteed to eventually recover their funds even if the recipient refuses to close the channel. It is up to the participants in a payment channel to decide how long to keep it open. For a short-lived transaction, such as paying an internet cafe for each minute of network access, @@ -902,15 +890,15 @@ or for a longer relationship, such as paying an employee an hourly wage, a payme Opening the Payment Channel --------------------------- -To open the payment channel, the Alice deploys the smart contract, +To open the payment channel, Alice deploys the smart contract, attaching the Ether to be escrowed and specifying the intendend recipient and a maximum duration for the channel to exist. It is the function -*SimplePaymentChannel* in the contract, that is at the end of this chapter. +``SimplePaymentChannel`` in the contract, that is at the end of this chapter. Making Payments --------------- -The Alice makes payments by sending signed messages to the Bob. +Alice makes payments by sending signed messages to Bob. This step is performed entirely outside of the Ethereum network. Messages are cryptographically signed by the sender and then transmitted directly to the recipient. @@ -924,11 +912,11 @@ Because of this, only one of the messages sent will be redeemed. This is why each message specifies a cumulative total amount of Ether owed, rather than the amount of the individual micropayment. The recipient will naturally choose to redeem the most recent message because that is the one with the highest total. -We don't need anymore the nonce per-message, because the smart contract will +The nonce per-message is not needed anymore, because the smart contract will only honor a single message. The address of the smart contract is still used to prevent a message intended for one payment channel from being used for a different channel. -Here's the modified **javascript code** to cryptographic a message from the previous chapter: +Here is the modified javascript code to cryptographically sign a message from the previous chapter: :: @@ -955,42 +943,43 @@ Here's the modified **javascript code** to cryptographic a message from the prev signMessage(message, callback); } + Closing the Payment Channel --------------------------- -When the Bob is ready to receive their funds, it is time to -close the payment channel by calling a *close* function on the smart contract. -Closing the channel pays the recipient the Ether they're owed and destroys the contract, -sending any remaining Ether back to the Alice. -To close the channel, the Bob needs to share a message signed by the Alice. +When Bob is ready to receive their funds, it is time to +close the payment channel by calling a ``close`` function on the smart contract. +Closing the channel pays the recipient the Ether they are owed and destroys the contract, +sending any remaining Ether back to Alice. +To close the channel, Bob needs to provide a message signed by Alice. The smart contract must verify that the message contains a valid signature from the sender. The process for doing this verification is the same as the process the recipient uses. -The Solidity functions *isValidSignature* and *recoverSigner* work just like their +The Solidity functions ``isValidSignature`` and ``recoverSigner`` work just like their JavaScript counterparts in the previous section. The latter is borrowed from the -*ReceiverPays* contract in the previous chapter. +``ReceiverPays`` contract in the previous chapter. -The *close* function can only be called by the payment channel recipient, +The ``close`` function can only be called by the payment channel recipient, who will naturally pass the most recent payment message because that message carries the highest total owed. If the sender were allowed to call this function, they could provide a message with a lower amount and cheat the recipient out of what they are owed. The function verifies the signed message matches the given parameters. If everything checks out, the recipient is sent their portion of the Ether, -and the sender is sent the rest via a *selfdestruct*. -You can see the *close* function in the full contract. +and the sender is sent the rest via a ``selfdestruct``. +You can see the ``close`` function in the full contract. Channel Expiration ------------------- -The Bob can close the payment channel at any time, but if they fail to do so, -the Alice needs a way to recover their escrowed funds. An *expiration* time was set -at the time of contract deployment. Once that time is reached, the Alice can call -*claimTimeout* to recover their funds. You can see the *claimTimeout* function in the +Bob can close the payment channel at any time, but if they fail to do so, +Alice needs a way to recover their escrowed funds. An *expiration* time was set +at the time of contract deployment. Once that time is reached, Alice can call +``claimTimeout`` to recover their funds. You can see the ``claimTimeout`` function in the full contract. -After this function is called, the Bob can no longer receive any Ether, -so it is important that the Bob close the channel before the expiration is reached. +After this function is called, Bob can no longer receive any Ether, +so it is important that Bob closes the channel before the expiration is reached. The full contract @@ -1015,9 +1004,9 @@ The full contract } function isValidSignature(uint256 amount, bytes signature) - internal - view - returns (bool) + internal + view + returns (bool) { bytes32 message = prefixed(keccak256(abi.encodePacked(this, amount))); @@ -1051,25 +1040,16 @@ The full contract selfdestruct(sender); } - /// from here to the end of this contract, all the functions we already wrote, in - /// the 'creating and verifying signatures' chapter, so if you already know what them - /// does, you can skip it. - - /// the same functions we wrote in the 'creating and verifying signatures' chapter, - /// you can go there to find the full explanations. - /// please read the notes below this contract. + /// All functions below this are just taken from the chapter + /// 'creating and verifying signatures' chapter. function splitSignature(bytes sig) internal pure - returns (uint8, bytes32, bytes32) + returns (uint8 v, bytes32 r, bytes32 s) { require(sig.length == 65); - bytes32 r; - bytes32 s; - uint8 v; - assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) @@ -1087,11 +1067,7 @@ The full contract pure returns (address) { - uint8 v; - bytes32 r; - bytes32 s; - - (v, r, s) = splitSignature(sig); + (uint8 v, bytes32 r, bytes32 s) = splitSignature(sig); return ecrecover(message, v, r, s); } @@ -1103,9 +1079,9 @@ The full contract } -Note: The function *splitSignature* uses the code from the `gist `_. In -a real implementation should be used a more tested library, such as the -openzepplin's fork of the original code, `library `_. +Note: The function ``splitSignature`` is very simple and does not use all security checks. +A real implementation should use a more rigorously tested library, such as +openzepplin's `version `_ of this code.