diff options
Diffstat (limited to 'docs')
-rw-r--r-- | docs/abi-spec.rst | 67 | ||||
-rw-r--r-- | docs/assembly.rst | 114 | ||||
-rw-r--r-- | docs/bugs_by_version.json | 8 | ||||
-rw-r--r-- | docs/common-patterns.rst | 18 | ||||
-rw-r--r-- | docs/contracts.rst | 373 | ||||
-rw-r--r-- | docs/contributing.rst | 6 | ||||
-rw-r--r-- | docs/control-structures.rst | 79 | ||||
-rw-r--r-- | docs/frequently-asked-questions.rst | 51 | ||||
-rw-r--r-- | docs/grammar.txt | 27 | ||||
-rw-r--r-- | docs/index.rst | 27 | ||||
-rw-r--r-- | docs/installing-solidity.rst | 38 | ||||
-rw-r--r-- | docs/introduction-to-smart-contracts.rst | 18 | ||||
-rw-r--r-- | docs/julia.rst | 571 | ||||
-rw-r--r-- | docs/metadata.rst | 2 | ||||
-rw-r--r-- | docs/miscellaneous.rst | 4 | ||||
-rw-r--r-- | docs/security-considerations.rst | 85 | ||||
-rw-r--r-- | docs/solidity-by-example.rst | 41 | ||||
-rw-r--r-- | docs/structure-of-a-contract.rst | 92 | ||||
-rw-r--r-- | docs/style-guide.rst | 97 | ||||
-rw-r--r-- | docs/types.rst | 92 | ||||
-rw-r--r-- | docs/units-and-global-variables.rst | 11 | ||||
-rw-r--r-- | docs/using-the-compiler.rst | 27 | ||||
-rw-r--r-- | docs/utils/SolidityLexer.py | 10 |
23 files changed, 1334 insertions, 524 deletions
diff --git a/docs/abi-spec.rst b/docs/abi-spec.rst index 77d15026..f249bbcd 100644 --- a/docs/abi-spec.rst +++ b/docs/abi-spec.rst @@ -40,21 +40,21 @@ The following elementary types exist: - ``int<M>``: two's complement signed integer type of ``M`` bits, ``0 < M <= 256``, ``M % 8 == 0``. -- ``address``: equivalent to ``uint160``, except for the assumed interpretation and language typing. +- ``address``: equivalent to ``uint160``, except for the assumed interpretation and language typing. For computing the function selector, ``address`` is used. -- ``uint``, ``int``: synonyms for ``uint256``, ``int256`` respectively (this shorthand not to be used for computing the function selector). +- ``uint``, ``int``: synonyms for ``uint256``, ``int256`` respectively. For computing the function selector, ``uint256`` and ``int256`` have to be used. -- ``bool``: equivalent to ``uint8`` restricted to the values 0 and 1 +- ``bool``: equivalent to ``uint8`` restricted to the values 0 and 1. For computing the function selector, ``bool`` is used. - ``fixed<M>x<N>``: signed fixed-point decimal number of ``M`` bits, ``8 <= M <= 256``, ``M % 8 ==0``, and ``0 < N <= 80``, which denotes the value ``v`` as ``v / (10 ** N)``. - ``ufixed<M>x<N>``: unsigned variant of ``fixed<M>x<N>``. -- ``fixed``, ``ufixed``: synonyms for ``fixed128x19``, ``ufixed128x19`` respectively (this shorthand not to be used for computing the function selector). +- ``fixed``, ``ufixed``: synonyms for ``fixed128x19``, ``ufixed128x19`` respectively. For computing the function selector, ``fixed128x19`` and ``ufixed128x19`` have to be used. - ``bytes<M>``: binary type of ``M`` bytes, ``0 < M <= 32``. -- ``function``: equivalent to ``bytes24``: an address, followed by a function selector +- ``function``: an address (20 bytes) folled by a function selector (4 bytes). Encoded identical to ``bytes24``. The following (fixed-size) array type exists: @@ -157,7 +157,7 @@ on the type of ``X`` being - ``uint<M>``: ``enc(X)`` is the big-endian encoding of ``X``, padded on the higher-order (left) side with zero-bytes such that the length is a multiple of 32 bytes. - ``address``: as in the ``uint160`` case -- ``int<M>``: ``enc(X)`` is the big-endian two's complement encoding of ``X``, padded on the higher-oder (left) side with ``0xff`` for negative ``X`` and with zero bytes for positive ``X`` such that the length is a multiple of 32 bytes. +- ``int<M>``: ``enc(X)`` is the big-endian two's complement encoding of ``X``, padded on the higher-order (left) side with ``0xff`` for negative ``X`` and with zero bytes for positive ``X`` such that the length is a multiple of 32 bytes. - ``bool``: as in the ``uint8`` case, where ``1`` is used for ``true`` and ``0`` for ``false`` - ``fixed<M>x<N>``: ``enc(X)`` is ``enc(X * 10**N)`` where ``X * 10**N`` is interpreted as a ``int256``. - ``fixed``: as in the ``fixed128x19`` case @@ -187,12 +187,12 @@ Given the contract: :: - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; contract Foo { - function bar(bytes3[2] xy) {} - function baz(uint32 x, bool y) returns (bool r) { r = x > 32 || y; } - function sam(bytes name, bool z, uint[] data) {} + function bar(bytes3[2]) public pure {} + function baz(uint32 x, bool y) public pure returns (bool r) { r = x > 32 || y; } + function sam(bytes, bool, uint[]) public pure {} } @@ -288,6 +288,8 @@ In effect, a log entry using this ABI is described as: - ``topics[n]``: ``EVENT_INDEXED_ARGS[n - 1]`` (``EVENT_INDEXED_ARGS`` is the series of ``EVENT_ARGS`` that are indexed); - ``data``: ``abi_serialise(EVENT_NON_INDEXED_ARGS)`` (``EVENT_NON_INDEXED_ARGS`` is the series of ``EVENT_ARGS`` that are not indexed, ``abi_serialise`` is the ABI serialisation function used for returning a series of typed values from a function, as described above). +For all fixed-length Solidity types, the ``EVENT_INDEXED_ARGS`` array contains the 32-byte encoded value directly. However, for *types of dynamic length*, which include ``string``, ``bytes``, and arrays, ``EVENT_INDEXED_ARGS`` will contain the *Keccak hash* of the encoded value, rather than the encoded value directly. This allows applications to efficiently query for values of dynamic-length types (by setting the hash of the encoded value as the topic), but leaves applications unable to decode indexed values they have not queried for. For dynamic-length types, application developers face a trade-off between fast search for predetermined values (if the argument is indexed) and legibility of arbitrary values (which requires that the arguments not be indexed). Developers may overcome this tradeoff and achieve both efficient search and arbitrary legibility by defining events with two arguments — one indexed, one not — intended to hold the same value. + JSON ==== @@ -330,15 +332,15 @@ For example, :: - pragma solidity ^0.4.0; + pragma solidity ^0.4.0; - contract Test { - function Test(){ b = 0x12345678901234567890123456789012; } - event Event(uint indexed a, bytes32 b); - event Event2(uint indexed a, bytes32 b); - function foo(uint a) { Event(a, b); } - bytes32 b; - } + contract Test { + function Test() public { b = 0x12345678901234567890123456789012; } + event Event(uint indexed a, bytes32 b); + event Event2(uint indexed a, bytes32 b); + function foo(uint a) public { Event(a, b); } + bytes32 b; + } would result in the JSON: @@ -377,11 +379,15 @@ As an example, the code :: - contract Test { - struct S { uint a; uint[] b; T[] c; } - struct T { uint x; uint y; } - function f(S s, T t, uint a) { } - } + pragma solidity ^0.4.19; + pragma experimental ABIEncoderV2; + + contract Test { + struct S { uint a; uint[] b; T[] c; } + struct T { uint x; uint y; } + function f(S s, T t, uint a) public { } + function g() public returns (S s, T t, uint a) {} + } would result in the JSON: @@ -451,13 +457,18 @@ Non-standard Packed Mode Solidity supports a non-standard packed mode where: - no :ref:`function selector <abi_function_selector>` is encoded, -- short types are not zero padded and +- types shorter than 32 bytes are neither zero padded nor sign extended and - dynamic types are encoded in-place and without the length. -As an example encoding ``uint1, bytes1, uint8, string`` with values ``1, 0x42, 0x2424, "Hello, world!"`` results in :: +As an example encoding ``int1, bytes1, uint16, string`` with values ``-1, 0x42, 0x2424, "Hello, world!"`` results in :: - 0x0142242448656c6c6f2c20776f726c6421 - ^^ uint1(1) + 0xff42242448656c6c6f2c20776f726c6421 + ^^ int1(-1) ^^ bytes1(0x42) - ^^^^ uint8(0x2424) + ^^^^ uint16(0x2424) ^^^^^^^^^^^^^^^^^^^^^^^^^^ string("Hello, world!") without a length field + +More specifically, each statically-sized type takes as many bytes as its range has +and dynamically-sized types like ``string``, ``bytes`` or ``uint[]`` are encoded without +their length field. This means that the encoding is ambiguous as soon as there are two +dynamically-sized elements. diff --git a/docs/assembly.rst b/docs/assembly.rst index f5abcdc8..02522469 100644 --- a/docs/assembly.rst +++ b/docs/assembly.rst @@ -9,11 +9,6 @@ This assembly language can also be used as "inline assembly" inside Solidity source code. We start with describing how to use inline assembly and how it differs from standalone assembly and then specify assembly itself. -.. note:: - TODO: Write about how scoping rules of inline assembly are a bit different - and the complications that arise when for example using internal functions - of libraries. Furthermore, write about the symbols defined by the compiler. - .. _inline-assembly: Inline Assembly @@ -28,9 +23,10 @@ arising when writing manual assembly by the following features: * functional-style opcodes: ``mul(1, add(2, 3))`` instead of ``push1 3 push1 2 add push1 1 mul`` * assembly-local variables: ``let x := add(2, 3) let y := mload(0x40) x := add(x, y)`` -* access to external variables: ``function f(uint x) { assembly { x := sub(x, 1) } }`` +* access to external variables: ``function f(uint x) public { assembly { x := sub(x, 1) } }`` * labels: ``let x := 10 repeat: x := sub(x, 1) jumpi(repeat, eq(x, 0))`` * loops: ``for { let i := 0 } lt(i, x) { i := add(i, 1) } { y := mul(2, y) }`` +* if statements: ``if slt(x, 0) { x := sub(0, x) }`` * switch statements: ``switch x case 0 { y := mul(x, 2) } default { y := 0 }`` * function calls: ``function f(x) -> y { switch x case 0 { y := 1 } default { y := mul(x, f(sub(x, 1))) } }`` @@ -41,6 +37,11 @@ We now want to describe the inline assembly language in detail. at a low level. This discards several important safety features of Solidity. +.. note:: + TODO: Write about how scoping rules of inline assembly are a bit different + and the complications that arise when for example using internal functions + of libraries. Furthermore, write about the symbols defined by the compiler. + Example ------- @@ -53,7 +54,7 @@ idea is that assembly libraries will be used to enhance the language in such way pragma solidity ^0.4.0; library GetCode { - function at(address _addr) returns (bytes o_code) { + function at(address _addr) public view returns (bytes o_code) { assembly { // retrieve the size of the code, this needs assembly let size := extcodesize(_addr) @@ -77,12 +78,12 @@ you really know what you are doing. .. code:: - pragma solidity ^0.4.12; + pragma solidity ^0.4.16; library VectorSum { // This function is less efficient because the optimizer currently fails to // remove the bounds checks in array access. - function sumSolidity(uint[] _data) returns (uint o_sum) { + function sumSolidity(uint[] _data) public view returns (uint o_sum) { for (uint i = 0; i < _data.length; ++i) o_sum += _data[i]; } @@ -90,7 +91,7 @@ you really know what you are doing. // We know that we only access the array in bounds, so we can avoid the check. // 0x20 needs to be added to an array because the first slot contains the // array length. - function sumAsm(uint[] _data) returns (uint o_sum) { + function sumAsm(uint[] _data) public view returns (uint o_sum) { for (uint i = 0; i < _data.length; ++i) { assembly { o_sum := add(o_sum, mload(add(add(_data, 0x20), mul(i, 0x20)))) @@ -99,7 +100,7 @@ you really know what you are doing. } // Same as above, but accomplish the entire code within inline assembly. - function sumPureAsm(uint[] _data) returns (uint o_sum) { + function sumPureAsm(uint[] _data) public view returns (uint o_sum) { assembly { // Load the length (first 32 bytes) let len := mload(_data) @@ -387,7 +388,7 @@ changes during the call, and thus references to local variables will be wrong. contract C { uint b; - function f(uint x) returns (uint r) { + function f(uint x) public returns (uint r) { assembly { r := mul(x, sload(b_slot)) // ignore the offset, we know it is zero } @@ -400,7 +401,7 @@ Labels Another problem in EVM assembly is that ``jump`` and ``jumpi`` use absolute addresses which can change easily. Solidity inline assembly provides labels to make the use of jumps easier. Note that labels are a low-level feature and it is possible to write -efficient assembly without labels, just using assembly functions, loops and switch instructions +efficient assembly without labels, just using assembly functions, loops, if and switch instructions (see below). The following code computes an element in the Fibonacci series. .. code:: @@ -446,31 +447,6 @@ will have a wrong impression about the stack height at label ``two``: three: } -This problem can be fixed by manually adjusting the stack height for the -assembler - you can provide a stack height delta that is added -to the stack height just prior to the label. -Note that you will not have to care about these things if you just use -loops and assembly-level functions. - -As an example how this can be done in extreme cases, please see the following. - -.. code:: - - { - let x := 8 - jump(two) - 0 // This code is unreachable but will adjust the stack height correctly - one: - x := 9 // Now x can be accessed properly. - jump(three) - pop // Similar negative correction. - two: - 7 // push something onto the stack - jump(one) - three: - pop // We have to pop the manually pushed value here again. - } - Declaring Assembly-Local Variables ---------------------------------- @@ -483,10 +459,10 @@ be just ``0``, but it can also be a complex functional-style expression. .. code:: - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; contract C { - function f(uint x) returns (uint b) { + function f(uint x) public view returns (uint b) { assembly { let v := add(x, 1) mstore(0x80, v) @@ -523,6 +499,21 @@ is performed by replacing the variable's value on the stack by the new value. =: v // instruction style assignment, puts the result of sload(10) into v } +If +-- + +The if statement can be used for conditionally executing code. +There is no "else" part, consider using "switch" (see below) if +you need multiple alternatives. + +.. code:: + + { + if eq(value, 0) { revert(0, 0) } + } + +The curly braces for the body are required. + Switch ------ @@ -583,7 +574,7 @@ Simply leave the initialization and post-iteration parts empty. x := add(x, mload(i)) i := add(i, 0x20) } - } + } Functions --------- @@ -622,7 +613,7 @@ Things to Avoid --------------- Inline assembly might have a quite high-level look, but it actually is extremely -low-level. Function calls, loops and switches are converted by simple +low-level. Function calls, loops, ifs and switches are converted by simple rewriting rules and after that, the only thing the assembler does for you is re-arranging functional-style opcodes, managing jump labels, counting stack height for variable access and removing stack slots for assembly-local variables when the end @@ -669,7 +660,7 @@ for the Solidity compiler. In this form, it tries to achieve several goals: 3. Control flow should be easy to detect to help in formal verification and optimization. In order to achieve the first and last goal, assembly provides high-level constructs -like ``for`` loops, ``switch`` statements and function calls. It should be possible +like ``for`` loops, ``if`` and ``switch`` statements and function calls. It should be possible to write assembly programs that do not make use of explicit ``SWAP``, ``DUP``, ``JUMP`` and ``JUMPI`` statements, because the first two obfuscate the data flow and the last two obfuscate control flow. Furthermore, functional statements of @@ -719,10 +710,10 @@ Example: We will follow an example compilation from Solidity to desugared assembly. We consider the runtime bytecode of the following Solidity program:: - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; contract C { - function f(uint x) returns (uint y) { + function f(uint x) public pure returns (uint y) { y = 1; for (uint i = 0; i < x; i++) y = 2 * y; @@ -870,36 +861,37 @@ Grammar:: AssemblyItem = Identifier | AssemblyBlock | - FunctionalAssemblyExpression | + AssemblyExpression | AssemblyLocalDefinition | - FunctionalAssemblyAssignment | AssemblyAssignment | + AssemblyStackAssignment | LabelDefinition | + AssemblyIf | AssemblySwitch | AssemblyFunctionDefinition | AssemblyFor | - 'break' | 'continue' | - SubAssembly | 'dataSize' '(' Identifier ')' | - LinkerSymbol | - 'errorLabel' | 'bytecodeSize' | - NumberLiteral | StringLiteral | HexLiteral + 'break' | + 'continue' | + SubAssembly + AssemblyExpression = AssemblyCall | Identifier | AssemblyLiteral + AssemblyLiteral = NumberLiteral | StringLiteral | HexLiteral Identifier = [a-zA-Z_$] [a-zA-Z_0-9]* - FunctionalAssemblyExpression = Identifier '(' ( AssemblyItem ( ',' AssemblyItem )* )? ')' - AssemblyLocalDefinition = 'let' IdentifierOrList ':=' FunctionalAssemblyExpression - FunctionalAssemblyAssignment = IdentifierOrList ':=' FunctionalAssemblyExpression + AssemblyCall = Identifier '(' ( AssemblyExpression ( ',' AssemblyExpression )* )? ')' + AssemblyLocalDefinition = 'let' IdentifierOrList ( ':=' AssemblyExpression )? + AssemblyAssignment = IdentifierOrList ':=' AssemblyExpression IdentifierOrList = Identifier | '(' IdentifierList ')' IdentifierList = Identifier ( ',' Identifier)* - AssemblyAssignment = '=:' Identifier + AssemblyStackAssignment = '=:' Identifier LabelDefinition = Identifier ':' - AssemblySwitch = 'switch' FunctionalAssemblyExpression AssemblyCase* + AssemblyIf = 'if' AssemblyExpression AssemblyBlock + AssemblySwitch = 'switch' AssemblyExpression AssemblyCase* ( 'default' AssemblyBlock )? - AssemblyCase = 'case' FunctionalAssemblyExpression AssemblyBlock + AssemblyCase = 'case' AssemblyExpression AssemblyBlock AssemblyFunctionDefinition = 'function' Identifier '(' IdentifierList? ')' ( '->' '(' IdentifierList ')' )? AssemblyBlock - AssemblyFor = 'for' ( AssemblyBlock | FunctionalAssemblyExpression) - FunctionalAssemblyExpression ( AssemblyBlock | FunctionalAssemblyExpression) AssemblyBlock + AssemblyFor = 'for' ( AssemblyBlock | AssemblyExpression ) + AssemblyExpression ( AssemblyBlock | AssemblyExpression ) AssemblyBlock SubAssembly = 'assembly' Identifier AssemblyBlock - LinkerSymbol = 'linkerSymbol' '(' StringLiteral ')' NumberLiteral = HexNumber | DecimalNumber HexLiteral = 'hex' ('"' ([0-9a-fA-F]{2})* '"' | '\'' ([0-9a-fA-F]{2})* '\'') StringLiteral = '"' ([^"\r\n\\] | '\\' .)* '"' diff --git a/docs/bugs_by_version.json b/docs/bugs_by_version.json index cca45428..5a4c9e29 100644 --- a/docs/bugs_by_version.json +++ b/docs/bugs_by_version.json @@ -397,6 +397,10 @@ "bugs": [], "released": "2017-10-18" }, + "0.4.19": { + "bugs": [], + "released": "2017-11-30" + }, "0.4.2": { "bugs": [ "ZeroFunctionSelector", @@ -410,6 +414,10 @@ ], "released": "2016-09-17" }, + "0.4.20": { + "bugs": [], + "released": "2018-02-14" + }, "0.4.3": { "bugs": [ "ZeroFunctionSelector", diff --git a/docs/common-patterns.rst b/docs/common-patterns.rst index 52319be0..7e09f534 100644 --- a/docs/common-patterns.rst +++ b/docs/common-patterns.rst @@ -36,12 +36,12 @@ become the new richest. mapping (address => uint) pendingWithdrawals; - function WithdrawalContract() payable { + function WithdrawalContract() public payable { richest = msg.sender; mostSent = msg.value; } - function becomeRichest() payable returns (bool) { + function becomeRichest() public payable returns (bool) { if (msg.value > mostSent) { pendingWithdrawals[richest] += msg.value; richest = msg.sender; @@ -52,7 +52,7 @@ become the new richest. } } - function withdraw() { + function withdraw() public { uint amount = pendingWithdrawals[msg.sender]; // Remember to zero the pending refund before // sending to prevent re-entrancy attacks @@ -71,12 +71,12 @@ This is as opposed to the more intuitive sending pattern: address public richest; uint public mostSent; - function SendContract() payable { + function SendContract() public payable { richest = msg.sender; mostSent = msg.value; } - function becomeRichest() payable returns (bool) { + function becomeRichest() public payable returns (bool) { if (msg.value > mostSent) { // This line can cause problems (explained below). richest.transfer(msg.value); @@ -157,6 +157,7 @@ restrictions highly readable. /// Make `_newOwner` the new owner of this /// contract. function changeOwner(address _newOwner) + public onlyBy(owner) { owner = _newOwner; @@ -171,6 +172,7 @@ restrictions highly readable. /// May only be called 6 weeks after /// the contract has been created. function disown() + public onlyBy(owner) onlyAfter(creationTime + 6 weeks) { @@ -191,6 +193,7 @@ restrictions highly readable. } function forceOwnerChange(address _newOwner) + public costs(200 ether) { owner = _newOwner; @@ -310,6 +313,7 @@ function finishes. // Order of the modifiers matters here! function bid() + public payable timedTransitions atStage(Stages.AcceptingBlindedBids) @@ -318,6 +322,7 @@ function finishes. } function reveal() + public timedTransitions atStage(Stages.RevealBids) { @@ -332,6 +337,7 @@ function finishes. } function g() + public timedTransitions atStage(Stages.AnotherStage) transitionNext @@ -339,6 +345,7 @@ function finishes. } function h() + public timedTransitions atStage(Stages.AreWeDoneYet) transitionNext @@ -346,6 +353,7 @@ function finishes. } function i() + public timedTransitions atStage(Stages.Finished) { diff --git a/docs/contracts.rst b/docs/contracts.rst index cdc92315..afc32b16 100644 --- a/docs/contracts.rst +++ b/docs/contracts.rst @@ -40,7 +40,7 @@ This means that cyclic creation dependencies are impossible. :: - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; contract OwnedToken { // TokenCreator is a contract type that is defined below. @@ -52,7 +52,7 @@ This means that cyclic creation dependencies are impossible. // This is the constructor which registers the // creator and the assigned name. - function OwnedToken(bytes32 _name) { + function OwnedToken(bytes32 _name) public { // State variables are accessed via their name // and not via e.g. this.owner. This also applies // to functions and especially in the constructors, @@ -67,7 +67,7 @@ This means that cyclic creation dependencies are impossible. name = _name; } - function changeName(bytes32 newName) { + function changeName(bytes32 newName) public { // Only the creator can alter the name -- // the comparison is possible since contracts // are implicitly convertible to addresses. @@ -75,7 +75,7 @@ This means that cyclic creation dependencies are impossible. name = newName; } - function transfer(address newOwner) { + function transfer(address newOwner) public { // Only the current owner can transfer the token. if (msg.sender != owner) return; // We also want to ask the creator if the transfer @@ -90,25 +90,27 @@ This means that cyclic creation dependencies are impossible. contract TokenCreator { function createToken(bytes32 name) + public returns (OwnedToken tokenAddress) { // Create a new Token contract and return its address. // From the JavaScript side, the return type is simply - // "address", as this is the closest type available in + // `address`, as this is the closest type available in // the ABI. return new OwnedToken(name); } - function changeName(OwnedToken tokenAddress, bytes32 name) { - // Again, the external type of "tokenAddress" is - // simply "address". + function changeName(OwnedToken tokenAddress, bytes32 name) public { + // Again, the external type of `tokenAddress` is + // simply `address`. tokenAddress.changeName(name); } - function isTokenTransferOK( - address currentOwner, - address newOwner - ) returns (bool ok) { + function isTokenTransferOK(address currentOwner, address newOwner) + public + view + returns (bool ok) + { // Check some arbitrary condition. address tokenAddress = msg.sender; return (keccak256(newOwner) & 0xff) == (bytes20(tokenAddress) & 0xff); @@ -171,10 +173,10 @@ return parameter list for functions. :: - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; contract C { - function f(uint a) private returns (uint b) { return a + 1; } + function f(uint a) private pure returns (uint b) { return a + 1; } function setData(uint a) internal { data = a; } uint public data; } @@ -193,27 +195,25 @@ In the following example, ``D``, can call ``c.getData()`` to retrieve the value uint private data; function f(uint a) private returns(uint b) { return a + 1; } - function setData(uint a) { data = a; } + function setData(uint a) public { data = a; } function getData() public returns(uint) { return data; } function compute(uint a, uint b) internal returns (uint) { return a+b; } } - contract D { - function readData() { + function readData() public { C c = new C(); - uint local = c.f(7); // error: member "f" is not visible + uint local = c.f(7); // error: member `f` is not visible c.setData(3); local = c.getData(); - local = c.compute(3, 5); // error: member "compute" is not visible + local = c.compute(3, 5); // error: member `compute` is not visible } } - contract E is C { - function g() { + function g() public { C c = new C(); - uint val = compute(3, 5); // acces to internal member (from derivated to parent contract) + uint val = compute(3, 5); // access to internal member (from derived to parent contract) } } @@ -238,10 +238,9 @@ be done at declaration. uint public data = 42; } - contract Caller { C c = new C(); - function f() { + function f() public { uint local = c.data(); } } @@ -257,7 +256,7 @@ it is evaluated as a state variable. If it is accessed externally contract C { uint public data; - function x() { + function x() public { data = 3; // internal access uint val = this.data(); // external access } @@ -280,7 +279,7 @@ The next example is a bit more complex: It will generate a function of the following form:: - function data(uint arg1, bool arg2, uint arg3) returns (uint a, bytes3 b) { + function data(uint arg1, bool arg2, uint arg3) public returns (uint a, bytes3 b) { a = data[arg1][arg2][arg3].a; b = data[arg1][arg2][arg3].b; } @@ -305,13 +304,13 @@ inheritable properties of contracts and may be overridden by derived contracts. pragma solidity ^0.4.11; contract owned { - function owned() { owner = msg.sender; } + function owned() public { owner = msg.sender; } address owner; // This contract only defines a modifier but does not use - // it - it will be used in derived contracts. + // it: it will be used in derived contracts. // The function body is inserted where the special symbol - // "_;" in the definition of a modifier appears. + // `_;` in the definition of a modifier appears. // This means that if the owner calls this function, the // function is executed and otherwise, an exception is // thrown. @@ -321,18 +320,16 @@ inheritable properties of contracts and may be overridden by derived contracts. } } - contract mortal is owned { - // This contract inherits the "onlyOwner"-modifier from - // "owned" and applies it to the "close"-function, which - // causes that calls to "close" only have an effect if + // This contract inherits the `onlyOwner` modifier from + // `owned` and applies it to the `close` function, which + // causes that calls to `close` only have an effect if // they are made by the stored owner. - function close() onlyOwner { + function close() public onlyOwner { selfdestruct(owner); } } - contract priced { // Modifiers can receive arguments: modifier costs(uint price) { @@ -342,21 +339,20 @@ inheritable properties of contracts and may be overridden by derived contracts. } } - contract Register is priced, owned { mapping (address => bool) registeredAddresses; uint price; - function Register(uint initialPrice) { price = initialPrice; } + function Register(uint initialPrice) public { price = initialPrice; } // It is important to also provide the - // "payable" keyword here, otherwise the function will + // `payable` keyword here, otherwise the function will // automatically reject all Ether sent to it. - function register() payable costs(price) { + function register() public payable costs(price) { registeredAddresses[msg.sender] = true; } - function changePrice(uint _price) onlyOwner { + function changePrice(uint _price) public onlyOwner { price = _price; } } @@ -371,10 +367,10 @@ inheritable properties of contracts and may be overridden by derived contracts. } /// This function is protected by a mutex, which means that - /// reentrant calls from within msg.sender.call cannot call f again. + /// reentrant calls from within `msg.sender.call` cannot call `f` again. /// The `return 7` statement assigns 7 to the return value but still /// executes the statement `locked = false` in the modifier. - function f() noReentrancy returns (uint) { + function f() public noReentrancy returns (uint) { require(msg.sender.call()); return 7; } @@ -432,19 +428,27 @@ value types and strings. bytes32 constant myHash = keccak256("abc"); } +.. index:: ! functions + +.. _functions: + +********* +Functions +********* + +.. index:: ! view function, function;view .. _view-functions: -************** View Functions -************** +============== Functions can be declared ``view`` in which case they promise not to modify the state. The following statements are considered modifying the state: #. Writing to state variables. -#. :ref:`Emitting events. <events>`. +#. :ref:`Emitting events <events>`. #. :ref:`Creating other contracts <creating-contracts>`. #. Using ``selfdestruct``. #. Sending Ether via calls. @@ -457,7 +461,7 @@ The following statements are considered modifying the state: pragma solidity ^0.4.16; contract C { - function f(uint a, uint b) view returns (uint) { + function f(uint a, uint b) public view returns (uint) { return a * (b + 42) + now; } } @@ -471,11 +475,12 @@ The following statements are considered modifying the state: .. warning:: The compiler does not enforce yet that a ``view`` method is not modifying state. +.. index:: ! pure function, function;pure + .. _pure-functions: -************** Pure Functions -************** +============== Functions can be declared ``pure`` in which case they promise not to read from or modify the state. @@ -492,7 +497,7 @@ In addition to the list of state modifying statements explained above, the follo pragma solidity ^0.4.16; contract C { - function f(uint a, uint b) pure returns (uint) { + function f(uint a, uint b) public pure returns (uint) { return a * (b + 42); } } @@ -504,9 +509,8 @@ In addition to the list of state modifying statements explained above, the follo .. _fallback-function: -***************** Fallback Function -***************** +================= A contract can have exactly one unnamed function. This function cannot have arguments and cannot return anything. @@ -557,9 +561,9 @@ Please ensure you test your fallback function thoroughly to ensure the execution // This function is called for all messages sent to // this contract (there is no other function). // Sending Ether to this contract will cause an exception, - // because the fallback function does not have the "payable" + // because the fallback function does not have the `payable` // modifier. - function() { x = 1; } + function() public { x = 1; } uint x; } @@ -567,12 +571,11 @@ Please ensure you test your fallback function thoroughly to ensure the execution // This contract keeps all Ether sent to it with no way // to get it back. contract Sink { - function() payable { } + function() public payable { } } - contract Caller { - function callTest(Test test) { + function callTest(Test test) public { test.call(0xabcdef01); // hash does not exist // results in test.x becoming == 1. @@ -584,6 +587,85 @@ Please ensure you test your fallback function thoroughly to ensure the execution } } +.. index:: ! overload + +.. _overload-function: + +Function Overloading +==================== + +A Contract can have multiple functions of the same name but with different arguments. +This also applies to inherited functions. The following example shows overloading of the +``f`` function in the scope of contract ``A``. + +:: + + pragma solidity ^0.4.16; + + contract A { + function f(uint _in) public pure returns (uint out) { + out = 1; + } + + function f(uint _in, bytes32 _key) public pure returns (uint out) { + out = 2; + } + } + +Overloaded functions are also present in the external interface. It is an error if two +externally visible functions differ by their Solidity types but not by their external types. + +:: + + // This will not compile + pragma solidity ^0.4.16; + + contract A { + function f(B _in) public pure returns (B out) { + out = _in; + } + + function f(address _in) public pure returns (address out) { + out = _in; + } + } + + contract B { + } + + +Both ``f`` function overloads above end up accepting the address type for the ABI although +they are considered different inside Solidity. + +Overload resolution and Argument matching +----------------------------------------- + +Overloaded functions are selected by matching the function declarations in the current scope +to the arguments supplied in the function call. Functions are selected as overload candidates +if all arguments can be implicitly converted to the expected types. If there is not exactly one +candidate, resolution fails. + +.. note:: + Return parameters are not taken into account for overload resolution. + +:: + + pragma solidity ^0.4.16; + + contract A { + function f(uint8 _in) public pure returns (uint8 out) { + out = _in; + } + + function f(uint256 _in) public pure returns (uint256 out) { + out = _in; + } + } + +Calling ``f(50)`` would create a type error since ``250`` can be implicitly converted both to ``uint8`` +and ``uint256`` types. On another hand ``f(256)`` would resolve to ``f(uint256)`` overload as ``256`` cannot be implicitly +converted to ``uint8``. + .. index:: ! event .. _events: @@ -641,7 +723,7 @@ All non-indexed arguments will be stored in the data part of the log. uint _value ); - function deposit(bytes32 _id) payable { + function deposit(bytes32 _id) public payable { // Any call to this function (even deeply nested) can // be detected from the JavaScript API by filtering // for `Deposit` to be called. @@ -662,7 +744,7 @@ The use in the JavaScript API would be as follows: // watch for changes event.watch(function(error, result){ // result will contain various information - // including the argumets given to the Deposit + // including the argumets given to the `Deposit` // call. if (!error) console.log(result); @@ -687,12 +769,19 @@ as topics. The event call above can be performed in the same way as :: - log3( - msg.value, - 0x50cb9fe53daa9737b786ab3646f04d0150dc50ef4e75f59509d83667ad5adb20, - msg.sender, - _id - ); + pragma solidity ^0.4.10; + + contract C { + function f() public payable { + bytes32 _id = 0x420042; + log3( + bytes32(msg.value), + bytes32(0x50cb9fe53daa9737b786ab3646f04d0150dc50ef4e75f59509d83667ad5adb20), + bytes32(msg.sender), + _id + ); + } + } where the long hexadecimal number is equal to ``keccak256("Deposit(address,hash256,uint256)")``, the signature of the event. @@ -727,15 +816,14 @@ Details are given in the following example. :: - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; contract owned { function owned() { owner = msg.sender; } address owner; } - - // Use "is" to derive from another contract. Derived + // Use `is` to derive from another contract. Derived // contracts can access all non-private members including // internal functions and state variables. These cannot be // accessed externally via `this`, though. @@ -745,28 +833,25 @@ Details are given in the following example. } } - // These abstract contracts are only provided to make the // interface known to the compiler. Note the function // without body. If a contract does not implement all // functions it can only be used as an interface. contract Config { - function lookup(uint id) returns (address adr); + function lookup(uint id) public returns (address adr); } - contract NameReg { - function register(bytes32 name); - function unregister(); + function register(bytes32 name) public; + function unregister() public; } - - // Multiple inheritance is possible. Note that "owned" is - // also a base class of "mortal", yet there is only a single - // instance of "owned" (as for virtual inheritance in C++). + // Multiple inheritance is possible. Note that `owned` is + // also a base class of `mortal`, yet there is only a single + // instance of `owned` (as for virtual inheritance in C++). contract named is owned, mortal { function named(bytes32 name) { - Config config = Config(0xd5f9d8d94886e70b06e474c3fb14fd43e2f23970); + Config config = Config(0xD5f9D8D94886E70b06E474c3fB14Fd43E2f23970); NameReg(config.lookup(1)).register(name); } @@ -775,9 +860,9 @@ Details are given in the following example. // types of output parameters, that causes an error. // Both local and message-based function calls take these overrides // into account. - function kill() { + function kill() public { if (msg.sender == owner) { - Config config = Config(0xd5f9d8d94886e70b06e474c3fb14fd43e2f23970); + Config config = Config(0xD5f9D8D94886E70b06E474c3fB14Fd43E2f23970); NameReg(config.lookup(1)).unregister(); // It is still possible to call a specific // overridden function. @@ -786,16 +871,15 @@ Details are given in the following example. } } - // If a constructor takes an argument, it needs to be // provided in the header (or modifier-invocation-style at // the constructor of the derived contract (see below)). contract PriceFeed is owned, mortal, named("GoldFeed") { - function updateInfo(uint newInfo) { + function updateInfo(uint newInfo) public { if (msg.sender == owner) info = newInfo; } - function get() constant returns(uint r) { return info; } + function get() public view returns(uint r) { return info; } uint info; } @@ -807,26 +891,24 @@ seen in the following example:: pragma solidity ^0.4.0; contract owned { - function owned() { owner = msg.sender; } + function owned() public { owner = msg.sender; } address owner; } contract mortal is owned { - function kill() { + function kill() public { if (msg.sender == owner) selfdestruct(owner); } } contract Base1 is mortal { - function kill() { /* do cleanup 1 */ mortal.kill(); } + function kill() public { /* do cleanup 1 */ mortal.kill(); } } - contract Base2 is mortal { - function kill() { /* do cleanup 2 */ mortal.kill(); } + function kill() public { /* do cleanup 2 */ mortal.kill(); } } - contract Final is Base1, Base2 { } @@ -838,36 +920,34 @@ derived override, but this function will bypass pragma solidity ^0.4.0; contract owned { - function owned() { owner = msg.sender; } + function owned() public { owner = msg.sender; } address owner; } contract mortal is owned { - function kill() { + function kill() public { if (msg.sender == owner) selfdestruct(owner); } } - contract Base1 is mortal { - function kill() { /* do cleanup 1 */ super.kill(); } + function kill() public { /* do cleanup 1 */ super.kill(); } } contract Base2 is mortal { - function kill() { /* do cleanup 2 */ super.kill(); } + function kill() public { /* do cleanup 2 */ super.kill(); } } - - contract Final is Base2, Base1 { + contract Final is Base1, Base2 { } -If ``Base1`` calls a function of ``super``, it does not simply -call this function on one of its base contracts. Rather, it +If ``Base2`` calls a function of ``super``, it does not simply +call this function on one of its base contracts. Rather, it calls this function on the next base contract in the final -inheritance graph, so it will call ``Base2.kill()`` (note that +inheritance graph, so it will call ``Base1.kill()`` (note that the final inheritance sequence is -- starting with the most -derived contract: Final, Base1, Base2, mortal, owned). +derived contract: Final, Base2, Base1, mortal, owned). The actual function that is called when using super is not known in the context of the class where it is used, although its type is known. This is similar for ordinary @@ -885,12 +965,11 @@ the base constructors. This can be done in two ways:: contract Base { uint x; - function Base(uint _x) { x = _x; } + function Base(uint _x) public { x = _x; } } - contract Derived is Base(7) { - function Derived(uint _y) Base(_y * _y) { + function Derived(uint _y) Base(_y * _y) public { } } @@ -955,7 +1034,7 @@ Contract functions can lack an implementation as in the following example (note pragma solidity ^0.4.0; contract Feline { - function utterance() returns (bytes32); + function utterance() public returns (bytes32); } Such contracts cannot be compiled (even if they contain @@ -965,11 +1044,11 @@ but they can be used as base contracts:: pragma solidity ^0.4.0; contract Feline { - function utterance() returns (bytes32); + function utterance() public returns (bytes32); } contract Cat is Feline { - function utterance() returns (bytes32) { return "miaow"; } + function utterance() public returns (bytes32) { return "miaow"; } } If a contract inherits from an abstract contract and does not implement all non-implemented functions by overriding, it will itself be abstract. @@ -1000,7 +1079,7 @@ Interfaces are denoted by their own keyword: pragma solidity ^0.4.11; interface Token { - function transfer(address recipient, uint amount); + function transfer(address recipient, uint amount) public; } Contracts can inherit interfaces as they would inherit other contracts. @@ -1021,7 +1100,11 @@ is executed in the context of the calling contract, i.e. ``this`` points to the calling contract, and especially the storage from the calling contract can be accessed. As a library is an isolated piece of source code, it can only access state variables of the calling contract if they are explicitly supplied (it -would have no way to name them, otherwise). +would have no way to name them, otherwise). Library functions can only be +called directly (i.e. without the use of ``DELEGATECALL``) if they do not modify +the state (i.e. if they are ``view`` or ``pure`` functions), +because libraries are assumed to be stateless. In particular, it is +not possible to destroy a library unless Solidity's type system is circumvented. Libraries can be seen as implicit base contracts of the contracts that use them. They will not be explicitly visible in the inheritance hierarchy, but calls @@ -1032,7 +1115,7 @@ if the library were a base contract. Of course, calls to internal functions use the internal calling convention, which means that all internal types can be passed and memory types will be passed by reference and not copied. To realize this in the EVM, code of internal library functions -and all functions called from therein will be pulled into the calling +and all functions called from therein will at compile time be pulled into the calling contract, and a regular ``JUMP`` call will be used instead of a ``DELEGATECALL``. .. index:: using for, set @@ -1043,7 +1126,7 @@ more advanced example to implement a set). :: - pragma solidity ^0.4.11; + pragma solidity ^0.4.16; library Set { // We define a new struct datatype that will be used to @@ -1054,9 +1137,10 @@ more advanced example to implement a set). // reference" and thus only its storage address and not // its contents is passed as part of the call. This is a // special feature of library functions. It is idiomatic - // to call the first parameter 'self', if the function can + // to call the first parameter `self`, if the function can // be seen as a method of that object. function insert(Data storage self, uint value) + public returns (bool) { if (self.flags[value]) @@ -1066,6 +1150,7 @@ more advanced example to implement a set). } function remove(Data storage self, uint value) + public returns (bool) { if (!self.flags[value]) @@ -1075,17 +1160,18 @@ more advanced example to implement a set). } function contains(Data storage self, uint value) + public + view returns (bool) { return self.flags[value]; } } - contract C { Set.Data knownValues; - function register(uint value) { + function register(uint value) public { // The library functions can be called without a // specific instance of the library, since the // "instance" will be the current contract. @@ -1095,7 +1181,7 @@ more advanced example to implement a set). } Of course, you do not have to follow this way to use -libraries - they can also be used without defining struct +libraries: they can also be used without defining struct data types. Functions also work without any storage reference parameters, and they can have multiple storage reference parameters and in any position. @@ -1114,19 +1200,19 @@ custom types without the overhead of external function calls: :: - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; library BigInt { struct bigint { uint[] limbs; } - function fromUint(uint x) internal returns (bigint r) { + function fromUint(uint x) internal pure returns (bigint r) { r.limbs = new uint[](1); r.limbs[0] = x; } - function add(bigint _a, bigint _b) internal returns (bigint r) { + function add(bigint _a, bigint _b) internal pure returns (bigint r) { r.limbs = new uint[](max(_a.limbs.length, _b.limbs.length)); uint carry = 0; for (uint i = 0; i < r.limbs.length; ++i) { @@ -1148,20 +1234,19 @@ custom types without the overhead of external function calls: } } - function limb(bigint _a, uint _limb) internal returns (uint) { + function limb(bigint _a, uint _limb) internal pure returns (uint) { return _limb < _a.limbs.length ? _a.limbs[_limb] : 0; } - function max(uint a, uint b) private returns (uint) { + function max(uint a, uint b) private pure returns (uint) { return a > b ? a : b; } } - contract C { using BigInt for BigInt.bigint; - function f() { + function f() public pure { var x = BigInt.fromUint(7); var y = BigInt.fromUint(uint(-1)); var z = x.add(y); @@ -1187,6 +1272,30 @@ Restrictions for libraries in comparison to contracts: (These might be lifted at a later point.) +Call Protection For Libraries +============================= + +As mentioned in the introduction, if a library's code is executed +using a ``CALL`` instead of a ``DELEGATECALL`` or ``CALLCODE``, +it will revert unless a ``view`` or ``pure`` function is called. + +The EVM does not provide a direct way for a contract to detect +whether it was called using ``CALL`` or not, but a contract +can use the ``ADDRESS`` opcode to find out "where" it is +currently running. The generated code compares this address +to the address used at construction time to determine the mode +of calling. + +More specifically, the runtime code of a library always starts +with a push instruction, which is a zero of 20 bytes at +compilation time. When the deploy code runs, this constant +is replaced in memory by the current address and this +modified code is stored in the contract. At runtime, +this causes the deploy time address to be the first +constant to be pushed onto the stack and the dispatcher +code compares the current address against this constant +for any non-view and non-pure function. + .. index:: ! using for, library .. _using-for: @@ -1219,13 +1328,14 @@ available without having to add further code. Let us rewrite the set example from the :ref:`libraries` in this way:: - pragma solidity ^0.4.11; + pragma solidity ^0.4.16; // This is the same code as before, just without comments library Set { struct Data { mapping(uint => bool) flags; } function insert(Data storage self, uint value) + public returns (bool) { if (self.flags[value]) @@ -1235,6 +1345,7 @@ Let us rewrite the set example from the } function remove(Data storage self, uint value) + public returns (bool) { if (!self.flags[value]) @@ -1244,48 +1355,52 @@ Let us rewrite the set example from the } function contains(Data storage self, uint value) + public + view returns (bool) { return self.flags[value]; } } - contract C { using Set for Set.Data; // this is the crucial change Set.Data knownValues; - function register(uint value) { + function register(uint value) public { // Here, all variables of type Set.Data have // corresponding member functions. // The following function call is identical to - // Set.insert(knownValues, value) + // `Set.insert(knownValues, value)` require(knownValues.insert(value)); } } It is also possible to extend elementary types in that way:: - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; library Search { - function indexOf(uint[] storage self, uint value) returns (uint) { + function indexOf(uint[] storage self, uint value) + public + view + returns (uint) + { for (uint i = 0; i < self.length; i++) if (self[i] == value) return i; return uint(-1); } } - contract C { using Search for uint[]; uint[] data; - function append(uint value) { + function append(uint value) public { data.push(value); } - function replace(uint _old, uint _new) { + function replace(uint _old, uint _new) public { // This performs the library function call uint index = data.indexOf(_old); if (index == uint(-1)) diff --git a/docs/contributing.rst b/docs/contributing.rst index 0f7c3e72..a5efba8b 100644 --- a/docs/contributing.rst +++ b/docs/contributing.rst @@ -50,8 +50,10 @@ and instead, ``git rebase`` your branch. Additionally, if you are writing a new feature, please ensure you write appropriate Boost test cases and place them under ``test/``. -However, if you are making a larger change, please consult with the Gitter -channel, first. +However, if you are making a larger change, please consult with the `Solidity Development Gitter channel +<https://gitter.im/ethereum/solidity-dev>`_ (different from the one mentioned above, this on is +focused on compiler and language development instead of language use) first. + Finally, please make sure you respect the `coding standards <https://raw.githubusercontent.com/ethereum/cpp-ethereum/develop/CodingStandards.txt>`_ diff --git a/docs/control-structures.rst b/docs/control-structures.rst index 0497365b..7be92cfa 100644 --- a/docs/control-structures.rst +++ b/docs/control-structures.rst @@ -20,10 +20,10 @@ For example, suppose we want our contract to accept one kind of external calls with two integers, we would write something like:: - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; contract Simple { - function taker(uint _a, uint _b) { + function taker(uint _a, uint _b) public pure { // do something with _a and _b. } } @@ -36,10 +36,14 @@ The output parameters can be declared with the same syntax after the the sum and the product of the two given integers, then we would write:: - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; contract Simple { - function arithmetics(uint _a, uint _b) returns (uint o_sum, uint o_product) { + function arithmetics(uint _a, uint _b) + public + pure + returns (uint o_sum, uint o_product) + { o_sum = _a + _b; o_product = _a * _b; } @@ -95,11 +99,11 @@ Internal Function Calls Functions of the current contract can be called directly ("internally"), also recursively, as seen in this nonsensical example:: - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; contract C { - function g(uint a) returns (uint ret) { return f(); } - function f() returns (uint ret) { return g(7) + f(); } + function g(uint a) public pure returns (uint ret) { return f(); } + function f() internal pure returns (uint ret) { return g(7) + f(); } } These function calls are translated into simple jumps inside the EVM. This has @@ -125,13 +129,13 @@ the gas can be specified with special options ``.value()`` and ``.gas()``, respe pragma solidity ^0.4.0; contract InfoFeed { - function info() payable returns (uint ret) { return 42; } + function info() public payable returns (uint ret) { return 42; } } contract Consumer { InfoFeed feed; - function setFeed(address addr) { feed = InfoFeed(addr); } - function callFeed() { feed.info.value(10).gas(800)(); } + function setFeed(address addr) public { feed = InfoFeed(addr); } + function callFeed() public { feed.info.value(10).gas(800)(); } } The modifier ``payable`` has to be used for ``info``, because otherwise, the `.value()` @@ -180,11 +184,11 @@ parameters from the function declaration, but can be in arbitrary order. pragma solidity ^0.4.0; contract C { - function f(uint key, uint value) { + function f(uint key, uint value) public { // ... } - function g() { + function g() public { // named arguments f({value: 2, key: 3}); } @@ -194,15 +198,15 @@ Omitted Function Parameter Names -------------------------------- The names of unused parameters (especially return parameters) can be omitted. -Those names will still be present on the stack, but they are inaccessible. +Those parameters will still be present on the stack, but they are inaccessible. :: - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; contract C { // omitted name for parameter - function func(uint k, uint) returns(uint) { + function func(uint k, uint) public pure returns(uint) { return k; } } @@ -225,7 +229,7 @@ creation-dependencies are not possible. contract D { uint x; - function D(uint a) payable { + function D(uint a) public payable { x = a; } } @@ -233,11 +237,11 @@ creation-dependencies are not possible. contract C { D d = new D(4); // will be executed as part of C's constructor - function createD(uint arg) { + function createD(uint arg) public { D newD = new D(arg); } - function createAndEndowD(uint arg, uint amount) payable { + function createAndEndowD(uint arg, uint amount) public payable { // Send ether along with the creation D newD = (new D).value(amount)(arg); } @@ -270,16 +274,16 @@ Destructuring Assignments and Returning Multiple Values Solidity internally allows tuple types, i.e. a list of objects of potentially different types whose size is a constant at compile-time. Those tuples can be used to return multiple values at the same time and also assign them to multiple variables (or LValues in general) at the same time:: - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; contract C { uint[] data; - function f() returns (uint, bool, uint) { + function f() public pure returns (uint, bool, uint) { return (7, true, 2); } - function g() { + function g() public { // Declares and assigns the variables. Specifying the type explicitly is not possible. var (x, b, y) = f(); // Assigns to a pre-existing variable. @@ -291,6 +295,7 @@ Solidity internally allows tuple types, i.e. a list of objects of potentially di // the rest of the values are discarded. (data.length,) = f(); // Sets the length to 7 // The same can be done on the left side. + // If the tuple begins in an empty component, the beginning values are discarded. (,data[3]) = f(); // Sets data[3] to 2 // Components can only be left out at the left-hand-side of assignments, with // one exception: @@ -326,10 +331,10 @@ As a result, the following code is illegal and cause the compiler to throw an er // This will not compile - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; contract ScopingErrors { - function scoping() { + function scoping() public { uint i = 0; while (i++ < 1) { @@ -341,7 +346,7 @@ As a result, the following code is illegal and cause the compiler to throw an er } } - function minimalScoping() { + function minimalScoping() public { { uint same2 = 0; } @@ -351,7 +356,7 @@ As a result, the following code is illegal and cause the compiler to throw an er } } - function forLoopScoping() { + function forLoopScoping() public { for (uint same3 = 0; same3 < 1; same3++) { } @@ -363,15 +368,19 @@ As a result, the following code is illegal and cause the compiler to throw an er In addition to this, if a variable is declared, it will be initialized at the beginning of the function to its default value. As a result, the following code is legal, despite being poorly written:: - function foo() returns (uint) { - // baz is implicitly initialized as 0 - uint bar = 5; - if (true) { - bar += baz; - } else { - uint baz = 10;// never executes + pragma solidity ^0.4.0; + + contract C { + function foo() public pure returns (uint) { + // baz is implicitly initialized as 0 + uint bar = 5; + if (true) { + bar += baz; + } else { + uint baz = 10;// never executes + } + return bar;// returns 5 } - return bar;// returns 5 } .. index:: ! exception, ! throw, ! assert, ! require, ! revert @@ -398,7 +407,7 @@ and the low-level functions ``call``, ``delegatecall`` and ``callcode`` -- those of an exception instead of "bubbling up". .. warning:: - The low-level ``call``, ``delegatecall`` and ``callcode`` will return success if the calling account is non-existent, as part of the design of EVM. Existence must be checked prior to calling if desired. + The low-level ``call``, ``delegatecall`` and ``callcode`` will return success if the called account is non-existent, as part of the design of EVM. Existence must be checked prior to calling if desired. Catching exceptions is not yet possible. @@ -408,7 +417,7 @@ and how ``assert`` can be used for internal error checking:: pragma solidity ^0.4.0; contract Sharer { - function sendHalf(address addr) payable returns (uint balance) { + function sendHalf(address addr) public payable returns (uint balance) { require(msg.value % 2 == 0); // Only allow even numbers uint balanceBeforeTransfer = this.balance; addr.transfer(msg.value / 2); diff --git a/docs/frequently-asked-questions.rst b/docs/frequently-asked-questions.rst index 5c427c69..a6bead29 100644 --- a/docs/frequently-asked-questions.rst +++ b/docs/frequently-asked-questions.rst @@ -39,12 +39,13 @@ This is just the bytecode "data" sent along with the request. Is there a decompiler available? ================================ -There is no decompiler to Solidity. This is in principle possible -to some degree, but for example variable names will be lost and -great effort will be necessary to make it look similar to -the original source code. +There is no exact decompiler to Solidity, but +`Porosity <https://github.com/comaeio/porosity>`_ is close. +Because some information like variable names, comments, and +source code formatting is lost in the compilation process, +it is not possible to completely recover the original source code. -Bytecode can be decompiled to opcodes, a service that is provided by +Bytecode can be disassembled to opcodes, a service that is provided by several blockchain explorers. Contracts on the blockchain should have their original source @@ -111,10 +112,10 @@ array in the return statement. Pretty cool, huh? Example:: - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; contract C { - function f() returns (uint8[5]) { + function f() public pure returns (uint8[5]) { string[4] memory adaArr = ["This", "is", "an", "array"]; return ([1, 2, 3, 4, 5]); } @@ -190,11 +191,11 @@ you should always convert it to a ``bytes`` first:: contract C { string s; - function append(byte c) { + function append(byte c) public { bytes(s).push(c); } - function set(uint i, byte c) { + function set(uint i, byte c) public { bytes(s)[i] = c; } } @@ -232,12 +233,14 @@ situation. If you do not want to throw, you can return a pair:: - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; contract C { uint[] counters; function getCounter(uint index) + public + view returns (uint counter, bool error) { if (index >= counters.length) return (0, true); @@ -245,7 +248,7 @@ If you do not want to throw, you can return a pair:: return (counters[index], false); } - function checkCounter(uint index) { + function checkCounter(uint index) public view { var (counter, error) = getCounter(index); if (error) { // ... @@ -316,11 +319,11 @@ Example:: uint[] data1; uint[] data2; - function appendOne() { + function appendOne() public { append(data1); } - function appendTwo() { + function appendTwo() public { append(data2); } @@ -349,7 +352,7 @@ be created in memory, although it will be created in storage:: uint someVariable; uint[] data; - function f() { + function f() public { uint[] x; x.push(2); data = x; @@ -375,7 +378,7 @@ The correct way to do this is the following:: uint someVariable; uint[] data; - function f() { + function f() public { uint[] x = data; x.push(2); } @@ -431,14 +434,14 @@ What happens to a ``struct``'s mapping when copying over a ``struct``? This is a very interesting question. Suppose that we have a contract field set up like such:: - struct user { + struct User { mapping(string => string) comments; } - function somefunction { - user user1; + function somefunction public { + User user1; user1.comments["Hello"] = "World"; - user user2 = user1; + User user2 = user1; } In this case, the mapping of the struct being copied over into the userList is ignored as there is no "list of mapped keys". @@ -456,13 +459,13 @@ In this example:: pragma solidity ^0.4.0; contract B { - function B() payable {} + function B() public payable {} } contract A { address child; - function test() { + function test() public { child = (new B).value(10)(); //construct a new B with 10 wei } } @@ -501,17 +504,17 @@ Can a contract pass an array (static size) or string or ``bytes`` (dynamic size) Sure. Take care that if you cross the memory / storage boundary, independent copies will be created:: - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; contract C { uint[20] x; - function f() { + function f() public { g(x); h(x); } - function g(uint[20] y) internal { + function g(uint[20] y) internal pure { y[2] = 3; } diff --git a/docs/grammar.txt b/docs/grammar.txt index 72364b7c..e700c946 100644 --- a/docs/grammar.txt +++ b/docs/grammar.txt @@ -27,14 +27,19 @@ ModifierInvocation = Identifier ( '(' ExpressionList? ')' )? FunctionDefinition = 'function' Identifier? ParameterList ( ModifierInvocation | StateMutability | 'external' | 'public' | 'internal' | 'private' )* ( 'returns' ParameterList )? ( ';' | Block ) -EventDefinition = 'event' Identifier IndexedParameterList 'anonymous'? ';' +EventDefinition = 'event' Identifier EventParameterList 'anonymous'? ';' EnumValue = Identifier EnumDefinition = 'enum' Identifier '{' EnumValue? (',' EnumValue)* '}' -IndexedParameterList = '(' ( TypeName 'indexed'? Identifier? (',' TypeName 'indexed'? Identifier?)* )? ')' -ParameterList = '(' ( TypeName Identifier? (',' TypeName Identifier?)* )? ')' -TypeNameList = '(' ( TypeName (',' TypeName )* )? ')' +ParameterList = '(' ( Parameter (',' Parameter)* )? ')' +Parameter = TypeName StorageLocation? Identifier? + +EventParameterList = '(' ( EventParameter (',' EventParameter )* )? ')' +EventParameter = TypeName 'indexed'? Identifier? + +FunctionTypeParameterList = '(' ( FunctionTypeParameter (',' FunctionTypeParameter )* )? ')' +FunctionTypeParameter = TypeName StorageLocation? // semantic restriction: mappings and structs (recursively) containing mappings // are not allowed in argument lists @@ -50,8 +55,8 @@ UserDefinedTypeName = Identifier ( '.' Identifier )* Mapping = 'mapping' '(' ElementaryTypeName '=>' TypeName ')' ArrayTypeName = TypeName '[' Expression? ']' -FunctionTypeName = 'function' TypeNameList ( 'internal' | 'external' | StateMutability )* - ( 'returns' TypeNameList )? +FunctionTypeName = 'function' FunctionTypeParameterList ( 'internal' | 'external' | StateMutability )* + ( 'returns' FunctionTypeParameterList )? StorageLocation = 'memory' | 'storage' StateMutability = 'pure' | 'constant' | 'view' | 'payable' @@ -127,10 +132,10 @@ StringLiteral = '"' ([^"\r\n\\] | '\\' .)* '"' Identifier = [a-zA-Z_$] [a-zA-Z_$0-9]* HexNumber = '0x' [0-9a-fA-F]+ -DecimalNumber = [0-9]+ +DecimalNumber = [0-9]+ ( '.' [0-9]* )? ( [eE] [0-9]+ )? -TupleExpression = '(' ( Expression ( ',' Expression )* )? ')' - | '[' ( Expression ( ',' Expression )* )? ']' +TupleExpression = '(' ( Expression? ( ',' Expression? )* )? ')' + | '[' ( Expression ( ',' Expression )* )? ']' ElementaryTypeNameExpression = ElementaryTypeName @@ -143,9 +148,9 @@ Uint = 'uint' | 'uint8' | 'uint16' | 'uint24' | 'uint32' | 'uint40' | 'uint48' | Byte = 'byte' | 'bytes' | 'bytes1' | 'bytes2' | 'bytes3' | 'bytes4' | 'bytes5' | 'bytes6' | 'bytes7' | 'bytes8' | 'bytes9' | 'bytes10' | 'bytes11' | 'bytes12' | 'bytes13' | 'bytes14' | 'bytes15' | 'bytes16' | 'bytes17' | 'bytes18' | 'bytes19' | 'bytes20' | 'bytes21' | 'bytes22' | 'bytes23' | 'bytes24' | 'bytes25' | 'bytes26' | 'bytes27' | 'bytes28' | 'bytes29' | 'bytes30' | 'bytes31' | 'bytes32' -Fixed = 'fixed' | ( 'fixed' DecimalNumber 'x' DecimalNumber ) +Fixed = 'fixed' | ( 'fixed' [0-9]+ 'x' [0-9]+ ) -Ufixed = 'ufixed' | ( 'ufixed' DecimalNumber 'x' DecimalNumber ) +Ufixed = 'ufixed' | ( 'ufixed' [0-9]+ 'x' [0-9]+ ) InlineAssemblyBlock = '{' AssemblyItem* '}' diff --git a/docs/index.rst b/docs/index.rst index 351f8ad7..3df0af3c 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -6,8 +6,9 @@ Solidity :alt: Solidity logo :align: center -Solidity is a contract-oriented, high-level language whose syntax is similar to that of JavaScript -and it is designed to target the Ethereum Virtual Machine (EVM). +Solidity is a contract-oriented, high-level language for implementing smart contracts. +It was influenced by C++, Python and JavaScript +and is designed to target the Ethereum Virtual Machine (EVM). Solidity is statically typed, supports inheritance, libraries and complex user-defined types among other features. @@ -20,6 +21,23 @@ crowdfunding, blind auctions, multi-signature wallets and more. `Remix <https://remix.ethereum.org/>`_ (it can take a while to load, please be patient). +.. warning:: + Since software is written by humans, it can have bugs. Thus, also + smart contracts should be created following well-known best-practices in + software development. This includes code review, testing, audits and correctness proofs. + Also note that users are sometimes more confident in code than its authors. + Finally, blockchains have their own things to watch out for, so please take + a look at the section :ref:`security_considerations`. + +Translations +------------ + +This documentation is translated into several languages by community volunteers, but the English version stands as a reference. + +* `Spanish <https://solidity-es.readthedocs.io>`_ +* `Russian <https://github.com/ethereum/wiki/wiki/%5BRussian%5D-%D0%A0%D1%83%D0%BA%D0%BE%D0%B2%D0%BE%D0%B4%D1%81%D1%82%D0%B2%D0%BE-%D0%BF%D0%BE-Solidity>`_ (rather outdated) + + Useful links ------------ @@ -60,7 +78,7 @@ Available Solidity Integrations Configurable Solidty linter for Atom using Solium as a base. * `Solium <https://github.com/duaraghav8/Solium/>`_ - A commandline linter for Solidity which strictly follows the rules prescribed by the `Solidity Style Guide <http://solidity.readthedocs.io/en/latest/style-guide.html>`_. + Linter to identify and fix style and security issues in Solidity. * `Solhint <https://github.com/protofire/solhint>`_ Solidity linter that provides security, style guide and best practice rules for smart contract validation. @@ -131,8 +149,6 @@ If you still have questions, you can try searching or asking on the site, or come to our `gitter channel <https://gitter.im/ethereum/solidity/>`_. Ideas for improving Solidity or this documentation are always welcome! -See also `Russian version (русский перевод) <https://github.com/ethereum/wiki/wiki/%5BRussian%5D-%D0%A0%D1%83%D0%BA%D0%BE%D0%B2%D0%BE%D0%B4%D1%81%D1%82%D0%B2%D0%BE-%D0%BF%D0%BE-Solidity>`_. - Contents ======== @@ -149,6 +165,7 @@ Contents using-the-compiler.rst metadata.rst abi-spec.rst + julia.rst style-guide.rst common-patterns.rst bugs.rst diff --git a/docs/installing-solidity.rst b/docs/installing-solidity.rst index b660cf02..8f30f199 100644 --- a/docs/installing-solidity.rst +++ b/docs/installing-solidity.rst @@ -2,9 +2,9 @@ .. _installing-solidity: -################### -Installing Solidity -################### +################################ +Installing the Solidity Compiler +################################ Versioning ========== @@ -18,30 +18,38 @@ will use the latest release. Remix ===== -If you just want to try Solidity for small contracts, you -can try `Remix <https://remix.ethereum.org/>`_ -which does not need any installation. If you want to use it -without connection to the Internet, you can go to -https://github.com/ethereum/browser-solidity/tree/gh-pages and -download the .ZIP file as explained on that page. +*We recommend Remix for small contracts and for quickly learning Solidity.* + +`Access Remix online <https://remix.ethereum.org/>`_, you don't need to install anything. +If you want to use it without connection to the Internet, go to +https://github.com/ethereum/browser-solidity/tree/gh-pages and download the .ZIP file as +explained on that page. + +Further options on this page detail installing commandline Solidity compiler software +on your computer. Choose a commandline compiler if you are working on a larger contract +or if you require more compilation options. npm / Node.js ============= -This is probably the most portable and most convenient way to install Solidity locally. +Use `npm` for a convenient and portable way to install `solcjs`, a Solidity compiler. The +`solcjs` program has less features than all options further down this page. Our +`Using the compiler <using-the-compiler.html>` documentation assumes you are using +the full-featured compiler, `solc`. So if you install `solcjs` from `npm` then you will +stop reading the documentation here and then continue to <https://github.com/ethereum/solc-js>, -A platform-independent JavaScript library is provided by compiling the C++ source -into JavaScript using Emscripten. It can be used in projects directly (such as Remix). +Note: The `solc-js <https://github.com/ethereum/solc-js>` project is derived from the C++ +`solc` by using Emscripten. `solc-js` can be used in JavaScript projects directly (such as Remix). Please refer to the `solc-js <https://github.com/ethereum/solc-js>`_ repository for instructions. -It also contains a commandline tool called `solcjs`, which can be installed via npm: - .. code:: bash npm install -g solc .. note:: + The commandline is named `solcjs`. + The comandline options of `solcjs` are not compatible with `solc` and tools (such as `geth`) expecting the behaviour of `solc` will not work with `solcjs`. @@ -63,7 +71,7 @@ output directories. Binary Packages =============== -Binary packages of Solidity available at +Binary packages of Solidity are available at `solidity/releases <https://github.com/ethereum/solidity/releases>`_. We also have PPAs for Ubuntu. For the latest stable version. diff --git a/docs/introduction-to-smart-contracts.rst b/docs/introduction-to-smart-contracts.rst index aedc0c09..c297a8ad 100644 --- a/docs/introduction-to-smart-contracts.rst +++ b/docs/introduction-to-smart-contracts.rst @@ -21,11 +21,11 @@ Storage contract SimpleStorage { uint storedData; - function set(uint x) { + function set(uint x) public { storedData = x; } - function get() constant returns (uint) { + function get() public constant returns (uint) { return storedData; } } @@ -94,16 +94,16 @@ registering with username and password - all you need is an Ethereum keypair. // This is the constructor whose code is // run only when the contract is created. - function Coin() { + function Coin() public { minter = msg.sender; } - function mint(address receiver, uint amount) { + function mint(address receiver, uint amount) public { if (msg.sender != minter) return; balances[receiver] += amount; } - function send(address receiver, uint amount) { + function send(address receiver, uint amount) public { if (balances[msg.sender] < amount) return; balances[msg.sender] -= amount; balances[receiver] += amount; @@ -118,9 +118,11 @@ that is publicly accessible. The ``address`` type is a 160-bit value that does not allow any arithmetic operations. It is suitable for storing addresses of contracts or keypairs belonging to external persons. The keyword ``public`` automatically generates a function that -allows you to access the current value of the state variable. +allows you to access the current value of the state variable +from outside of the contract. Without this keyword, other contracts have no way to access the variable. -The function will look something like this:: +The code of the function generated by the compiler is roughly equivalent +to the following:: function minter() returns (address) { return minter; } @@ -145,7 +147,7 @@ like this one. The :ref:`getter function<getter-functions>` created by the ``pub is a bit more complex in this case. It roughly looks like the following:: - function balances(address _account) returns (uint) { + function balances(address _account) public view returns (uint) { return balances[_account]; } diff --git a/docs/julia.rst b/docs/julia.rst new file mode 100644 index 00000000..9e961a9d --- /dev/null +++ b/docs/julia.rst @@ -0,0 +1,571 @@ +################################################# +Joyfully Universal Language for (Inline) Assembly +################################################# + +.. _julia: + +.. index:: ! assembly, ! asm, ! evmasm, ! julia + +JULIA is an intermediate language that can compile to various different backends +(EVM 1.0, EVM 1.5 and eWASM are planned). +Because of that, it is designed to be a usable common denominator of all three +platforms. +It can already be used for "inline assembly" inside Solidity and +future versions of the Solidity compiler will even use JULIA as intermediate +language. It should also be easy to build high-level optimizer stages for JULIA. + +.. note:: + + Note that the flavour used for "inline assembly" does not have types + (everything is ``u256``) and the built-in functions are identical + to the EVM opcodes. Please resort to the inline assembly documentation + for details. + +The core components of JULIA are functions, blocks, variables, literals, +for-loops, if-statements, switch-statements, expressions and assignments to variables. + +JULIA is typed, both variables and literals must specify the type with postfix +notation. The supported types are ``bool``, ``u8``, ``s8``, ``u32``, ``s32``, +``u64``, ``s64``, ``u128``, ``s128``, ``u256`` and ``s256``. + +JULIA in itself does not even provide operators. If the EVM is targeted, +opcodes will be available as built-in functions, but they can be reimplemented +if the backend changes. For a list of mandatory built-in functions, see the section below. + +The following example program assumes that the EVM opcodes ``mul``, ``div`` +and ``mod`` are available either natively or as functions and computes exponentiation. + +.. code:: + + { + function power(base:u256, exponent:u256) -> result:u256 + { + switch exponent + case 0:u256 { result := 1:u256 } + case 1:u256 { result := base } + default: + { + result := power(mul(base, base), div(exponent, 2:u256)) + switch mod(exponent, 2:u256) + case 1:u256 { result := mul(base, result) } + } + } + } + +It is also possible to implement the same function using a for-loop +instead of with recursion. Here, we need the EVM opcodes ``lt`` (less-than) +and ``add`` to be available. + +.. code:: + + { + function power(base:u256, exponent:u256) -> result:u256 + { + result := 1:u256 + for { let i := 0:u256 } lt(i, exponent) { i := add(i, 1:u256) } + { + result := mul(result, base) + } + } + } + +Specification of JULIA +====================== + +JULIA code is described in this chapter. JULIA code is usually placed into a JULIA object, which is described in the following chapter. + +Grammar:: + + Block = '{' Statement* '}' + Statement = + Block | + FunctionDefinition | + VariableDeclaration | + Assignment | + Expression | + Switch | + ForLoop | + BreakContinue + FunctionDefinition = + 'function' Identifier '(' TypedIdentifierList? ')' + ( '->' TypedIdentifierList )? Block + VariableDeclaration = + 'let' TypedIdentifierList ( ':=' Expression )? + Assignment = + IdentifierList ':=' Expression + Expression = + FunctionCall | Identifier | Literal + If = + 'if' Expression Block + Switch = + 'switch' Expression Case* ( 'default' Block )? + Case = + 'case' Literal Block + ForLoop = + 'for' Block Expression Block Block + BreakContinue = + 'break' | 'continue' + FunctionCall = + Identifier '(' ( Expression ( ',' Expression )* )? ')' + Identifier = [a-zA-Z_$] [a-zA-Z_0-9]* + IdentifierList = Identifier ( ',' Identifier)* + TypeName = Identifier | BuiltinTypeName + BuiltinTypeName = 'bool' | [us] ( '8' | '32' | '64' | '128' | '256' ) + TypedIdentifierList = Identifier ':' TypeName ( ',' Identifier ':' TypeName )* + Literal = + (NumberLiteral | StringLiteral | HexLiteral | TrueLiteral | FalseLiteral) ':' TypeName + NumberLiteral = HexNumber | DecimalNumber + HexLiteral = 'hex' ('"' ([0-9a-fA-F]{2})* '"' | '\'' ([0-9a-fA-F]{2})* '\'') + StringLiteral = '"' ([^"\r\n\\] | '\\' .)* '"' + TrueLiteral = 'true' + FalseLiteral = 'false' + HexNumber = '0x' [0-9a-fA-F]+ + DecimalNumber = [0-9]+ + +Restrictions on the Grammar +--------------------------- + +Switches must have at least one case (including the default case). +If all possible values of the expression is covered, the default case should +not be allowed (i.e. a switch with a ``bool`` expression and having both a +true and false case should not allow a default case). + +Every expression evaluates to zero or more values. Identifiers and Literals +evaluate to exactly +one value and function calls evaluate to a number of values equal to the +number of return values of the function called. + +In variable declarations and assignments, the right-hand-side expression +(if present) has to evaluate to a number of values equal to the number of +variables on the left-hand-side. +This is the only situation where an expression evaluating +to more than one value is allowed. + +Expressions that are also statements (i.e. at the block level) have to +evaluate to zero values. + +In all other situations, expressions have to evaluate to exactly one value. + +The ``continue`` and ``break`` statements can only be used inside loop bodies +and have to be in the same function as the loop (or both have to be at the +top level). +The condition part of the for-loop has to evaluate to exactly one value. + +Literals cannot be larger than the their type. The largest type defined is 256-bit wide. + +Scoping Rules +------------- + +Scopes in JULIA are tied to Blocks (exceptions are functions and the for loop +as explained below) and all declarations +(``FunctionDefinition``, ``VariableDeclaration``) +introduce new identifiers into these scopes. + +Identifiers are visible in +the block they are defined in (including all sub-nodes and sub-blocks). +As an exception, identifiers defined in the "init" part of the for-loop +(the first block) are visible in all other parts of the for-loop +(but not outside of the loop). +Identifiers declared in the other parts of the for loop respect the regular +syntatical scoping rules. +The parameters and return parameters of functions are visible in the +function body and their names cannot overlap. + +Variables can only be referenced after their declaration. In particular, +variables cannot be referenced in the right hand side of their own variable +declaration. +Functions can be referenced already before their declaration (if they are visible). + +Shadowing is disallowed, i.e. you cannot declare an identifier at a point +where another identifier with the same name is also visible, even if it is +not accessible. + +Inside functions, it is not possible to access a variable that was declared +outside of that function. + +Formal Specification +-------------------- + +We formally specify JULIA by providing an evaluation function E overloaded +on the various nodes of the AST. Any functions can have side effects, so +E takes two state objects and the AST node and returns two new +state objects and a variable number of other values. +The two state objects are the global state object +(which in the context of the EVM is the memory, storage and state of the +blockchain) and the local state object (the state of local variables, i.e. a +segment of the stack in the EVM). +If the AST node is a statement, E returns the two state objects and a "mode", +which is used for the ``break`` and ``continue`` statements. +If the AST node is an expression, E returns the two state objects and +as many values as the expression evaluates to. + + +The exact nature of the global state is unspecified for this high level +description. The local state ``L`` is a mapping of identifiers ``i`` to values ``v``, +denoted as ``L[i] = v``. + +For an identifier ``v``, let ``$v`` be the name of the identifier. + +We will use a destructuring notation for the AST nodes. + +.. code:: + + E(G, L, <{St1, ..., Stn}>: Block) = + let G1, L1, mode = E(G, L, St1, ..., Stn) + let L2 be a restriction of L1 to the identifiers of L + G1, L2, mode + E(G, L, St1, ..., Stn: Statement) = + if n is zero: + G, L, regular + else: + let G1, L1, mode = E(G, L, St1) + if mode is regular then + E(G1, L1, St2, ..., Stn) + otherwise + G1, L1, mode + E(G, L, FunctionDefinition) = + G, L, regular + E(G, L, <let var1, ..., varn := rhs>: VariableDeclaration) = + E(G, L, <var1, ..., varn := rhs>: Assignment) + E(G, L, <let var1, ..., varn>: VariableDeclaration) = + let L1 be a copy of L where L1[$vari] = 0 for i = 1, ..., n + G, L1, regular + E(G, L, <var1, ..., varn := rhs>: Assignment) = + let G1, L1, v1, ..., vn = E(G, L, rhs) + let L2 be a copy of L1 where L2[$vari] = vi for i = 1, ..., n + G, L2, regular + E(G, L, <for { i1, ..., in } condition post body>: ForLoop) = + if n >= 1: + let G1, L1, mode = E(G, L, i1, ..., in) + // mode has to be regular due to the syntactic restrictions + let G2, L2, mode = E(G1, L1, for {} condition post body) + // mode has to be regular due to the syntactic restrictions + let L3 be the restriction of L2 to only variables of L + G2, L3, regular + else: + let G1, L1, v = E(G, L, condition) + if v is false: + G1, L1, regular + else: + let G2, L2, mode = E(G1, L, body) + if mode is break: + G2, L2, regular + else: + G3, L3, mode = E(G2, L2, post) + E(G3, L3, for {} condition post body) + E(G, L, break: BreakContinue) = + G, L, break + E(G, L, continue: BreakContinue) = + G, L, continue + E(G, L, <if condition body>: If) = + let G0, L0, v = E(G, L, condition) + if v is true: + E(G0, L0, body) + else: + G0, L0, regular + E(G, L, <switch condition case l1:t1 st1 ... case ln:tn stn>: Switch) = + E(G, L, switch condition case l1:t1 st1 ... case ln:tn stn default {}) + E(G, L, <switch condition case l1:t1 st1 ... case ln:tn stn default st'>: Switch) = + let G0, L0, v = E(G, L, condition) + // i = 1 .. n + // Evaluate literals, context doesn't matter + let _, _, v1 = E(G0, L0, l1) + ... + let _, _, vn = E(G0, L0, ln) + if there exists smallest i such that vi = v: + E(G0, L0, sti) + else: + E(G0, L0, st') + + E(G, L, <name>: Identifier) = + G, L, L[$name] + E(G, L, <fname(arg1, ..., argn)>: FunctionCall) = + G1, L1, vn = E(G, L, argn) + ... + G(n-1), L(n-1), v2 = E(G(n-2), L(n-2), arg2) + Gn, Ln, v1 = E(G(n-1), L(n-1), arg1) + Let <function fname (param1, ..., paramn) -> ret1, ..., retm block> + be the function of name $fname visible at the point of the call. + Let L' be a new local state such that + L'[$parami] = vi and L'[$reti] = 0 for all i. + Let G'', L'', mode = E(Gn, L', block) + G'', Ln, L''[$ret1], ..., L''[$retm] + E(G, L, l: HexLiteral) = G, L, hexString(l), + where hexString decodes l from hex and left-aligns it into 32 bytes + E(G, L, l: StringLiteral) = G, L, utf8EncodeLeftAligned(l), + where utf8EncodeLeftAligned performs a utf8 encoding of l + and aligns it left into 32 bytes + E(G, L, n: HexNumber) = G, L, hex(n) + where hex is the hexadecimal decoding function + E(G, L, n: DecimalNumber) = G, L, dec(n), + where dec is the decimal decoding function + +Type Conversion Functions +------------------------- + +JULIA has no support for implicit type conversion and therefore functions exists to provide explicit conversion. +When converting a larger type to a shorter type a runtime exception can occur in case of an overflow. + +The following type conversion functions must be available: +- ``u32tobool(x:u32) -> y:bool`` +- ``booltou32(x:bool) -> y:u32`` +- ``u32tou64(x:u32) -> y:u64`` +- ``u64tou32(x:u64) -> y:u32`` +- etc. (TBD) + +Low-level Functions +------------------- + +The following functions must be available: + ++---------------------------------------------------------------------------------------------------------------+ +| *Arithmetics* | ++---------------------------------------------------------------------------------------------------------------+ +| addu256(x:u256, y:u256) -> z:u256 | x + y | ++---------------------------------------------------------------------------------------------------------------+ +| subu256(x:u256, y:u256) -> z:u256 | x - y | ++---------------------------------------------------------------------------------------------------------------+ +| mulu256(x:u256, y:u256) -> z:u256 | x * y | ++---------------------------------------------------------------------------------------------------------------+ +| divu256(x:u256, y:u256) -> z:u256 | x / y | ++---------------------------------------------------------------------------------------------------------------+ +| divs256(x:s256, y:s256) -> z:s256 | x / y, for signed numbers in two's complement | ++---------------------------------------------------------------------------------------------------------------+ +| modu256(x:u256, y:u256) -> z:u256 | x % y | ++---------------------------------------------------------------------------------------------------------------+ +| mods256(x:s256, y:s256) -> z:s256 | x % y, for signed numbers in two's complement | ++---------------------------------------------------------------------------------------------------------------+ +| signextendu256(i:u256, x:u256) -> z:u256 | sign extend from (i*8+7)th bit counting from least significant | ++---------------------------------------------------------------------------------------------------------------+ +| expu256(x:u256, y:u256) -> z:u256 | x to the power of y | ++---------------------------------------------------------------------------------------------------------------+ +| addmodu256(x:u256, y:u256, m:u256) -> z:u256| (x + y) % m with arbitrary precision arithmetics | ++---------------------------------------------------------------------------------------------------------------+ +| mulmodu256(x:u256, y:u256, m:u256) -> z:u256| (x * y) % m with arbitrary precision arithmetics | ++---------------------------------------------------------------------------------------------------------------+ +| ltu256(x:u256, y:u256) -> z:bool | 1 if x < y, 0 otherwise | ++---------------------------------------------------------------------------------------------------------------+ +| gtu256(x:u256, y:u256) -> z:bool | 1 if x > y, 0 otherwise | ++---------------------------------------------------------------------------------------------------------------+ +| sltu256(x:s256, y:s256) -> z:bool | 1 if x < y, 0 otherwise, for signed numbers in two's complement | ++---------------------------------------------------------------------------------------------------------------+ +| sgtu256(x:s256, y:s256) -> z:bool | 1 if x > y, 0 otherwise, for signed numbers in two's complement | ++---------------------------------------------------------------------------------------------------------------+ +| equ256(x:u256, y:u256) -> z:bool | 1 if x == y, 0 otherwise | ++---------------------------------------------------------------------------------------------------------------+ +| notu256(x:u256) -> z:u256 | ~x, every bit of x is negated | ++---------------------------------------------------------------------------------------------------------------+ +| andu256(x:u256, y:u256) -> z:u256 | bitwise and of x and y | ++---------------------------------------------------------------------------------------------------------------+ +| oru256(x:u256, y:u256) -> z:u256 | bitwise or of x and y | ++---------------------------------------------------------------------------------------------------------------+ +| xoru256(x:u256, y:u256) -> z:u256 | bitwise xor of x and y | ++---------------------------------------------------------------------------------------------------------------+ +| shlu256(x:u256, y:u256) -> z:u256 | logical left shift of x by y | ++---------------------------------------------------------------------------------------------------------------+ +| shru256(x:u256, y:u256) -> z:u256 | logical right shift of x by y | ++---------------------------------------------------------------------------------------------------------------+ +| saru256(x:u256, y:u256) -> z:u256 | arithmetic right shift of x by y | ++---------------------------------------------------------------------------------------------------------------+ +| byte(n:u256, x:u256) -> v:u256 | nth byte of x, where the most significant byte is the 0th byte | +| Cannot this be just replaced by and256(shr256(n, x), 0xff) and let it be optimised out by the EVM backend? | ++---------------------------------------------------------------------------------------------------------------+ +| *Memory and storage* | ++---------------------------------------------------------------------------------------------------------------+ +| mload(p:u256) -> v:u256 | mem[p..(p+32)) | ++---------------------------------------------------------------------------------------------------------------+ +| mstore(p:u256, v:u256) | mem[p..(p+32)) := v | ++---------------------------------------------------------------------------------------------------------------+ +| mstore8(p:u256, v:u256) | mem[p] := v & 0xff - only modifies a single byte | ++---------------------------------------------------------------------------------------------------------------+ +| sload(p:u256) -> v:u256 | storage[p] | ++---------------------------------------------------------------------------------------------------------------+ +| sstore(p:u256, v:u256) | storage[p] := v | ++---------------------------------------------------------------------------------------------------------------+ +| msize() -> size:u256 | size of memory, i.e. largest accessed memory index, albeit due | +| | due to the memory extension function, which extends by words, | +| | this will always be a multiple of 32 bytes | ++---------------------------------------------------------------------------------------------------------------+ +| *Execution control* | ++---------------------------------------------------------------------------------------------------------------+ +| create(v:u256, p:u256, s:u256) | create new contract with code mem[p..(p+s)) and send v wei | +| | and return the new address | ++---------------------------------------------------------------------------------------------------------------+ +| call(g:u256, a:u256, v:u256, in:u256, | call contract at address a with input mem[in..(in+insize)) | +| insize:u256, out:u256, | providing g gas and v wei and output area | +| outsize:u256) | mem[out..(out+outsize)) returning 0 on error (eg. out of gas) | +| -> r:u256 | and 1 on success | ++---------------------------------------------------------------------------------------------------------------+ +| callcode(g:u256, a:u256, v:u256, in:u256, | identical to ``call`` but only use the code from a | +| insize:u256, out:u256, | and stay in the context of the | +| outsize:u256) -> r:u256 | current contract otherwise | ++---------------------------------------------------------------------------------------------------------------+ +| delegatecall(g:u256, a:u256, in:u256, | identical to ``callcode``, | +| insize:u256, out:u256, | but also keep ``caller`` | +| outsize:u256) -> r:u256 | and ``callvalue`` | ++---------------------------------------------------------------------------------------------------------------+ +| stop() | stop execution, identical to return(0,0) | +| Perhaps it would make sense retiring this as it equals to return(0,0). It can be an optimisation by the EVM | +| backend. | ++---------------------------------------------------------------------------------------------------------------+ +| abort() | abort (equals to invalid instruction on EVM) | ++---------------------------------------------------------------------------------------------------------------+ +| return(p:u256, s:u256) | end execution, return data mem[p..(p+s)) | ++---------------------------------------------------------------------------------------------------------------+ +| revert(p:u256, s:u256) | end execution, revert state changes, return data mem[p..(p+s)) | ++---------------------------------------------------------------------------------------------------------------+ +| selfdestruct(a:u256) | end execution, destroy current contract and send funds to a | ++---------------------------------------------------------------------------------------------------------------+ +| log0(p:u256, s:u256) | log without topics and data mem[p..(p+s)) | ++---------------------------------------------------------------------------------------------------------------+ +| log1(p:u256, s:u256, t1:u256) | log with topic t1 and data mem[p..(p+s)) | ++---------------------------------------------------------------------------------------------------------------+ +| log2(p:u256, s:u256, t1:u256, t2:u256) | log with topics t1, t2 and data mem[p..(p+s)) | ++---------------------------------------------------------------------------------------------------------------+ +| log3(p:u256, s:u256, t1:u256, t2:u256, | log with topics t, t2, t3 and data mem[p..(p+s)) | +| t3:u256) | | ++---------------------------------------------------------------------------------------------------------------+ +| log4(p:u256, s:u256, t1:u256, t2:u256, | log with topics t1, t2, t3, t4 and data mem[p..(p+s)) | +| t3:u256, t4:u256) | | ++---------------------------------------------------------------------------------------------------------------+ +| *State queries* | ++---------------------------------------------------------------------------------------------------------------+ +| blockcoinbase() -> address:u256 | current mining beneficiary | ++---------------------------------------------------------------------------------------------------------------+ +| blockdifficulty() -> difficulty:u256 | difficulty of the current block | ++---------------------------------------------------------------------------------------------------------------+ +| blockgaslimit() -> limit:u256 | block gas limit of the current block | ++---------------------------------------------------------------------------------------------------------------+ +| blockhash(b:u256) -> hash:u256 | hash of block nr b - only for last 256 blocks excluding current | ++---------------------------------------------------------------------------------------------------------------+ +| blocknumber() -> block:u256 | current block number | ++---------------------------------------------------------------------------------------------------------------+ +| blocktimestamp() -> timestamp:u256 | timestamp of the current block in seconds since the epoch | ++---------------------------------------------------------------------------------------------------------------+ +| txorigin() -> address:u256 | transaction sender | ++---------------------------------------------------------------------------------------------------------------+ +| txgasprice() -> price:u256 | gas price of the transaction | ++---------------------------------------------------------------------------------------------------------------+ +| gasleft() -> gas:u256 | gas still available to execution | ++---------------------------------------------------------------------------------------------------------------+ +| balance(a:u256) -> v:u256 | wei balance at address a | ++---------------------------------------------------------------------------------------------------------------+ +| this() -> address:u256 | address of the current contract / execution context | ++---------------------------------------------------------------------------------------------------------------+ +| caller() -> address:u256 | call sender (excluding delegatecall) | ++---------------------------------------------------------------------------------------------------------------+ +| callvalue() -> v:u256 | wei sent together with the current call | ++---------------------------------------------------------------------------------------------------------------+ +| calldataload(p:u256) -> v:u256 | call data starting from position p (32 bytes) | ++---------------------------------------------------------------------------------------------------------------+ +| calldatasize() -> v:u256 | size of call data in bytes | ++---------------------------------------------------------------------------------------------------------------+ +| calldatacopy(t:u256, f:u256, s:u256) | copy s bytes from calldata at position f to mem at position t | ++---------------------------------------------------------------------------------------------------------------+ +| codesize() -> size:u256 | size of the code of the current contract / execution context | ++---------------------------------------------------------------------------------------------------------------+ +| codecopy(t:u256, f:u256, s:u256) | copy s bytes from code at position f to mem at position t | ++---------------------------------------------------------------------------------------------------------------+ +| extcodesize(a:u256) -> size:u256 | size of the code at address a | ++---------------------------------------------------------------------------------------------------------------+ +| extcodecopy(a:u256, t:u256, f:u256, s:u256) | like codecopy(t, f, s) but take code at address a | ++---------------------------------------------------------------------------------------------------------------+ +| *Others* | ++---------------------------------------------------------------------------------------------------------------+ +| discardu256(unused:u256) | discard value | ++---------------------------------------------------------------------------------------------------------------+ +| splitu256tou64(x:u256) -> (x1:u64, x2:u64, | split u256 to four u64's | +| x3:u64, x4:u64) | | ++---------------------------------------------------------------------------------------------------------------+ +| combineu64tou256(x1:u64, x2:u64, x3:u64, | combine four u64's into a single u256 | +| x4:u64) -> (x:u256) | | ++---------------------------------------------------------------------------------------------------------------+ +| sha3(p:u256, s:u256) -> v:u256 | keccak(mem[p...(p+s))) | ++---------------------------------------------------------------------------------------------------------------+ + +Backends +-------- + +Backends or targets are the translators from JULIA to a specific bytecode. Each of the backends can expose functions +prefixed with the name of the backend. We reserve ``evm_`` and ``ewasm_`` prefixes for the two proposed backends. + +Backend: EVM +------------ + +The EVM target will have all the underlying EVM opcodes exposed with the `evm_` prefix. + +Backend: "EVM 1.5" +------------------ + +TBD + +Backend: eWASM +-------------- + +TBD + +Specification of JULIA Object +============================= + +Grammar:: + + TopLevelObject = 'object' '{' Code? ( Object | Data )* '}' + Object = 'object' StringLiteral '{' Code? ( Object | Data )* '}' + Code = 'code' Block + Data = 'data' StringLiteral HexLiteral + HexLiteral = 'hex' ('"' ([0-9a-fA-F]{2})* '"' | '\'' ([0-9a-fA-F]{2})* '\'') + StringLiteral = '"' ([^"\r\n\\] | '\\' .)* '"' + +Above, ``Block`` refers to ``Block`` in the JULIA code grammar explained in the previous chapter. + +An example JULIA Object is shown below: + +..code:: + + // Code consists of a single object. A single "code" node is the code of the object. + // Every (other) named object or data section is serialized and + // made accessible to the special built-in functions datacopy / dataoffset / datasize + object { + code { + let size = datasize("runtime") + let offset = allocate(size) + // This will turn into a memory->memory copy for eWASM and + // a codecopy for EVM + datacopy(dataoffset("runtime"), offset, size) + // this is a constructor and the runtime code is returned + return(offset, size) + } + + data "Table2" hex"4123" + + object "runtime" { + code { + // runtime code + + let size = datasize("Contract2") + let offset = allocate(size) + // This will turn into a memory->memory copy for eWASM and + // a codecopy for EVM + datacopy(dataoffset("Contract2"), offset, size) + // constructor parameter is a single number 0x1234 + mstore(add(offset, size), 0x1234) + create(offset, add(size, 32)) + } + + // Embedded object. Use case is that the outside is a factory contract, + // and Contract2 is the code to be created by the factory + object "Contract2" { + code { + // code here ... + } + + object "runtime" { + code { + // code here ... + } + } + + data "Table1" hex"4123" + } + } + } diff --git a/docs/metadata.rst b/docs/metadata.rst index dbde87e8..5e37219e 100644 --- a/docs/metadata.rst +++ b/docs/metadata.rst @@ -131,6 +131,8 @@ user interface for the contract. Furthermore, Mist can use the userdoc to display a confirmation message to the user whenever they interact with the contract. +Additional information about Ethereum Natural Specification (NatSpec) can be found `here <https://github.com/ethereum/wiki/wiki/Ethereum-Natural-Specification-Format>`_. + Usage for Source Code Verification ================================== diff --git a/docs/miscellaneous.rst b/docs/miscellaneous.rst index 1c4f918c..328ec6ea 100644 --- a/docs/miscellaneous.rst +++ b/docs/miscellaneous.rst @@ -327,8 +327,8 @@ Global Variables - ``sha256(...) returns (bytes32)``: compute the SHA-256 hash of the :ref:`(tightly packed) arguments <abi_packed_mode>` - ``ripemd160(...) returns (bytes20)``: compute the RIPEMD-160 hash of the :ref:`(tightly packed) arguments <abi_packed_mode>` - ``ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address)``: recover address associated with the public key from elliptic curve signature, return zero on error -- ``addmod(uint x, uint y, uint k) returns (uint)``: compute ``(x + y) % k`` where the addition is performed with arbitrary precision and does not wrap around at ``2**256`` -- ``mulmod(uint x, uint y, uint k) returns (uint)``: compute ``(x * y) % k`` where the multiplication is performed with arbitrary precision and does not wrap around at ``2**256`` +- ``addmod(uint x, uint y, uint k) returns (uint)``: compute ``(x + y) % k`` where the addition is performed with arbitrary precision and does not wrap around at ``2**256``. Assert that ``k != 0`` starting from version 0.5.0. +- ``mulmod(uint x, uint y, uint k) returns (uint)``: compute ``(x * y) % k`` where the multiplication is performed with arbitrary precision and does not wrap around at ``2**256``. Assert that ``k != 0`` starting from version 0.5.0. - ``this`` (current contract's type): the current contract, explicitly convertible to ``address`` - ``super``: the contract one level higher in the inheritance hierarchy - ``selfdestruct(address recipient)``: destroy the current contract, sending its funds to the given address diff --git a/docs/security-considerations.rst b/docs/security-considerations.rst index 6586cb5f..49fd7ea4 100644 --- a/docs/security-considerations.rst +++ b/docs/security-considerations.rst @@ -55,42 +55,59 @@ complete contract): :: - pragma solidity ^0.4.0; - - // THIS CONTRACT CONTAINS A BUG - DO NOT USE - contract Fund { - /// Mapping of ether shares of the contract. - mapping(address => uint) shares; - /// Withdraw your share. - function withdraw() { - if (msg.sender.send(shares[msg.sender])) - shares[msg.sender] = 0; - } - } + pragma solidity ^0.4.0; + + // THIS CONTRACT CONTAINS A BUG - DO NOT USE + contract Fund { + /// Mapping of ether shares of the contract. + mapping(address => uint) shares; + /// Withdraw your share. + function withdraw() public { + if (msg.sender.send(shares[msg.sender])) + shares[msg.sender] = 0; + } + } The problem is not too serious here because of the limited gas as part -of ``send``, but it still exposes a weakness: Ether transfer always -includes code execution, so the recipient could be a contract that calls +of ``send``, but it still exposes a weakness: Ether transfer can always +include code execution, so the recipient could be a contract that calls back into ``withdraw``. This would let it get multiple refunds and -basically retrieve all the Ether in the contract. +basically retrieve all the Ether in the contract. In particular, the +following contract will allow an attacker to refund multiple times +as it uses ``call`` which forwards all remaining gas by default: + +:: + + pragma solidity ^0.4.0; + + // THIS CONTRACT CONTAINS A BUG - DO NOT USE + contract Fund { + /// Mapping of ether shares of the contract. + mapping(address => uint) shares; + /// Withdraw your share. + function withdraw() public { + if (msg.sender.call.value(shares[msg.sender])()) + shares[msg.sender] = 0; + } + } To avoid re-entrancy, you can use the Checks-Effects-Interactions pattern as outlined further below: :: - pragma solidity ^0.4.11; + pragma solidity ^0.4.11; - contract Fund { - /// Mapping of ether shares of the contract. - mapping(address => uint) shares; - /// Withdraw your share. - function withdraw() { - var share = shares[msg.sender]; - shares[msg.sender] = 0; - msg.sender.transfer(share); - } - } + contract Fund { + /// Mapping of ether shares of the contract. + mapping(address => uint) shares; + /// Withdraw your share. + function withdraw() public { + var share = shares[msg.sender]; + shares[msg.sender] = 0; + msg.sender.transfer(share); + } + } Note that re-entrancy is not only an effect of Ether transfer but of any function call on another contract. Furthermore, you also have to take @@ -113,7 +130,7 @@ Sending and Receiving Ether - Neither contracts nor "external accounts" are currently able to prevent that someone sends them Ether. Contracts can react on and reject a regular transfer, but there are ways to move Ether without creating a message call. One way is to simply "mine to" - the contract address and the second way is using ``selfdestruct(x)``. + the contract address and the second way is using ``selfdestruct(x)``. - If a contract receives Ether (without a function being called), the fallback function is executed. If it does not have a fallback function, the Ether will be rejected (by throwing an exception). @@ -169,32 +186,34 @@ Never use tx.origin for authorization. Let's say you have a wallet contract like contract TxUserWallet { address owner; - function TxUserWallet() { + function TxUserWallet() public { owner = msg.sender; } - function transferTo(address dest, uint amount) { + function transferTo(address dest, uint amount) public { require(tx.origin == owner); dest.transfer(amount); } } -Now someone tricks you into sending ether to the address of this attack wallet:: +Now someone tricks you into sending ether to the address of this attack wallet: + +:: pragma solidity ^0.4.11; interface TxUserWallet { - function transferTo(address dest, uint amount); + function transferTo(address dest, uint amount) public; } contract TxAttackWallet { address owner; - function TxAttackWallet() { + function TxAttackWallet() public { owner = msg.sender; } - function() { + function() public { TxUserWallet(msg.sender).transferTo(owner, msg.sender.balance); } } diff --git a/docs/solidity-by-example.rst b/docs/solidity-by-example.rst index 59ab7962..b663083c 100644 --- a/docs/solidity-by-example.rst +++ b/docs/solidity-by-example.rst @@ -36,7 +36,7 @@ of votes. :: - pragma solidity ^0.4.11; + pragma solidity ^0.4.16; /// @title Voting with delegation. contract Ballot { @@ -66,7 +66,7 @@ of votes. Proposal[] public proposals; /// Create a new ballot to choose one of `proposalNames`. - function Ballot(bytes32[] proposalNames) { + function Ballot(bytes32[] proposalNames) public { chairperson = msg.sender; voters[chairperson].weight = 1; @@ -86,7 +86,7 @@ of votes. // Give `voter` the right to vote on this ballot. // May only be called by `chairperson`. - function giveRightToVote(address voter) { + function giveRightToVote(address voter) public { // If the argument of `require` evaluates to `false`, // it terminates and reverts all changes to // the state and to Ether balances. It is often @@ -99,7 +99,7 @@ of votes. } /// Delegate your vote to the voter `to`. - function delegate(address to) { + function delegate(address to) public { // assigns reference Voter storage sender = voters[msg.sender]; require(!sender.voted); @@ -140,7 +140,7 @@ of votes. /// Give your vote (including votes delegated to you) /// to proposal `proposals[proposal].name`. - function vote(uint proposal) { + function vote(uint proposal) public { Voter storage sender = voters[msg.sender]; require(!sender.voted); sender.voted = true; @@ -154,7 +154,7 @@ of votes. /// @dev Computes the winning proposal taking all /// previous votes into account. - function winningProposal() constant + function winningProposal() public view returns (uint winningProposal) { uint winningVoteCount = 0; @@ -169,7 +169,7 @@ of votes. // Calls winningProposal() function to get the index // of the winner contained in the proposals array and then // returns the name of the winner - function winnerName() constant + function winnerName() public view returns (bytes32 winnerName) { winnerName = proposals[winningProposal()].name; @@ -248,7 +248,7 @@ activate themselves. function SimpleAuction( uint _biddingTime, address _beneficiary - ) { + ) public { beneficiary = _beneficiary; auctionEnd = now + _biddingTime; } @@ -257,7 +257,7 @@ activate themselves. /// together with this transaction. /// The value will only be refunded if the /// auction is not won. - function bid() payable { + function bid() public payable { // No arguments are necessary, all // information is already part of // the transaction. The keyword payable @@ -286,7 +286,7 @@ activate themselves. } /// Withdraw a bid that was overbid. - function withdraw() returns (bool) { + function withdraw() public returns (bool) { uint amount = pendingReturns[msg.sender]; if (amount > 0) { // It is important to set this to zero because the recipient @@ -305,7 +305,7 @@ activate themselves. /// End the auction and send the highest bid /// to the beneficiary. - function auctionEnd() { + function auctionEnd() public { // It is a good guideline to structure functions that interact // with other contracts (i.e. they call functions or send Ether) // into three phases: @@ -405,7 +405,7 @@ high or low invalid bids. uint _biddingTime, uint _revealTime, address _beneficiary - ) { + ) public { beneficiary = _beneficiary; biddingEnd = now + _biddingTime; revealEnd = biddingEnd + _revealTime; @@ -421,6 +421,7 @@ high or low invalid bids. /// still make the required deposit. The same address can /// place multiple bids. function bid(bytes32 _blindedBid) + public payable onlyBefore(biddingEnd) { @@ -438,6 +439,7 @@ high or low invalid bids. bool[] _fake, bytes32[] _secret ) + public onlyAfter(biddingEnd) onlyBefore(revealEnd) { @@ -487,12 +489,12 @@ high or low invalid bids. } /// Withdraw a bid that was overbid. - function withdraw() { + function withdraw() public { uint amount = pendingReturns[msg.sender]; if (amount > 0) { // It is important to set this to zero because the recipient // can call this function again as part of the receiving call - // before `send` returns (see the remark above about + // before `transfer` returns (see the remark above about // conditions -> effects -> interaction). pendingReturns[msg.sender] = 0; @@ -503,17 +505,17 @@ high or low invalid bids. /// End the auction and send the highest bid /// to the beneficiary. function auctionEnd() + public onlyAfter(revealEnd) { require(!ended); AuctionEnded(highestBidder, highestBid); ended = true; - // We send all the money we have, because some - // of the refunds might have failed. - beneficiary.transfer(this.balance); + beneficiary.transfer(highestBid); } } + .. index:: purchase, remote purchase, escrow ******************** @@ -534,7 +536,7 @@ Safe Remote Purchase // Ensure that `msg.value` is an even number. // Division will truncate if it is an odd number. // Check via multiplication that it wasn't an odd number. - function Purchase() payable { + function Purchase() public payable { seller = msg.sender; value = msg.value / 2; require((2 * value) == msg.value); @@ -568,6 +570,7 @@ Safe Remote Purchase /// Can only be called by the seller before /// the contract is locked. function abort() + public onlySeller inState(State.Created) { @@ -581,6 +584,7 @@ Safe Remote Purchase /// The ether will be locked until confirmReceived /// is called. function confirmPurchase() + public inState(State.Created) condition(msg.value == (2 * value)) payable @@ -593,6 +597,7 @@ Safe Remote Purchase /// Confirm that you (the buyer) received the item. /// This will release the locked ether. function confirmReceived() + public onlyBuyer inState(State.Locked) { diff --git a/docs/structure-of-a-contract.rst b/docs/structure-of-a-contract.rst index 224eb368..a9a7ed52 100644 --- a/docs/structure-of-a-contract.rst +++ b/docs/structure-of-a-contract.rst @@ -8,7 +8,7 @@ Structure of a Contract Contracts in Solidity are similar to classes in object-oriented languages. Each contract can contain declarations of :ref:`structure-state-variables`, :ref:`structure-functions`, -:ref:`structure-function-modifiers`, :ref:`structure-events`, :ref:`structure-structs-types` and :ref:`structure-enum-types`. +:ref:`structure-function-modifiers`, :ref:`structure-events`, :ref:`structure-struct-types` and :ref:`structure-enum-types`. Furthermore, contracts can inherit from other contracts. .. _structure-state-variables: @@ -20,12 +20,12 @@ State variables are values which are permanently stored in contract storage. :: - pragma solidity ^0.4.0; + pragma solidity ^0.4.0; - contract SimpleStorage { - uint storedData; // State variable - // ... - } + contract SimpleStorage { + uint storedData; // State variable + // ... + } See the :ref:`types` section for valid state variable types and :ref:`visibility-and-getters` for possible choices for @@ -40,13 +40,13 @@ Functions are the executable units of code within a contract. :: - pragma solidity ^0.4.0; + pragma solidity ^0.4.0; - contract SimpleAuction { - function bid() payable { // Function - // ... - } - } + contract SimpleAuction { + function bid() public payable { // Function + // ... + } + } :ref:`function-calls` can happen internally or externally and have different levels of visibility (:ref:`visibility-and-getters`) @@ -62,20 +62,20 @@ Function modifiers can be used to amend the semantics of functions in a declarat :: - pragma solidity ^0.4.11; + pragma solidity ^0.4.11; - contract Purchase { - address public seller; + contract Purchase { + address public seller; - modifier onlySeller() { // Modifier - require(msg.sender == seller); - _; - } + modifier onlySeller() { // Modifier + require(msg.sender == seller); + _; + } - function abort() onlySeller { // Modifier usage - // ... - } - } + function abort() public onlySeller { // Modifier usage + // ... + } + } .. _structure-events: @@ -86,23 +86,23 @@ Events are convenience interfaces with the EVM logging facilities. :: - pragma solidity ^0.4.0; + pragma solidity ^0.4.0; - contract SimpleAuction { - event HighestBidIncreased(address bidder, uint amount); // Event + contract SimpleAuction { + event HighestBidIncreased(address bidder, uint amount); // Event - function bid() payable { - // ... - HighestBidIncreased(msg.sender, msg.value); // Triggering event - } - } + function bid() public payable { + // ... + HighestBidIncreased(msg.sender, msg.value); // Triggering event + } + } See :ref:`events` in contracts section for information on how events are declared and can be used from within a dapp. -.. _structure-structs-types: +.. _structure-struct-types: -Structs Types +Struct Types ============= Structs are custom defined types that can group several variables (see @@ -110,16 +110,16 @@ Structs are custom defined types that can group several variables (see :: - pragma solidity ^0.4.0; + pragma solidity ^0.4.0; - contract Ballot { - struct Voter { // Struct - uint weight; - bool voted; - address delegate; - uint vote; - } - } + contract Ballot { + struct Voter { // Struct + uint weight; + bool voted; + address delegate; + uint vote; + } + } .. _structure-enum-types: @@ -131,8 +131,8 @@ Enums can be used to create custom types with a finite set of values (see :: - pragma solidity ^0.4.0; + pragma solidity ^0.4.0; - contract Purchase { - enum State { Created, Locked, Inactive } // Enum - } + contract Purchase { + enum State { Created, Locked, Inactive } // Enum + } diff --git a/docs/style-guide.rst b/docs/style-guide.rst index a438b3d0..ab1af13d 100644 --- a/docs/style-guide.rst +++ b/docs/style-guide.rst @@ -86,17 +86,17 @@ Blank lines may be omitted between groups of related one-liners (such as stub fu Yes:: contract A { - function spam(); - function ham(); + function spam() public; + function ham() public; } contract B is A { - function spam() { + function spam() public { ... } - function ham() { + function ham() public { ... } } @@ -104,10 +104,10 @@ Yes:: No:: contract A { - function spam() { + function spam() public { ... } - function ham() { + function ham() public { ... } } @@ -169,26 +169,26 @@ Within a grouping, place the ``constant`` functions last. Yes:: contract A { - function A() { + function A() public { ... } - - function() { + + function() public { ... } - + // External functions // ... - + // External functions that are constant // ... - + // Public functions // ... - + // Internal functions // ... - + // Private functions // ... } @@ -196,7 +196,7 @@ Yes:: No:: contract A { - + // External functions // ... @@ -206,16 +206,16 @@ No:: // Public functions // ... - function A() { + function A() public { ... } - - function() { + + function() public { ... } // Internal functions - // ... + // ... } Whitespace in Expressions @@ -235,17 +235,17 @@ No:: Exception:: - function singleLine() { spam(); } + function singleLine() public { spam(); } Immediately before a comma, semicolon: Yes:: - function spam(uint i, Coin coin); + function spam(uint i, Coin coin) public; No:: - function spam(uint i , Coin coin) ; + function spam(uint i , Coin coin) public ; More than one space around an assignment or other operator to align with another: @@ -266,13 +266,13 @@ Don't include a whitespace in the fallback function: Yes:: - function() { + function() public { ... } No:: - - function () { + + function () public { ... } @@ -395,30 +395,30 @@ The opening brace should be preceeded by a single space. Yes:: - function increment(uint x) returns (uint) { + function increment(uint x) public pure returns (uint) { return x + 1; } - function increment(uint x) public onlyowner returns (uint) { + function increment(uint x) public pure onlyowner returns (uint) { return x + 1; } No:: - function increment(uint x) returns (uint) + function increment(uint x) public pure returns (uint) { return x + 1; } - function increment(uint x) returns (uint){ + function increment(uint x) public pure returns (uint){ return x + 1; } - function increment(uint x) returns (uint) { + function increment(uint x) public pure returns (uint) { return x + 1; } - function increment(uint x) returns (uint) { + function increment(uint x) public pure returns (uint) { return x + 1;} The visibility modifiers for a function should come before any custom @@ -450,14 +450,16 @@ Yes:: address d, address e, address f - ) { + ) + public + { doSomething(); } No:: function thisFunctionHasLotsOfArguments(address a, address b, address c, - address d, address e, address f) { + address d, address e, address f) public { doSomething(); } @@ -466,7 +468,7 @@ No:: address c, address d, address e, - address f) { + address f) public { doSomething(); } @@ -476,12 +478,12 @@ No:: address c, address d, address e, - address f) { + address f) public { doSomething(); } If a long function declaration has modifiers, then each modifier should be -dropped to it's own line. +dropped to its own line. Yes:: @@ -542,6 +544,7 @@ Yes:: B(param1) C(param2, param3) D(param4) + public { // do something with param5 } @@ -554,6 +557,7 @@ No:: B(param1) C(param2, param3) D(param4) + public { // do something with param5 } @@ -563,7 +567,8 @@ No:: function A(uint param1, uint param2, uint param3, uint param4, uint param5) B(param1) C(param2, param3) - D(param4) { + D(param4) + public { // do something with param5 } } @@ -572,7 +577,7 @@ When declaring short functions with a single statement, it is permissible to do Permissible:: - function shortFunction() { doSomething(); } + function shortFunction() public { doSomething(); } These guidelines for function declarations are intended to improve readability. Authors should use their best judgement as this guide does not try to cover all @@ -679,7 +684,7 @@ naming styles. * ``mixedCase`` (differs from CapitalizedWords by initial lowercase character!) * ``Capitalized_Words_With_Underscores`` -.. note:: When using abbreviations in CapWords, capitalize all the letters of the abbreviation. Thus HTTPServerError is better than HttpServerError. +.. note:: When using initialisms in CapWords, capitalize all the letters of the initialisms. Thus HTTPServerError is better than HttpServerError. When using initialisms is mixedCase, capitalize all the letters of the initialisms, except keep the first one lower case if it is the beginning of the name. Thus xmlHTTPRequest is better than XMLHTTPRequest. Names to Avoid @@ -699,6 +704,12 @@ Contract and Library Names Contracts and libraries should be named using the CapWords style. Examples: ``SimpleToken``, ``SmartBank``, ``CertificateHashRepository``, ``Player``. +Struct Names +========================== + +Structs should be named using the CapWords style. Examples: ``MyCoin``, ``Position``, ``PositionXY``. + + Event Names =========== @@ -708,7 +719,7 @@ Events should be named using the CapWords style. Examples: ``Deposit``, ``Transf Function Names ============== -Functions should use mixedCase. Examples: ``getBalance``, ``transfer``, ``verifyOwner``, ``addMember``, ``changeOwner``. +Functions other than constructors should use mixedCase. Examples: ``getBalance``, ``transfer``, ``verifyOwner``, ``addMember``, ``changeOwner``. Function Argument Names @@ -739,6 +750,12 @@ Modifier Names Use mixedCase. Examples: ``onlyBy``, ``onlyAfter``, ``onlyDuringThePreSale``. +Enums +===== + +Enums, in the style of simple type declarations, should be named using the CapWords style. Examples: ``TokenGroup``, ``Frame``, ``HashStyle``, ``CharacterLocation``. + + Avoiding Naming Collisions ========================== diff --git a/docs/types.rst b/docs/types.rst index 0be8255e..55eaa69a 100644 --- a/docs/types.rst +++ b/docs/types.rst @@ -79,8 +79,8 @@ Fixed Point Numbers Fixed point numbers are not fully supported by Solidity yet. They can be declared, but cannot be assigned to or from. -``fixed`` / ``ufixed``: Signed and unsigned fixed point number of various sizes. Keywords ``ufixedMxN`` and ``fixedMxN``, where ``M`` represent the number of bits taken by -the type and ``N`` represent how many decimal points are available. ``M`` must be divisible by 8 and goes from 8 to 256 bits. ``N`` must be between 0 and 80, inclusive. +``fixed`` / ``ufixed``: Signed and unsigned fixed point number of various sizes. Keywords ``ufixedMxN`` and ``fixedMxN``, where ``M`` represents the number of bits taken by +the type and ``N`` represents how many decimal points are available. ``M`` must be divisible by 8 and goes from 8 to 256 bits. ``N`` must be between 0 and 80, inclusive. ``ufixed`` and ``fixed`` are aliases for ``ufixed128x19`` and ``fixed128x19``, respectively. Operators: @@ -331,14 +331,14 @@ check the value ranges at runtime and a failure causes an exception. Enums need :: - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; contract test { enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } ActionChoices choice; ActionChoices constant defaultChoice = ActionChoices.GoStraight; - function setGoStraight() { + function setGoStraight() public { choice = ActionChoices.GoStraight; } @@ -347,11 +347,11 @@ check the value ranges at runtime and a failure causes an exception. Enums need // for all matters external to Solidity. The integer type used is just // large enough to hold all enum values, i.e. if you have more values, // `uint16` will be used and so on. - function getChoice() returns (ActionChoices) { + function getChoice() public view returns (ActionChoices) { return choice; } - function getDefaultChoice() returns (uint) { + function getDefaultChoice() public pure returns (uint) { return uint(defaultChoice); } } @@ -409,23 +409,24 @@ just use ``f``, if you want to use its external form, use ``this.f``. Additionally, public (or external) functions also have a special member called ``selector``, which returns the :ref:`ABI function selector <abi_function_selector>`:: - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; contract Selector { - function f() returns (bytes4) { + function f() public view returns (bytes4) { return this.f.selector; } } Example that shows how to use internal function types:: - pragma solidity ^0.4.5; + pragma solidity ^0.4.16; library ArrayUtils { // internal functions can be used in internal library functions because // they will be part of the same code context - function map(uint[] memory self, function (uint) returns (uint) f) + function map(uint[] memory self, function (uint) pure returns (uint) f) internal + pure returns (uint[] memory r) { r = new uint[](self.length); @@ -435,9 +436,10 @@ Example that shows how to use internal function types:: } function reduce( uint[] memory self, - function (uint, uint) returns (uint) f + function (uint, uint) pure returns (uint) f ) internal + pure returns (uint r) { r = self[0]; @@ -445,23 +447,23 @@ Example that shows how to use internal function types:: r = f(r, self[i]); } } - function range(uint length) internal returns (uint[] memory r) { + function range(uint length) internal pure returns (uint[] memory r) { r = new uint[](length); for (uint i = 0; i < r.length; i++) { r[i] = i; } } } - + contract Pyramid { using ArrayUtils for *; - function pyramid(uint l) returns (uint) { + function pyramid(uint l) public pure returns (uint) { return ArrayUtils.range(l).map(square).reduce(sum); } - function square(uint x) internal returns (uint) { + function square(uint x) internal pure returns (uint) { return x * x; } - function sum(uint x, uint y) internal returns (uint) { + function sum(uint x, uint y) internal pure returns (uint) { return x + y; } } @@ -477,11 +479,11 @@ Another example that uses external function types:: } Request[] requests; event NewRequest(uint); - function query(bytes data, function(bytes memory) external callback) { + function query(bytes data, function(bytes memory) external callback) public { requests.push(Request(data, callback)); NewRequest(requests.length - 1); } - function reply(uint requestID, bytes response) { + function reply(uint requestID, bytes response) public { // Here goes the check that the reply comes from a trusted source requests[requestID].callback(response); } @@ -492,7 +494,7 @@ Another example that uses external function types:: function buySomething() { oracle.query("USD", this.oracleResponse); } - function oracleResponse(bytes response) { + function oracleResponse(bytes response) public { require(msg.sender == address(oracle)); // Use the data } @@ -543,7 +545,7 @@ memory-stored reference type do not create a copy. uint[] x; // the data location of x is storage // the data location of memoryArray is memory - function f(uint[] memoryArray) { + function f(uint[] memoryArray) public { x = memoryArray; // works, copies the whole array to storage var y = x; // works, assigns a pointer, data location of y is storage y[7]; // fine, returns the 8th element @@ -560,7 +562,7 @@ memory-stored reference type do not create a copy. } function g(uint[] storage storageArray) internal {} - function h(uint[] memoryArray) {} + function h(uint[] memoryArray) public {} } Summary @@ -620,10 +622,10 @@ the ``.length`` member. :: - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; contract C { - function f(uint len) { + function f(uint len) public pure { uint[] memory a = new uint[](7); bytes memory b = new bytes(len); // Here we have a.length == 7 and b.length == len @@ -641,13 +643,13 @@ assigned to a variable right away. :: - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; contract C { - function f() { + function f() public pure { g([uint(1), 2, 3]); } - function g(uint[3] _data) { + function g(uint[3] _data) public pure { // ... } } @@ -667,7 +669,7 @@ possible: pragma solidity ^0.4.0; contract C { - function f() { + function f() public { // The next line creates a type error because uint[3] memory // cannot be converted to uint[] memory. uint[] x = [uint(1), 3, 4]; @@ -703,7 +705,7 @@ Members :: - pragma solidity ^0.4.0; + pragma solidity ^0.4.16; contract ArrayContract { uint[2**20] m_aLotOfIntegers; @@ -712,23 +714,23 @@ Members bool[2][] m_pairsOfFlags; // newPairs is stored in memory - the default for function arguments - function setAllFlagPairs(bool[2][] newPairs) { + function setAllFlagPairs(bool[2][] newPairs) public { // assignment to a storage array replaces the complete array m_pairsOfFlags = newPairs; } - function setFlagPair(uint index, bool flagA, bool flagB) { + function setFlagPair(uint index, bool flagA, bool flagB) public { // access to a non-existing index will throw an exception m_pairsOfFlags[index][0] = flagA; m_pairsOfFlags[index][1] = flagB; } - function changeFlagArraySize(uint newSize) { + function changeFlagArraySize(uint newSize) public { // if the new size is smaller, removed array elements will be cleared m_pairsOfFlags.length = newSize; } - function clear() { + function clear() public { // these clear the arrays completely delete m_pairsOfFlags; delete m_aLotOfIntegers; @@ -738,20 +740,20 @@ Members bytes m_byteData; - function byteArrays(bytes data) { + function byteArrays(bytes data) public { // byte arrays ("bytes") are different as they are stored without padding, // but can be treated identical to "uint8[]" m_byteData = data; m_byteData.length += 7; - m_byteData[3] = 8; + m_byteData[3] = byte(8); delete m_byteData[2]; } - function addFlag(bool[2] flag) returns (uint) { + function addFlag(bool[2] flag) public returns (uint) { return m_pairsOfFlags.push(flag); } - function createMemoryArray(uint size) returns (bytes) { + function createMemoryArray(uint size) public pure returns (bytes) { // Dynamic memory arrays are created using `new`: uint[2][] memory arrayOfPairs = new uint[2][](size); // Create a dynamic byte array: @@ -795,13 +797,13 @@ shown in the following example: uint numCampaigns; mapping (uint => Campaign) campaigns; - function newCampaign(address beneficiary, uint goal) returns (uint campaignID) { + function newCampaign(address beneficiary, uint goal) public returns (uint campaignID) { campaignID = numCampaigns++; // campaignID is return variable // Creates new struct and saves in storage. We leave out the mapping type. campaigns[campaignID] = Campaign(beneficiary, goal, 0, 0); } - function contribute(uint campaignID) payable { + function contribute(uint campaignID) public payable { Campaign storage c = campaigns[campaignID]; // Creates a new temporary memory struct, initialised with the given values // and copies it over to storage. @@ -810,7 +812,7 @@ shown in the following example: c.amount += msg.value; } - function checkGoalReached(uint campaignID) returns (bool reached) { + function checkGoalReached(uint campaignID) public returns (bool reached) { Campaign storage c = campaigns[campaignID]; if (c.amount < c.fundingGoal) return false; @@ -872,13 +874,13 @@ for each ``_KeyType``, recursively. contract MappingExample { mapping(address => uint) public balances; - function update(uint newBalance) { + function update(uint newBalance) public { balances[msg.sender] = newBalance; } } contract MappingUser { - function f() returns (uint) { + function f() public returns (uint) { MappingExample m = new MappingExample(); m.update(100); return m.balances(this); @@ -897,7 +899,7 @@ Operators Involving LValues If ``a`` is an LValue (i.e. a variable or something that can be assigned to), the following operators are available as shorthands: -``a += e`` is equivalent to ``a = a + e``. The operators ``-=``, ``*=``, ``/=``, ``%=``, ``a |=``, ``&=`` and ``^=`` are defined accordingly. ``a++`` and ``a--`` are equivalent to ``a += 1`` / ``a -= 1`` but the expression itself still has the previous value of ``a``. In contrast, ``--a`` and ``++a`` have the same effect on ``a`` but return the value after the change. +``a += e`` is equivalent to ``a = a + e``. The operators ``-=``, ``*=``, ``/=``, ``%=``, ``|=``, ``&=`` and ``^=`` are defined accordingly. ``a++`` and ``a--`` are equivalent to ``a += 1`` / ``a -= 1`` but the expression itself still has the previous value of ``a``. In contrast, ``--a`` and ``++a`` have the same effect on ``a`` but return the value after the change. delete ------ @@ -916,11 +918,11 @@ It is important to note that ``delete a`` really behaves like an assignment to ` uint data; uint[] dataArray; - function f() { + function f() public { uint x = data; delete x; // sets x to 0, does not affect data delete data; // sets data to 0, does not affect x which still holds a copy - uint[] y = dataArray; + uint[] storage y = dataArray; delete dataArray; // this sets dataArray.length to zero, but as uint[] is a complex object, also // y is affected which is an alias to the storage object // On the other hand: "delete y" is not valid, as assignments to local variables @@ -990,6 +992,6 @@ parameters or return parameters. .. warning:: The type is only deduced from the first assignment, so the loop in the following snippet is infinite, as ``i`` will have the type - ``uint8`` and any value of this type is smaller than ``2000``. + ``uint8`` and the highest value of this type is smaller than ``2000``. ``for (var i = 0; i < 2000; i++) { ... }`` diff --git a/docs/units-and-global-variables.rst b/docs/units-and-global-variables.rst index dd16ccc6..cc4d4446 100644 --- a/docs/units-and-global-variables.rst +++ b/docs/units-and-global-variables.rst @@ -34,7 +34,7 @@ library has to be updated by an external oracle. These suffixes cannot be applied to variables. If you want to interpret some input variable in e.g. days, you can do it in the following way:: - function f(uint start, uint daysAfter) { + function f(uint start, uint daysAfter) public { if (now >= start + daysAfter * 1 days) { // ... } @@ -85,11 +85,6 @@ Block and Transaction Properties consecutive blocks in the canonical chain. .. note:: - If you want to implement access restrictions in library functions using - ``msg.sender``, you have to manually supply the value of - ``msg.sender`` as an argument. - -.. note:: The block hashes are not available for all blocks for scalability reasons. You can only access the hashes of the most recent 256 blocks, all other values will be zero. @@ -112,9 +107,9 @@ Mathematical and Cryptographic Functions ---------------------------------------- ``addmod(uint x, uint y, uint k) returns (uint)``: - compute ``(x + y) % k`` where the addition is performed with arbitrary precision and does not wrap around at ``2**256``. + compute ``(x + y) % k`` where the addition is performed with arbitrary precision and does not wrap around at ``2**256``. Assert that ``k != 0`` starting from version 0.5.0. ``mulmod(uint x, uint y, uint k) returns (uint)``: - compute ``(x * y) % k`` where the multiplication is performed with arbitrary precision and does not wrap around at ``2**256``. + compute ``(x * y) % k`` where the multiplication is performed with arbitrary precision and does not wrap around at ``2**256``. Assert that ``k != 0`` starting from version 0.5.0. ``keccak256(...) returns (bytes32)``: compute the Ethereum-SHA-3 (Keccak-256) hash of the :ref:`(tightly packed) arguments <abi_packed_mode>` ``sha256(...) returns (bytes32)``: diff --git a/docs/using-the-compiler.rst b/docs/using-the-compiler.rst index 7f82df70..42cc807a 100644 --- a/docs/using-the-compiler.rst +++ b/docs/using-the-compiler.rst @@ -138,7 +138,7 @@ Input Description // ewasm.wasm - eWASM binary format (not supported atm) // // Note that using a using `evm`, `evm.bytecode`, `ewasm`, etc. will select every - // target part of that output. + // target part of that output. Additionally, `*` can be used as a wildcard to request everything. // outputSelection: { // Enable the metadata and bytecode outputs of every single contract. @@ -147,11 +147,11 @@ Input Description }, // Enable the abi and opcodes output of MyContract defined in file def. "def": { - "MyContract": [ "abi", "evm.opcodes" ] + "MyContract": [ "abi", "evm.bytecode.opcodes" ] }, // Enable the source map output of every single contract. "*": { - "*": [ "evm.sourceMap" ] + "*": [ "evm.bytecode.sourceMap" ] }, // Enable the legacy AST output of every single file. "*": { @@ -177,7 +177,8 @@ Output Description start: 0, end: 100 ], - // Mandatory: Error type, such as "TypeError", "InternalCompilerError", "Exception", etc + // Mandatory: Error type, such as "TypeError", "InternalCompilerError", "Exception", etc. + // See below for complete list of types. type: "TypeError", // Mandatory: Component where the error originated, such as "general", "ewasm", etc. component: "general", @@ -273,3 +274,21 @@ Output Description } } } + + +Error types +~~~~~~~~~~~ + +1. ``JSONError``: JSON input doesn't conform to the required format, e.g. input is not a JSON object, the language is not supported, etc. +2. ``IOError``: IO and import processing errors, such as unresolvable URL or hash mismatch in supplied sources. +3. ``ParserError``: Source code doesn't conform to the language rules. +4. ``DocstringParsingError``: The NatSpec tags in the comment block cannot be parsed. +5. ``SyntaxError``: Syntactical error, such as ``continue`` is used outside of a ``for`` loop. +6. ``DeclarationError``: Invalid, unresolvable or clashing identifier names. e.g. ``Identifier not found`` +7. ``TypeError``: Error within the type system, such as invalid type conversions, invalid assignments, etc. +8. ``UnimplementedFeatureError``: Feature is not supported by the compiler, but is expected to be supported in future versions. +9. ``InternalCompilerError``: Internal bug triggered in the compiler - this should be reported as an issue. +10. ``Exception``: Unknown failure during compilation - this should be reported as an issue. +11. ``CompilerError``: Invalid use of the compiler stack - this should be reported as an issue. +12. ``FatalError``: Fatal error not processed correctly - this should be reported as an issue. +13. ``Warning``: A warning, which didn't stop the compilation, but should be addressed if possible. diff --git a/docs/utils/SolidityLexer.py b/docs/utils/SolidityLexer.py index a828146f..50f51cf4 100644 --- a/docs/utils/SolidityLexer.py +++ b/docs/utils/SolidityLexer.py @@ -56,7 +56,7 @@ class SolidityLexer(RegexLexer): (r'[})\].]', Punctuation), (r'(anonymous|as|assembly|break|constant|continue|do|delete|else|external|for|hex|if|' r'indexed|internal|import|is|mapping|memory|new|payable|public|pragma|' - r'private|return|returns|storage|super|this|throw|using|while)\b', Keyword, 'slashstartsregex'), + r'private|pure|return|returns|storage|super|this|throw|using|view|while)\b', Keyword, 'slashstartsregex'), (r'(var|function|event|modifier|struct|enum|contract|library|interface)\b', Keyword.Declaration, 'slashstartsregex'), (r'(bytes|string|address|uint|int|bool|byte|' + '|'.join( @@ -67,15 +67,15 @@ class SolidityLexer(RegexLexer): ['fixed%dx%d' % ((i), (j + 8)) for i in range(0, 256, 8) for j in range(0, 256 - i, 8)] ) + r')\b', Keyword.Type, 'slashstartsregex'), (r'(wei|szabo|finney|ether|seconds|minutes|hours|days|weeks|years)\b', Keyword.Type, 'slashstartsregex'), - (r'(abstract|after|case|catch|default|final|in|inline|interface|let|match|' - r'null|of|pure|relocatable|static|switch|try|type|typeof|view)\b', Keyword.Reserved), + (r'(abstract|after|case|catch|default|final|in|inline|let|match|' + r'null|of|relocatable|static|switch|try|type|typeof)\b', Keyword.Reserved), (r'(true|false)\b', Keyword.Constant), (r'(block|msg|tx|now|suicide|selfdestruct|addmod|mulmod|sha3|keccak256|log[0-4]|' r'sha256|ecrecover|ripemd160|assert|revert|require)', Name.Builtin), (r'[$a-zA-Z_][a-zA-Z0-9_]*', Name.Other), - (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float), + (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?', Number.Float), (r'0x[0-9a-fA-F]+', Number.Hex), - (r'[0-9]+', Number.Integer), + (r'[0-9]+([eE][0-9]+)?', Number.Integer), (r'"(\\\\|\\"|[^"])*"', String.Double), (r"'(\\\\|\\'|[^'])*'", String.Single), ] |