├── .gitignore ├── LICENSE.md ├── README.md ├── proposal ├── README.md └── proposal-32.md ├── template.md ├── tip-01.md ├── tip-10.md ├── tip-101.md ├── tip-102.md ├── tip-104.md ├── tip-105.md ├── tip-1102.md ├── tip-1155.md ├── tip-1193.md ├── tip-12.md ├── tip-120.md ├── tip-127.md ├── tip-128.md ├── tip-13.md ├── tip-135.md ├── tip-137.md ├── tip-138.md ├── tip-156.md ├── tip-157.md ├── tip-16.md ├── tip-165.md ├── tip-17.md ├── tip-171.md ├── tip-174.md ├── tip-175.md ├── tip-176.md ├── tip-178.md ├── tip-19.md ├── tip-191.md ├── tip-196.md ├── tip-20.md ├── tip-203.md ├── tip-204.md ├── tip-207.md ├── tip-209.md ├── tip-222.md ├── tip-23.md ├── tip-24.md ├── tip-241.md ├── tip-250.md ├── tip-26.md ├── tip-268.md ├── tip-269.md ├── tip-271.md ├── tip-272.md ├── tip-276.md ├── tip-28.md ├── tip-281.md ├── tip-285.md ├── tip-289.md ├── tip-29.md ├── tip-290.md ├── tip-292.md ├── tip-293.md ├── tip-295.md ├── tip-298.md ├── tip-30.md ├── tip-306.md ├── tip-31.md ├── tip-318.md ├── tip-32.md ├── tip-3326.md ├── tip-343.md ├── tip-344.md ├── tip-362.md ├── tip-366.md ├── tip-369.md ├── tip-37.md ├── tip-370.md ├── tip-382.md ├── tip-383.md ├── tip-387.md ├── tip-388.md ├── tip-391.md ├── tip-397.md ├── tip-41.md ├── tip-425.md ├── tip-428.md ├── tip-43.md ├── tip-44.md ├── tip-440.md ├── tip-461.md ├── tip-465.md ├── tip-467.md ├── tip-474.md ├── tip-476.md ├── tip-4906.md ├── tip-491.md ├── tip-51.md ├── tip-53.md ├── tip-534.md ├── tip-54.md ├── tip-541.md ├── tip-542.md ├── tip-543.md ├── tip-544.md ├── tip-547.md ├── tip-548.md ├── tip-549.md ├── tip-550.md ├── tip-555.md ├── tip-586.md ├── tip-592.md ├── tip-60.md ├── tip-62.md ├── tip-621.md ├── tip-635.md ├── tip-64.md ├── tip-650.md ├── tip-651.md ├── tip-652.md ├── tip-653.md ├── tip-694.md ├── tip-697.md ├── tip-712.md ├── tip-721.md ├── tip-745.md └── tp ├── README.md ├── p2p ├── 001-Node-Discover-Protocol.md ├── 002-Node-State-Machine.md ├── 003-Node-Scoring-Policy.md ├── 004-TCP-Connection-Policy.md └── 005-Handshake.md └── ticp ├── ticp-blockheader-sync ├── Synchronize_block_headers.png ├── Synchronize_block_headers_between_chains.png ├── Synchronize_block_headers_when_new_node_add.png └── Synchronize_block_headers_within_chains.png ├── ticp-optimized-pbft ├── pbft-1.png ├── pbft-2.png └── ticp-Optimized-PBFT.md ├── ticp-spv-proof-support └── ticp-SPV-PROOF-SUPPORT.md └── ticp-verctor-commitment └── ticp-Vector-Commitment.md /.gitignore: -------------------------------------------------------------------------------- 1 | # IDEA 2 | .idea 3 | *iml 4 | .DS_Store 5 | 6 | # gradle 7 | .gradle 8 | build 9 | 10 | 11 | -------------------------------------------------------------------------------- /template.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 3 | title: 4 | author: , FirstName (@GitHubUsername) and GitHubUsername (@GitHubUsername)> 5 | discussions-to: 6 | status: 7 | type: 8 | category (*only required for Standard Track): 9 | created: 10 | requires (*optional): 11 | replaces (*optional): 12 | ``` 13 | 14 | This is the suggested template for new TIPs. 15 | 16 | Note that an TIP number will be assigned by an editor. When opening a pull request to submit your TIP, please use an abbreviated title in the filename. 17 | 18 | The title should be 44 characters or less. 19 | 20 | ## Simple Summary (required) 21 | 22 | Provide a simplified explanation of the TIP. 23 | 24 | ## Abstract (required) 25 | 26 | A short (~200 word) description of the technical issue being addressed. 27 | 28 | ## Motivation (required) 29 | 30 | The motivation is critical for TIPs that want to change the TRON protocol. It should clearly explain why the existing protocol specification is inadequate to address the problem that the TIP solves. TIP submissions without sufficient motivation may be rejected outright. 31 | 32 | ## Specification (required) 33 | 34 | The technical specification should describe the syntax and semantics of any new feature. 35 | 36 | ## Rationale (required) 37 | 38 | The rationale fleshes out the specification by describing what motivated the design and why particular design decisions were made. It should describe alternate designs that were considered and related work, e.g. how the feature is supported in other languages. The rationale may also provide evidence of consensus within the community, and should discuss important objections or concerns raised during discussion. 39 | 40 | ## Backwards Compatibility (optional) 41 | 42 | All TIPs that introduce backwards incompatibilities must include a section describing these incompatibilities and their severity. The TIP must explain how the author proposes to deal with these incompatibilities. TIP submissions without a sufficient backwards compatibility treatise may be rejected outright. 43 | 44 | ## Test Cases (optional) 45 | 46 | Test cases for an implementation are mandatory for TIPs that are affecting consensus changes. Other TIPs can choose to include links to test cases if applicable. 47 | 48 | ## Implementation (required) 49 | 50 | The implementations must be completed before any TIP is given status "Final", but it need not be completed before the TIP is accepted. While there is merit to the approach of reaching consensus on the specification and rationale before writing code, the principle of "rough consensus and running code" is still useful when it comes to resolving many discussions of API details. 51 | 52 | ## Copyright 53 | 54 | Copyright and related rights waived via [CC0](LICENSE.md). -------------------------------------------------------------------------------- /tip-101.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 101 3 | title: Wallet Keystore Specification 4 | author: federico 5 | discussions-to: https://github.com/tronprotocol/tips/issues/101 6 | status: Last Call 7 | type: Standards Track 8 | category: TRC 9 | created: 2019-10-17 10 | ``` 11 | 12 | ## Simple Summary 13 | 14 | This TIP describes the keystore generation method to store the private key in wallet. 15 | 16 | ## Abstract 17 | 18 | Private key is fatally important for users, which should be kept carefully. Mnemonic code specified in [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) is used to 19 | generate the private key, but it is not convenient for users to remember. Usually, encrypted private key is stored in keystore file and can be recovered by passphrase. This is a standard 20 | about keystore specification, which includes the procedures of key derivation, symmetric encryption and message authentication. 21 | 22 | ## Motivation 23 | 24 | The proposal presents the explicit cryptographic method to generate the keystore file and guarantee the security of users' private keys. 25 | 26 | 27 | ## Specification 28 | 29 | There are mainly three steps as follows. 30 | 31 | ### Key Derivation Function 32 | 33 | First, the user needs to provide the passphrase as the input of [PBKDF2](https://en.wikipedia.org/wiki/PBKDF2). The key derivation function has five input parameters: 34 | 35 | 36 | DK = PBKDF2(PRF, Passphrase, Salt, c, dkLen) 37 | 38 | where 39 | * *PRF* is a pseudorandom function generated by SHA256 40 | * *Passphrase* is the master password from which a derived key is generated 41 | * *Salt* is a sequence of bits, known as a cryptographic salt 42 | * *c* is the number of iterations desired 43 | * *dkLen* is the desired bit-length of the derived key 44 | * *DK* is the generated derived key 45 | 46 | ### Symmetric Encryption 47 | The derived key *DK* is used as key of [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard) to encrypt the real private key of user. 48 | 49 | C = AES-128(DK, PrivK, CTR, iv) 50 | 51 | where 52 | * *DK* is the derived key 53 | * *PrivK* is the private key of user,which is generated by mnemonic codes specified in [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) 54 | * *CTR* is the counter encryption mode 55 | * *iv* is 128-bit initialisation vector for the cipher 56 | * *C* is the generated cipher text 57 | 58 | ### Message Authentication Code 59 | 60 | MAC (Message authentication code) is used to check the correctness of derived key *DK* when the user try to decrypt the private key 61 | with the passphrase. [SHA3](https://en.wikipedia.org/wiki/SHA-3) is used to produce the MAC: 62 | 63 | mac = SHA3-256 (DK || C) 64 | 65 | where 66 | * *DK* is the derived key 67 | * *C* is the cipher text of private key 68 | * *mac* is the generated MAC 69 | 70 | ## Rationale 71 | 72 | The SHA256 and AES used in the proposal are all international cryptography standard, which are sufficient to ensure the security of the private key. 73 | 74 | ## Test Cases 75 | For *Passphrase* = ``dark1234``, the generated keystore file is: 76 | 77 | {"crypto": 78 | {"cipher":"aes-128-ctr", 79 | "cipherparams":{"iv":"faa1c1b73bb9630b8abb7930eccc85f0"}, 80 | "ciphertext":"3c46834a29e69fc206277838fdeb395320d7da10d2c067f5b1e0a8a52524fde3", 81 | "kdf":"pbkdf2", 82 | "kdfparams": 83 | {"c":10240, 84 | "dklen":32, 85 | "prf":"hmac-sha256", 86 | "salt":"aaf471468f1030229004f5a189be470fde806685ede147b1694be60fb15b70f1" 87 | }, 88 | "mac":"ff7679e803175ba739fadbffe38959282f45aefa3458f083eedc76fc220b201e" 89 | }, 90 | "id":"e40c9b94-369c-4b75-a2cd-8c68d542e093", 91 | "version":3, 92 | "address":"fdf9ae6a88fd403cdd2433c23230e729d12d6de4" 93 | } 94 | 95 | ## Implementation 96 | None 97 | 98 | ## Reference 99 | * https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition 100 | 101 | 102 | ## Copyright 103 | 104 | Copyright and related rights waived via [CC0](LICENSE.md). 105 | -------------------------------------------------------------------------------- /tip-1102.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 1102 3 | title: Opt-in account exposure 4 | author: Aaron 5 | discussions to: https://github.com/tronprotocol/tips/issues/463 6 | category: Interface 7 | status: Final 8 | created: 2022-09-05 9 | ``` 10 | ## Table of Contents 11 | - [Table of Contents](#table-of-contents) 12 | - [Simple Summary](#simple-summary) 13 | - [Motivation](#motivation) 14 | - [Specification](#specification) 15 | - [Examples](#examples) 16 | - [Returns](#returns) 17 | - [Error Code](#error-code) 18 | - [Constraints](#constraints) 19 | - [Backwards Compatibility](#backwards-compatibility) 20 | 21 | 22 | ## Simple Summary 23 | This protocol is used to describe the communication between a DApp and a wallet. It allows the wallet to determine what information and when to provide it to the DApp. 24 | 25 | ## Motivation 26 | Currently, there is no such protocol on TRON. This leads to inconsistent implementation of DApps connected to TRON, which objectively increases the development workload of DApp developers. 27 | The goal of this proposal is to standardize the method for DApps to obtain user information from the wallet. 28 | Description of the proposal: Wallet will not disclose any account information until the user agrees, so as to ensure the security of the user's information. 29 | Ethereum's [EIP-1102](https://eips.ethereum.org/EIPS/eip-1102) is a similar protocol that can be followed. 30 | 31 | ## Specification 32 | `eth_requestAccounts` 33 | #### Examples 34 | ```javascript 35 | try { 36 | await tron.request({method: 'eth_requestAccounts'}); 37 | } catch (e) {} 38 | ``` 39 | #### Returns 40 | If successful, an array will be returned, the array has one element, which is the address of the current account, like: 41 | `['TQKLs3GzCNLjzyCvaPWSrqcpUGUhadxm7P']`. 42 | 43 | If it fails, an error code and an error message will be returned. See the [Error Code](error-code) section for details. 44 | #### Error Code 45 | | Code | Message | Description | 46 | | ---- | ---- | ---- | 47 | | -32002 | Other requests are being processed | current DApp is processed, it cannot execute the current request | 48 | | -32602 | Invalid params | invalid parameters, or added additional parameters | 49 | | 4001 | User rejected request | the user has rejected this request | 50 | | 4200 | Unsupported method | unsupported method | 51 | 52 | #### Constraints 53 | - The wallet must define an `eth_requestAccounts` method. 54 | - If Promise is resolved, the wallet must return an array containing at least one account. 55 | - If no account is available, the wallet must reject the Promise and return an error message 56 | - If the user rejects, the wallet must reject the Promise and return an error message. 57 | - If the user can no longer accept the Promise, for example, the user interface is closed and the user interface cannot be invoked again, the wallet must reject the Promise and return an error message. 58 | 59 | 60 | ## Backwards Compatibility 61 | This protocol has no impact on existing wallets and DApps, but it is recommended that all wallets and DApps implement this protocol. 62 | It is also recommended to implement this protocol for DApps that have already implemented other similar functional protocols. 63 | 64 | 65 | ## Copyright 66 | 67 | Copyright and related rights waived via [CC0](LICENSE.md). 68 | -------------------------------------------------------------------------------- /tip-12.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 12 3 | title: TRC-12 Tron event subscribes model 4 | author: jiangyy 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/12 6 | status: Final 7 | type: Standards Track 8 | category: TRC 9 | created: 2018-12-20 10 | ``` 11 | 12 | ## Simple Summary 13 | This doc describes event subscribe model of Tron. 14 | 15 | ## Abstract 16 | The following describes a model which is used to subscribe to block chain events, transaction events, contract logs and contract events from Tron FullNode. Developers can set up filters to subscribe to specific events. Plug-ins can be developed to export these events for further development. 17 | 18 | ## Motivation 19 | This will allow dapps developers or exchange to subscribe any event triggered on Tron. 20 | 21 | ## Specification 22 | 23 | ### Events to subscribe 24 | 25 | - **transactionTrigger**, triggered after the transaction is processed 26 | - **blockTrigger**, triggered after a block is inserted into block chain 27 | - **contractLogTrigger**, triggered after smart contract is executed 28 | - **contractEventTrigger**, triggered after smart contract is executed 29 | 30 | ### Filter 31 | 32 | - **fromBlock**: the beginning of the queried range, it could be set to "", "earliest", "latest" or specified block number, the default value is "latest". "earliest" is the oldest block number from the beginning of the subscription. "latest" is the latest block number when the filter is set. 33 | - **toBlock**: end of the range, it could be set to "", "latest" or specified block number, the default value is "latest". 34 | - **contractAddress**: restricts matches to events created by specific contracts. 35 | - **contractTopics**: The Topic list restricts matches to particular event topics. Each event has a list of topics. Topics match a prefix of that list. An empty element slice matches any. 36 | 37 | **Notice**: No support the historical data query. 38 | 39 | ### Smart Contract log 40 | **contractLogTrigger** is used to represent the object of smart contract log, which has following parameters: 41 | 42 | - **transactionId**, transaction id. 43 | - **contractAddress**, contract address. 44 | - **callerAddress**, contract caller address. 45 | - **blockNumber**, the block number of transaction. 46 | - **blockTimestamp**, the packing time of a transaction in block. 47 | - **contractTopics**, list of topics that Log can output in Solidity language. 48 | - **data**, data filed that Log can output in Solidity language. 49 | 50 | ### Smart Contract event 51 | **contracteventTrigger** is used to represent the object of smart contract log, which has following parameters: 52 | 53 | - **transactionId**, transaction id. 54 | - **contractAddress**, contract address. 55 | - **callerAddress**, contract caller address. 56 | - **blockNumber**, the block number of transaction. 57 | - **blockTimestamp**, the packing time of a transaction in block. 58 | - **eventSignature**, signature string of event. 59 | - **contractTopicMap**, It is a map from a topic name to topic value that event can output in Solidity language. 60 | - **data**, data filed that log can output in Solidity language. 61 | 62 | 63 | ### Trigger event 64 | 65 | - Triggering block event, create a blockTrigger when the block is inserted. 66 | - Triggering transaction event, create a txsTrigger before the transaction is executed. 67 | - Triggeingr smart contract log, create a contractLogTrigger after the contract is executed. 68 | - Triggering smart contract event, create a contractEventTrigger after the contract is executed. 69 | 70 | ### Send trigger 71 | java-tron sends the trigger to the plugin asynchronously, and the trigger must satisfy the filter condition. The following is a filter example, the block number of the trigger must be between fromBlock and toBlock, the contractAddress must be "AddressA", the topics must include "TopicA", and only the Trigger that satisfies the condition will be sent. 72 | 73 | - **fromBlock**: 0x1000000 74 | - **toBlock**: 0x1200000 75 | - **contractAddress**: "AddressA" 76 | - **topics**: ["TopicA"] 77 | 78 | ## Implementation 79 | The function of the plugin is to implement event dump. Developers can customize it according to their needs, such as Message queue, Kafka, MongoDB or writing to local files. 80 | 81 | The plugin is independent of java-tron and is not loaded by default. It can be enabled by configuring command line parameters. By default, only subscriptions to smart contract event are supported. Developers could subscribe to other triggers by modifying configuration files. 82 | 83 | Developers are flexible in defining plug-in configuration files, including message queue server addresses, defined Trigger types, and so on. 84 | 85 | Take Kafka plug-in as an example, define the Kafka server address in the configuration file, Kafka topics (corresponding to the Trigger category). After receiving the Trigger sent by java-tron, the plug-in sends the Trigger to the corresponding Kafka topic according to the Trigger category. 86 | 87 | The plug-in implements the ILogsFilterPlugin interface, including the initialization and start-up of the plug-in, receiving Trigger, and loading the plug-in according to the configuration file. 88 | 89 | ## Copyright 90 | 91 | Copyright and related rights waived via [CC0](LICENSE.md). 92 | -------------------------------------------------------------------------------- /tip-120.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 120 3 | title: ECDSA Signature Encoding Specification 4 | author: federico 5 | discussions-to: https://github.com/tronprotocol/tips/issues/120 6 | status: Final 7 | type: Standards Track 8 | category: TRC 9 | created: 2020-01-07 10 | ``` 11 | 12 | ## Simple Summary 13 | 14 | This TIP aims to present clear signature encoding specification to avoid ambiguity in practical applications. 15 | 16 | ## Abstract 17 | 18 | The ECDSA signature scheme in [RFC6919](https://tools.ietf.org/html/rfc6979) with elliptic curve [secp256k1](http://www.secg.org/sec2-v2.pdf) returns the signature `(r, s, v)`, where `r` and `s` are the values 19 | used in standard ECDSA signatures. `v` is needed to recover the public key. In programming, The signature `(r, s, v)` needs to be encoded in standard manner for storage and transmission. 20 | 21 | 22 | ## Motivation 23 | In practice, if two applications interact with signature, e.g. one application generate the signature and another verify. If they use different 24 | signature encoding and decoding method, an valid signature may fail the verification. In order to avoid the ambiguity, the it needs to unify the 25 | the signature encoding specification. 26 | 27 | ## Specification 28 | 29 | The TIP concentrates on how to encode the ECDSA signature `(r, s, v)`, regardless of the procedure on how to generate ECDSA signature. 30 | 31 | Let `S = (r, s, v)`, we specify its encoding method is 32 | ``` 33 | encode(S) = r ‖ s ‖ v 34 | ``` 35 | where `r` and `s` are 32-byte value, v is one byte, `v = 27 + (y % 2)`. adding 27 is just the conventional manner to denote the `v`, so 36 | `v` is 27 or 28. 37 | 38 | ## Rationale 39 | In practical cases, we find someone may encode signature by `encode(S) = v ‖ r ‖ s ` or someone may regard `v` as `v = y % 2`. So we specify the encoding order 40 | of `(r, s, v)`. As for `v = 27 + (y % 2)`, it is consistent with convention used in Bitcoin and Ethereum. 41 | 42 | ## Test Cases 43 | The following is a practical signature encoding example: 44 | 45 | private key: `0xc85ef7d79691fe79573b1a7064c19c1a9819ebdbd1faaab1a8ec92344438aaf4` 46 | 47 | public key: `0x040947751e3022ecf3016be03ec77ab0ce3c2662b4843898cb068d74f698ccc8ad75aa17564ae80a20bb044ee7a6d903e8e8df624b089c95d66a0570f051e5a05b` 48 | 49 | plain message: `message digest` 50 | 51 | message hash: `0xf7846f55cf23e14eebeab5b4e1550cad5b509e3348fbc4efa3a1413d393cb650` 52 | 53 | signature: `0xdfe0122b92e0eff35e67d479e7ed774400231c723aef4bb6616f392f2505f63c726c57b96469e0c71eb58e46cd4efd16295e9bba99fb6da3758c026ceb4ace061c` 54 | 55 | `r`: `0xdfe0122b92e0eff35e67d479e7ed774400231c723aef4bb6616f392f2505f63c` 56 | 57 | `s`: `0x726c57b96469e0c71eb58e46cd4efd16295e9bba99fb6da3758c026ceb4ace06` 58 | 59 | `v`: `0x1c` 60 | 61 | ## Implementation 62 | 63 | None 64 | 65 | 66 | ## Copyright 67 | 68 | Copyright and related rights waived via [CC0](LICENSE.md). 69 | -------------------------------------------------------------------------------- /tip-127.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip:127 3 | title: Support Tron-DEX based on system contracts 4 | author: sean liu 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/127 6 | status: Final 7 | type: Standards Track 8 | category: core 9 | created: 2020-08-10 10 | ``` 11 | 12 | ## Simple Summary 13 | This TIP provides system contracts for the market in java-tron. 14 | 15 | ## Abstract 16 | This TIP provides system contracts to support the exchange of token, including TRX and TRC-10. The main features include an online order table and online matching. 17 | 18 | ## Motivation 19 | Security, transparency, and efficiency have always been at the core of DEX, but exchanges in the form of smart contracts often rely on offline matchmaking systems. 20 | In addition, the higher costs also lead to users avoiding frequent transactions as much as possible, reducing the overall transaction volume. 21 | 22 | 23 | ## Specification 24 | Only two system contracts are added, which is convenient and simple to use. 25 | 26 | Create new order: 27 | ``` 28 | rpc MarketSellAsset (MarketSellAssetContract) returns (TransactionExtention) {} 29 | 30 | message MarketSellAssetContract { 31 | bytes owner_address = 1; 32 | bytes sell_token_id = 2; 33 | int64 sell_token_quantity = 3; 34 | bytes buy_token_id = 4; 35 | int64 buy_token_quantity = 5; 36 | } 37 | 38 | Parameter: 39 | owner_address:Owner address,default hexString 40 | sell_token_id:sell token id,default hexString 41 | sell_token_quantity:sell token quantity 42 | buy_token_id:buy token id,default hexString 43 | buy_token_quantity:buy token quantity, min to receive 44 | ``` 45 | 46 | Cancel an exist order: 47 | ``` 48 | rpc MarketCancelOrder (MarketCancelOrderContract) returns (TransactionExtention) {} 49 | 50 | message MarketCancelOrderContract { 51 | bytes owner_address = 1; 52 | bytes order_id = 2; 53 | } 54 | Parameter: 55 | owner_address:Owner address,default hexString 56 | order_id:order id 57 | ``` 58 | 59 | A set of query interfaces is also provided.Like, 60 | Get all trading pairs: 61 | ``` 62 | rpc GetMarketPairList (EmptyMessage) returns (MarketOrderPairList) { } 63 | ``` 64 | Get all order prices for the trading pair: 65 | ``` 66 | rpc GetMarketPriceByPair (MarketOrderPair) returns (MarketOrderList) { 67 | ``` 68 | Get all orders for the trading pair: 69 | ``` 70 | rpc GetMarketOrderListByPair (MarketOrderPair) returns (MarketOrderList) {}; 71 | ``` 72 | Get order by orderId: 73 | ``` 74 | rpc GetMarketOrderById (BytesMessage) returns (MarketOrder) {} 75 | ``` 76 | Get all orders for the account: 77 | ``` 78 | rpc GetMarketOrderByAccount (BytesMessage) returns (MarketOrderList) {}; 79 | ``` 80 | 81 | Get orderId from transactionInfo 82 | ``` 83 | message Transaction{ 84 | ... 85 | repeated MarketOrderDetail orderDetails = 26; 86 | } 87 | 88 | message MarketOrderDetail { 89 | bytes makerOrderId = 1; 90 | bytes takerOrderId = 2; 91 | int64 fillSellQuantity = 3; 92 | int64 fillBuyQuantity = 4; 93 | } 94 | Parameter: 95 | makerOrderId: exist order id 96 | takerOrderId: current order id 97 | fillSellQuantity: sell quantity in this matching 98 | fillBuyQuantity: buy quantity in this matching 99 | ``` 100 | 101 | ## Copyright 102 | 103 | Copyright and related rights waived via [CC0](LICENSE.md). 104 | 105 | -------------------------------------------------------------------------------- /tip-13.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 13 3 | title: Account System Standard 4 | author: Justin Sun(@justintron) 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/13 6 | status: Final 7 | type: Standards Track 8 | category: TRC 9 | created: 2018-12-21 10 | ``` 11 | 12 | ## Simple Summary 13 | 14 | This doc describes the design of the TRON account system. 15 | 16 | ## Abstract 17 | 18 | Account system mainly including account name spec, account name exchange, transfer through account name. Account name will be equal to Address but easier memorize. 19 | TRX can only transfer by address. 20 | 21 | ## Motivation 22 | 23 | the address is the unique identity of an account. 24 | It's very normal for people who familiar with Bitcoin, but It's not very friendly to people who never used bitcoin or other crypto coins and the address is too long for the user to read and write. Using address to represent account stops people to try to use TRON. Every account should have a name and the name is equal to the address. 25 | 26 | ## Specification 27 | ###Account Name 28 | 29 | `length: [8, 20] 30 | case sensitive: No` 31 | 32 | **how to set account name** 33 | The address is sha256(public_key) in TRON. after the address is activated through transfer user get an account in the network. The user can set the account name to this address by RPC interface. something like below: 34 | 35 | ``` 36 | Account { 37 | 38 | string account_name; // lovelycat 39 | 40 | string address1; // prim address 41 | 42 | string address2; 43 | 44 | } 45 | ``` 46 | if I send TRX to the lovelycat, that means I send TRX to address 1. 47 | ###Account Auth 48 | ###Account Exchange 49 | 50 | the account name can be traded through muti-sig. 51 | 52 | ``` 53 | Account { 54 | string account_name; // lovelycat 55 | string address1; // prim address => 56 | string address2; 57 | } 58 | 59 | Account { 60 | string account_name; // lovelycat 61 | string address3; // prim address 62 | string address4; 63 | } 64 | ``` 65 | 66 | That means account lovelycat controlled by adderss3 and address4. 67 | 68 | ## Reserved List 69 | 70 | The full note should keep a reserved list for famous company and brand. All the SR can manager this list by voting the proposal to add or remove name from list. 71 | 72 | ## Copyright 73 | 74 | Copyright and related rights waived via [CC0](LICENSE.md). 75 | -------------------------------------------------------------------------------- /tip-138.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 138 3 | title: Pedersen hash function 4 | author: federico 5 | discussions-to: https://github.com/tronprotocol/tips/issues/138 6 | status: Final 7 | type: Standards Track 8 | category: VM 9 | created: 2020-03-10 10 | ``` 11 | 12 | ## Simple Summary 13 | 14 | The TIP provides the Pedersen hash computation function in the shielded TRC-20 contract ([TIP-135](https://github.com/tronprotocol/tips/blob/master/tip-135.md)), which can be used in shielded token transactions. 15 | 16 | ## Abstract 17 | 18 | The TIP introduces the `pedersenHash` function, which is used for the computation of Merkle tree node value in the shielded TRC-20 contract. The function is implemented in the form of the precompiled contract. 19 | 20 | ## Motivation 21 | 22 | To implement shielded transactions for [TRC-20](https://github.com/tronprotocol/TIPs/blob/master/tip-20.md) token, We have developed the shielded TRC-20 contract ([TIP-135](https://github.com/tronprotocol/tips/blob/master/tip-135.md)) and it needs the Merkle tree construction and proof, which further needs the Pedersen hash computation. So providing the Pedersen hash function `pedersenHash` is necessary for shielded TRC-20 contract implementation. 23 | 24 | ## Specification 25 | 26 | `pedersenHash` function is used to compute the node value in the Merkle tree. 27 | 28 | ``` 29 | nodeValue = pedersenHash(level, left, right); 30 | ``` 31 | 32 | * `level` - Merkle tree level, in the range [0, 31] 33 | * `left` - the left child node in the Merkle tree 34 | * `right` - the right child node in the Merkle tree 35 | 36 | ``` 37 | [uint32 for level][32 bytes for left][32 bytes for right] 38 | ``` 39 | 40 | For the output, `nodeValue` returns the parent node value in the Merkle tree. The time cost of `perdersenHash` function takes less than 1ms. 41 | 42 | ## Rationale 43 | 44 | By introducing the Pedersen hash computation function, it will be more convenient for Merkle tree construction and shielded TRC-20 contract implementation, which can provide users stronger privacy for shielded TRC-20 transactions. 45 | 46 | ## Test Case 47 | 48 | (1)test case 1 49 | 50 | Input: 51 | 52 | `level` : 0 53 | 54 | `left` : 0x0100000000000000000000000000000000000000000000000000000000000000 55 | 56 | `right`: 0x0100000000000000000000000000000000000000000000000000000000000000 57 | 58 | Output: 59 | 60 | `nodeValue` : 0x817de36ab2d57feb077634bca77819c8e0bd298c04f6fed0e6a83cc1356ca155 61 | 62 | (2)test case 2 63 | 64 | Input: 65 | 66 | `level` : 1 67 | 68 | `left` : 0x817de36ab2d57feb077634bca77819c8e0bd298c04f6fed0e6a83cc1356ca155 69 | 70 | `right`: 0x817de36ab2d57feb077634bca77819c8e0bd298c04f6fed0e6a83cc1356ca155 71 | 72 | Output: 73 | 74 | `nodeValue` : 0xffe9fc03f18b176c998806439ff0bb8ad193afdb27b2ccbc88856916dd804e34 75 | 76 | (3)test case 1 77 | 78 | Input: 79 | 80 | `level` : 2 81 | 82 | `left` : 0xffe9fc03f18b176c998806439ff0bb8ad193afdb27b2ccbc88856916dd804e34 83 | 84 | `right`: 0xffe9fc03f18b176c998806439ff0bb8ad193afdb27b2ccbc88856916dd804e34 85 | 86 | Output: 87 | 88 | `nodeValue` : 0xd8283386ef2ef07ebdbb4383c12a739a953a4d6e0d6fb1139a4036d693bfbb6c 89 | 90 | ## Implementation 91 | * https://github.com/tronprotocol/java-tron/blob/master/actuator/src/main/java/org/tron/core/vm/PrecompiledContracts.java 92 | * https://github.com/Federico2014/java-tron/blob/feature/shieldedUSDT/deploy/ShieldedTRC20.sol 93 | 94 | 95 | ## Copyright 96 | 97 | Copyright and related rights waived via [CC0](LICENSE.md). 98 | 99 | 100 | -------------------------------------------------------------------------------- /tip-156.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 156 3 | title: Vote instructions in TVM 4 | author: taihao.fu@gmail.com 5 | status: Draft 6 | type: Standards Track 7 | category : Core 8 | created: 2020-06-03 9 | 10 | ``` 11 | 12 | ## Simple Summary 13 | 14 | To provide vote related operations in TVM. 15 | 16 | ## Abstract 17 | 18 | Vote & withdrawReward operation in system contract are introduced, smart contract can vote for witness and get reward from the system. 19 | 20 | ## Motivation 21 | 22 | Common user can vote for activated witness to get block reward. However, none privatekey accounts, like smart contracts, can't get benefit from this incentive mechanism. This TIP provide instructions to implement the incentive functionalities. 23 | 24 | ## Specification 25 | 26 | The following instructions are introduced: 27 | 28 | ### `0xd9`: `VOTE` 29 | 30 | The `VOTE` takes 4 operands pop up from stack: 31 | 32 | `witnessOffset`: witness information offset. 33 | 34 | `witnessSize`: witness information size. 35 | 36 | `tronPowerOffset`: tron power information. 37 | 38 | `tronPowerSize`: tron power information array size. 39 | 40 | TVM will get sr array from memory by using `witnessOffset` and `witnessSize`. 41 | 42 | TVM will get tron power nubmer array from memory by using `tronPowerOffset` and `tronPowerSize`. 43 | 44 | Execute vote function and push 0 to stack if fail, push 1 otherwize. 45 | 46 | ### `0xda`: `WITHDRAWREWARD` 47 | 48 | The `WITHDRAWREWARD` takes 1 operand from stack. 49 | 50 | `accountAddress`: target account address. 51 | 52 | Execute withdraw function and push 0 to stack if fail, push 1 otherwise. 53 | 54 | ### `0xdc`: `ISWITNESS` 55 | 56 | The `ISWITNESS` takes 1 operand from stack. 57 | 58 | `accountAddress`: target account address. 59 | 60 | Push 0 if target address is not a witness, otherwise push 1. 61 | 62 | ### Result show in SystemLog 63 | 64 | SystemLog is contains system level operation result in transactioninfo for a specific transaction. 65 | 66 | A system log structure can be defined as below: 67 | 68 | ``` 69 | message SystemLog { 70 | enum operationType { 71 | VOTE = 1; 72 | WITHDRAWREWARD = 2; 73 | } 74 | bytes address = 1; // user address or contract address 75 | repeated bytes params = 2; 76 | // VOTE contains 2 parameters: VOTE(toAddress, TRONPowerValue); 77 | // WITHDRAWREWARD contains 1 parameter: WITHDRAWREWARD(toAddress); 78 | 79 | operationType type = 3; 80 | } 81 | ``` 82 | 83 | Vote and withdraw infomation will be record in the SystemLog field in transactionInfo. 84 | 85 | ## Rationale 86 | 87 | `VOTE` tier.ExtTier 88 | 89 | `WITHDRAWREWARD` tier.ExtTier 90 | 91 | `REWARDBALANCE` tier.ExtTier 92 | 93 | `ISWITNESS` tier.ExtTier 94 | 95 | 96 | ## Copyright 97 | 98 | Copyright and related rights waived via [CC0](LICENSE.md). 99 | -------------------------------------------------------------------------------- /tip-17.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 17 3 | title: Adaptive Energy Limit Model 4 | author: nanfengpo 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/17 6 | status: Final 7 | type: Standards Track 8 | category: TRC 9 | created: 2018-12-29 10 | ``` 11 | 12 | ## Simple Summary 13 | 14 | This doc describes the standard interface of the Adaptive Energy Limit Model 15 | 16 | 17 | ## Abstract 18 | 19 | In the current TRON network, the creation and operation of smart contracts require Energy consumption. Energy can only be obtained by freezing TRX, the amount of Energy obtained = TRX/Total TRX * Total Energy Limit of the whole network for obtaining Energy frozen. 20 | 21 | For example, if the total amount of TRX frozen for Energy in the current network is 1_000_000_000 TRX, and an account with 1_000 TRX frozen accounts for one-millionth of the total amount frozen, then the Energy limit for that account is 32400 Energy. 22 | 23 | However, if some accounts freeze TRX and have the corresponding energy, but do not use it, energy resources will be wasted. To this end, the Adaptive Energy Limit Model is proposed in this document. This model can automatically adjust the upper limit of energy according to the current energy consumption tension. Specifically, 24 | - when energy consumption is low, increase the energy limit so that each account can get more energy 25 | - when energy consumption is high, lower the energy ceiling so that each account has less energy 26 | 27 | ## Motivation 28 | 29 | 1. Avoid waste of energy resources; 30 | 2. Each account has more energy resources; 31 | 32 | ## Implementation 33 | 34 | This model adjusts the energy owned by each account by adjusting the total upper limit of the total network energy. For the energy of the entire Tron network, there are the following measures: 35 | - Real Energy Limit: An upper limit on the real capacity of the TRON network within 24 hours. The current value is 100 billion. This value can be modified by proposal. 36 | - Virtual Energy Limit: An upper limit on the virtual capacity of the TRON network within 24 hours. Used to calculate the energy owned by an address in real-time, changes per block.The current maximum is 50 times the Real Energy Limit. The multiplier 50 can be adjusted by the proposal. 37 | - Target Energy Limit: The target upper limit of Energy consumed in one minute (equal to 50% * RealEnergyLimit/(24 * 60)), used to measure whether the TotalEnergyAverageUsage in the past minute is small or large, so as to determine whether the virtual upper limit is high or low, that is, whether the network is congested or not. The ratio 50% can be adjusted by the proposal.[will change as the RealEnergyLimit changes] 38 | - Average energy usage over the last minute: changes per block 39 | 40 | Adjustment strategy: 41 | The width of the sliding window is 1 minute. Calculate the average Energy usage in a window: 42 | - increase the Virtual Energy Limit when the usage amount is greater than the Target Energy Limit within 1min. The increase is 1/1000. The maximum is increased to 50 times the Real Energy Limit 43 | - if the usage amount is less than the Target Energy Limit within 1min, the Virtual Energy Limit will be reduced. The reduction is 1/100. The minimum is reduced to one times the Real Energy Limit 44 | 45 | For example, the initial Virtual Energy Limit is 500_000_000_000L and the target ceiling is 500_000_000L. 46 | When the energy usage is <500_000_000 in the first minute, Virtual Energy Limit:= Virtual Energy Limit *1000/999 = 500_500_000_000. When the energy usage is >500_000_000 in the second minute, Virtual Energy Limit = Virtual Energy Limit *99/100=495_500_000_000. However, the Virtual Energy Limit is within the range of [Real Energy Limit, Real Energy Limit * 1000], that is, after the second minute, the Virtual Energy Limit is still 500_000_000_000 47 | 48 | 49 | ## Copyright 50 | 51 | Copyright and related rights waived via [CC0](LICENSE.md). 52 | 53 | 54 | -------------------------------------------------------------------------------- /tip-171.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 171 3 | title: STAKE instructions in TVM 4 | author: taihao.fu@gmail.com 5 | status: Draft 6 | type: Standards Track 7 | category : Core 8 | created: 2020-08-05 9 | 10 | ``` 11 | 12 | ## Simple Summary 13 | 14 | To provide Staking operations in TVM. 15 | 16 | ## Abstract 17 | 18 | This is a simplified solution for PoS incentive mechanism in smart contract. 19 | 20 | ## Motivation 21 | 22 | Current mechanism allows a normal privatkey address to vote for SR and get dividend, while TRX locked in smart contract can't get benefit from the mechanism. This TIP introduced a new way to support vote and get block procude reward in smart contracts. This will motivate more developers for their DApp developing. They should be able to get more profit from their products. 23 | 24 | ## Specification 25 | 26 | The following instructions are introduced: 27 | 28 | ### `0xd5`: `STAKE` 29 | 30 | `STAKE` is a TRX staking to get TRON Powever and voting SR process for a smart contract. 31 | 32 | FACTS: 33 | 34 | 1. STAKE ONLY available for single SR. 35 | 2. As long as a STAKE be executed, it is not adding a vote information, but replacing the entire vote information belongs to the contract itself. 36 | 37 | The `STAKE` takes 2 operands pop up from stack: 38 | 39 | `sr_address`: the target address to vote. 40 | 41 | `stake_amount`: TRX amount to freeze in SUN. 42 | 43 | Will process following logic: 44 | 45 | 1. Contract stake trx as bandwidth and add the frozen amount to its `Account.frozenBalance`. The default staking period is 3 days. 46 | 2. Contract update vote information in voteStore and accountStore (**this will replace the entire vote state for owner, not append**) 47 | 48 | Execute STAKE function and push 0 to stack if fail, push 1 otherwise. 49 | 50 | ### `0xd6`: `UNSTAKE` 51 | 52 | `UNSTAKE` is a TRX unstaking and clear all votes process for a smart contract. 53 | 54 | The `UNSTAKE` takes 0 operands from stack. 55 | 56 | Will process following logic: 57 | 58 | 1. 3 days after the last `STAKE` operation for this contract, the contract can choose to `UNSTAKE` its TRX. 59 | 2. Update block produce reward balance for this contract. 60 | 3. Unfrozne balance in contract. 61 | 4. Contract clears vote information. 62 | 63 | Execute UNSTAKE function and push 0 to stack if fail, push 1 otherwise. 64 | 65 | ### `0xd7`: `WITHDRAWREWARD` 66 | 67 | A smart contract can collects block produce reward by using `WITHDRAWREWARD` instruction. 68 | 69 | The `WITHDRAWREWARD` takes 0 operand from stack. 70 | 71 | Execute withdraw function and push exact balance value to stack if success, push 0 if it is failed. 72 | 73 | ### `0xd8`: `REWARDBALANCE` 74 | 75 | Show current reward balance for an address 76 | 77 | The `REWARDBALANCE` takes 1 operand from stack. 78 | 79 | `accountAddress`: target account address. 80 | 81 | Push the block reward balance of the target address to stack. 82 | 83 | ### `0xd9`: `ISWITNESS` 84 | 85 | Check if a target address is a witness. 86 | 87 | The `ISSRCANDIDATE` takes 1 operand from stack. 88 | 89 | `accountAddress`: target account address. 90 | 91 | Push 0 if target address is not a candidate witness, otherwise push 1. 92 | 93 | ## Rationale 94 | 95 | ### `STAKE` tier.ExtTier 96 | 97 | 7 key changes: 98 | 99 | dynamiceStore: `TOTAL_NET_WEIGHT` 100 | 101 | AccountStore: the contract account key 102 | 103 | delegateStore: `Remark`,`BeginCycle`,`EndCycle`,`AccountVote` 104 | 105 | VoteStore: the contract vote key 106 | 107 | 35,000 Energy = 7 * 5000 108 | 109 | ### `UNSTAKE` tier.ExtTier 110 | 111 | 7 key changes: 112 | 113 | dynamiceStore: `TOTAL_NET_WEIGHT` 114 | 115 | AccountStore: the contract account key 116 | 117 | delegateStore: `Remark`,`BeginCycle`,`EndCycle`,`AccountVote` 118 | 119 | VoteStore: the contract vote key 120 | 121 | 35,000 Energy = 7 * 5000 122 | 123 | ### `WITHDRAWREWARD` tier.ExtTier 124 | 125 | 5 key changes: 126 | 127 | ccountStore: the contract account key 128 | 129 | delegateStore: `Remark`,`BeginCycle`,`EndCycle`,`AccountVote` 130 | 131 | 25,000 Energy = 5 * 5000 132 | 133 | ### `REWARDBALANCE` tier.ExtTier 134 | 135 | 20 Energy 136 | 137 | ### `ISWITNESS` tier.ExtTier 138 | 139 | 20 Energy 140 | 141 | 142 | ## Copyright 143 | 144 | Copyright and related rights waived via [CC0](LICENSE.md). 145 | -------------------------------------------------------------------------------- /tip-174.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 174 3 | title: CHAINID instructions in TVM 4 | author: taihao.fu@gmail.com 5 | status: Final 6 | type: Standards Track 7 | category : VM 8 | created: 2020-08-12 9 | 10 | ``` 11 | 12 | ## Simple Summary 13 | 14 | To provide CHAINID instruction in TVM. 15 | 16 | ## Abstract 17 | 18 | This is value can be read from smart contract to distinguish current chain with other chains. 19 | 20 | ## Motivation 21 | 22 | Currently we have multiple chains in TRON ecosystem those are build from 3 main ways: testnets, side-chain and cross-chains.From smart contract perspective, currently we don't have a mechnism to distinguish those chains, which leads to potential replay attacks. As a result, a chainid parameter is required in TVM level to guanrantee smart contract safety. 23 | 24 | ## Specification 25 | 26 | ### `0x46`: `CHAINID` 27 | 28 | `CHAINID` takes 0 operands pop up from stack. 29 | 30 | The return value is the genesis block id for this chain as uint256. 31 | 32 | ## Rationale 33 | 34 | ### `CHAINID` tier.ExtTier 35 | 36 | 20 Energy 37 | 38 | 39 | ## Copyright 40 | 41 | Copyright and related rights waived via [CC0](LICENSE.md). 42 | 43 | -------------------------------------------------------------------------------- /tip-175.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 175 3 | title: SELFBALANCE instructions in TVM 4 | author: taihao.fu@gmail.com 5 | status: Final 6 | type: Standards Track 7 | category : VM 8 | created: 2020-08-12 9 | 10 | ``` 11 | 12 | ## Simple Summary 13 | 14 | To provide SELFBALANCE instruction in TVM. 15 | 16 | ## Abstract 17 | 18 | This is value can directly get current address balance. 19 | 20 | ## Motivation 21 | 22 | Currently we have `BALANCE` to get TRX value for a specific address. We may consider to increase `BALANCE` energy cost in future for security purpose. But balance for current address is usually consider as a seperate case and it should keeps in a cheap price level. As a result, `SELFBALANCE` is introduced here. 23 | 24 | ## Specification 25 | 26 | ### `0x47`: `SELFBALANCE` 27 | 28 | `SELFBALANCE` takes 0 operands pop up from stack. 29 | 30 | The return value the current address account balance. 31 | 32 | ## Rationale 33 | 34 | ### `SELFBALANCE` tier.ExtTier 35 | 36 | 20 Energy 37 | 38 | ## Copyright 39 | 40 | Copyright and related rights waived via [CC0](LICENSE.md). 41 | -------------------------------------------------------------------------------- /tip-176.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 176 3 | title: altbn128 operation energy reduction in TVM 4 | author: taihao.fu@gmail.com 5 | status: LastCall 6 | type: Standards Track 7 | category : VM 8 | created: 2020-08-12 9 | 10 | ``` 11 | 12 | ## Simple Summary 13 | 14 | To provide altbn128 related operations energy reduction in TVM. 15 | 16 | ## Abstract 17 | 18 | Precompile contracts altbn128 addition/multiplication/pairing energy reduction. 19 | 20 | ## Motivation 21 | 22 | Use latest research result and improve user experience when trigger contract contains `altbn128` functionalities. Also avoid to hit 1000 TRX feelimit and increase the capbility for altbn128 running times in single transaction. 23 | 24 | ## Specification 25 | 26 | ### `0x06`: `Altbn128Addition` 27 | 28 | `500` -> `150` 29 | 30 | ### `0x07`: `Altbn128Multiplication` 31 | 32 | `40000` -> `6000` 33 | 34 | ### `0x08`: `Altbn128Paring` 35 | 36 | `80000 * pairs + 100000` -> `34000 * pairs + 45000` 37 | 38 | ## Copyright 39 | 40 | Copyright and related rights waived via [CC0](LICENSE.md). 41 | -------------------------------------------------------------------------------- /tip-178.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 178 3 | title: TOKENISSUE and UPDATEASSET Instruction in TVM 4 | author: taihao.fu@gmail.com 5 | status: Draft 6 | type: Standards Track 7 | category : Core 8 | created: 2020-08-12 9 | 10 | ``` 11 | 12 | ## Simple Summary 13 | 14 | To provide TOKENISSUE and UPDATEASSET Instructions in TVM. 15 | 16 | ## Abstract 17 | 18 | Provide TRC10 asset issue and update functionalities for smart contract. 19 | 20 | ## Motivation 21 | 22 | Asset issued in smart contract is feasible for developers to provide asset management according to a smart contract status. Asset issue related instruction is a big plus to the whole life cycle of TRC10. Previous implementation only consider about TRC10 transfer cases. However, a coinbase for TRC10 token is never mentioned in TVM level. `ASSETISSUE` instruction pefect the whole logic system. And makes TRC10 fully controlled by decentralized exchanges and apps to be possible. 23 | 24 | ## Specification 25 | 26 | ### `0xda`: `TOKENISSUE` 27 | 28 | `TOKENISSUE` takes 4 operands pop up from stack. 29 | 30 | `name`: the name of the TRC10 token. No more than 32 bytes. 31 | 32 | `abbreviation`: the abbreviation of the TRC10 token. No more than 32 bytes. 33 | 34 | `total_supply`: the total supply of the TRC10 token. A uint64 value. 35 | 36 | `precision`: the precision of the TRC10 token. A uint8 value. 37 | 38 | The return value the current address account balance. 39 | 40 | ### `0xdb`: `UPDATEASSET` 41 | 42 | `UPDATEASSET` takes 4 operands pop up from stack. 43 | 44 | `TRC10_token_id`: the TRC10 token id. Should bigger than 1000000. 45 | 46 | `url_offset`: read the token url as a string, and the value is the string offset in TVM memory. 47 | 48 | `description_offset`: read the token description as a string, and the value is the string offset in TVM memory. 49 | 50 | The return value the current address account balance. 51 | 52 | ## Rationale 53 | 54 | ### `TOKENISSUE` tier.ExtTier 55 | 56 | 25000 Energy 57 | 58 | ### `UPDATEASSET` tier.ExtTier 59 | 60 | 5000 Energy 61 | 62 | ## Copyright 63 | 64 | Copyright and related rights waived via [CC0](LICENSE.md). 65 | -------------------------------------------------------------------------------- /tip-191.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 191 3 | title: Signed Data Standard 4 | author: yanghang8612@163.com 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/442 6 | status: Final 7 | type: Standards Track 8 | category: TRC 9 | created: 2022-07-25 10 | ``` 11 | 12 | ## Abstract 13 | 14 | This TIP proposes a specification about how to handle signed data in TRON contracts. 15 | 16 | ## Motivation 17 | 18 | Off-chain message signing for use on-chain now is widely used by some multisignature wallet implementations and tokens with `permit` method. 19 | 20 | However, there is currently no standard for off-chain message signing for TRON protocol, so this TIP aims to introduce an signed data standard similar to [EIP-191](https://eips.ethereum.org/EIPS/eip-191). 21 | 22 | ## Specification 23 | 24 | We propose the following format for `signed_data` 25 | 26 | ``` 27 | 0x19 <1 byte version> . 28 | ``` 29 | 30 | The format is totaly cmpatible with `EIP-191`. 31 | 32 | Version `0` has `<20 byte address>` for the version specific data, and the `address` is the intended validator. In the case of a Multisig wallet, that is the wallet’s own address. 33 | 34 | The initial `0x19` byte is intended to ensure that the `signed_data` is not valid beginning byte for `Transaction` and `Block`. Because in TRON protocol, the bytestrings transformed by the protobuf structure of `Transaction.raw` and `Block.Header` cannot start with `0x19`. 35 | 36 | ### Registry of version bytes 37 | 38 | | Version byte | TIP | Description 39 | | ------------ | -------------- | ----------- 40 | | `0x00` | [191](https://github.com/tronprotocol/tips/issues/442) | Data with intended validator 41 | | `0x01` | [712](https://github.com/tronprotocol/tips/issues/443) | Structured data 42 | 43 | ### Signatures and Hashing 44 | 45 | A signature scheme consists of hashing algorithm and a signing algorithm. The signing algorithm of choice is `secp256k1`. The hashing algorithm of choice is `keccak256`. 46 | 47 | ## Copyright 48 | 49 | Copyright and related rights waived via [CC0](LICENSE.md). 50 | -------------------------------------------------------------------------------- /tip-196.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip:196 3 | title: Reward SRs with the transaction fees charged for bandwidth and Energy 4 | author: sean liu 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/196 6 | status: Final 7 | type: Standards Track 8 | category: core 9 | created: 2020-12-06 10 | ``` 11 | 12 | ## Simple Summary 13 | Reward SRs with the transaction fees charged for bandwidth and Energy. 14 | 15 | ## Abstract 16 | With the development of the TRON network, the TRON network ecosystem has become increasingly prosperous. 17 | At the same time, SR (Super Representatives) also need to consume more resources to maintain the entire network, 18 | which includes higher hardware demand and higher maintenance cost. 19 | The current rewards given to each SR include 16 TRX for block production and 160 TRX for voting. 20 | Compared with other public blockchains, the TRON network currently lacks the mechanism for rewarding SR with transaction fees. 21 | The transaction fee of the TRON network is mainly caused by energy and bandwidth consumption. 22 | Currently, all the transaction fee is transferred to the black hole account. 23 | 24 | ## Motivation 25 | In order to further improve the stability and efficiency of the TRON network, 26 | it is proposed to increase the rewards for SRs. 27 | The transaction fees charged by energy and bandwidth consumption can be rewarded to SR, 28 | and they are distributed to voters like rewards for producing block. 29 | Transaction fees will increase the enthusiasm of SR to maintain the network. 30 | At the same time, the transaction fee mechanism can effectively prevent SR from producing blank blocks that contain 0 transactions. 31 | 32 | ## Specification 33 | Previously, in each transaction, if a user burned TRX to obtain energy and bandwidth, 34 | the transaction fee was directly transferred to the black hole, and now it is transferred to the fee pool. 35 | At the end of each block, the fee of all transactions in this block is rewarded to the block SR, 36 | which is the total number in the fee pool. The reward method is similar to the block reward. 37 | 38 | #### Storage data definition 39 | In the storage method, add TRANSACTION_FEE_POOL to dynamicStore to store transaction fees. 40 | ``` 41 | private static final byte[] TRANSACTION_FEE_POOL = "TRANSACTION_FEE_POOL".getBytes(); 42 | ``` 43 | 44 | In the TransactionInfo protocol, add packingFee to record the fee rewarded to the SR and voters. 45 | ``` 46 | message TransactionInfo { 47 | ... 48 | int64 packingFee = 27; 49 | } 50 | ``` 51 | #### Transaction processing 52 | In the process of transaction processing, the fee generated by each transaction, 53 | including bandwidth fee and energy fee, is directly transferred to TRANSACTION_FEE_POOL. 54 | 55 | ``` 56 | //bandwidth fee code 57 | if (dynamicPropertiesStore.supportTransactionFeePool()) { 58 | dynamicPropertiesStore.saveTransactionFeePool(dynamicPropertiesStore.getTransactionFeePool() + fee); 59 | } else { 60 | Commons.adjustBalance(accountStore, accountStore.getBlackhole().createDbKey(), +fee); 61 | } 62 | ``` 63 | ``` 64 | //energy fee code 65 | if (dynamicPropertiesStore.supportTransactionFeePool() && 66 | !contractResult.equals(contractResult.OUT_OF_TIME)) { 67 | dynamicPropertiesStore.saveTransactionFeePool(dynamicPropertiesStore.getTransactionFeePool() + energyFee); 68 | } else { 69 | //send to blackHole 70 | Commons.adjustBalance(accountStore, accountStore.getBlackhole().getAddress().toByteArray(),energyFee); 71 | } 72 | ``` 73 | For the fees of timeout smart contract transaction, 74 | it should continue to transfer them to the black hole account to avoid malicious SRs from deliberately 75 | setting the transaction overtime to obtain high fees. 76 | 77 | #### Produce block 78 | When the block is packaged, all transaction fees in the TRANSACTION_FEE_POOL will be rewarded to the block-producing SR. 79 | If the SR adopts the default reward distribution method, then 20% of it will be transferred to the SR and 80% to the voters. 80 | ``` 81 | if (chainBaseManager.getDynamicPropertiesStore().supportTransactionFeePool()) { 82 | long transactionFeeReward = Math 83 | .floorDiv(chainBaseManager.getDynamicPropertiesStore().getTransactionFeePool(), 84 | Constant.TRANSACTION_FEE_POOL_PERIOD);//Constant.TRANSACTION_FEE_POOL_PERIOD=1 85 | mortgageService.payTransactionFeeReward(witnessCapsule.getAddress().toByteArray(), 86 | transactionFeeReward);//reward distribution method 87 | chainBaseManager.getDynamicPropertiesStore().saveTransactionFeePool( 88 | chainBaseManager.getDynamicPropertiesStore().getTransactionFeePool() 89 | - transactionFeeReward); 90 | } 91 | ``` 92 | 93 | 94 | ## Backward Compatibility 95 | There are no backward compatibility concerns. 96 | 97 | ## Test Cases 98 | 1. Check the balance of the black hole account after the implementation of the new solution. 99 | 2. Check the reward income of the SR. 100 | 3. Check the recipient of fee for the timeout transaction. 101 | 102 | 103 | ## Copyright 104 | 105 | Copyright and related rights waived via [CC0](LICENSE.md). 106 | -------------------------------------------------------------------------------- /tip-203.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 203 3 | title: Adaptation to solidity-v0.5.15 4 | author: yanghang8612 5 | status: Final 6 | type: Standards Track 7 | category: VM 8 | created: 2020-12-03 9 | ``` 10 | 11 | ## Simple Summary 12 | 13 | An adaptation to solidity-v0.5.15 14 | 15 | ## Abstract 16 | 17 | Ethereum released version 0.5.15 of solidity to fix a bug. Solidity in tron should be updated to follow this release. 18 | 19 | ## Motivation 20 | 21 | The release of solidity-v0.5.15 means this bugfix about Yul Optimizer is very necessary. We should update solidity to follow this release as soon as possible. 22 | 23 | ## Specification 24 | 25 | The previous release of solidity introduced an incorrect redundant load optimization crossing user-defined functions that contain for-loops with memory / storage writes. This bug may cause wrong results even failure of function calls. The release of solidity-v0.5.15 fixed this bug quickly. So we should update solidity in Tron to follow this release. 26 | 27 | ## Copyright 28 | 29 | Copyright and related rights waived via [CC0](LICENSE.md). 30 | 31 | -------------------------------------------------------------------------------- /tip-204.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 204 3 | title: Make MAX_FEE_LIMIT configurable as a chain property 4 | author: yanghang8612 5 | status: Final 6 | type: Standards Track 7 | category: VM 8 | created: 2020-12-07 9 | ``` 10 | 11 | ## Simple Summary 12 | 13 | MAX_FEE_LIMIT Should be Configurable. 14 | 15 | ## Abstract 16 | 17 | Fixed `MAX_FEE_LIMIT` is not suitable as the cost of energy increases a lot recently. So we should make `MAX_FEE_LIMIT` configurable in order to adjust dynamically. 18 | 19 | ## Motivation 20 | 21 | As the cost of energy increased, in some cases, `MAX_FEE_LIMIT` may be insufficient. So we should change `MAX_FEE_LIMIT` to be a configurable parameter. If needed, we could make a proposal to update this parameter to a higher value. 22 | 23 | ## Specification 24 | 25 | There are mainly two steps as follows. 26 | 27 | First, add `MAX_FEE_LIMIT` to dynamicStore and initialize by current value. 28 | 29 | Second, create a new proposal which can modify the value of `MAX_FEE_LIMIT` if needed. 30 | 31 | ## Copyright 32 | 33 | Copyright and related rights waived via [CC0](LICENSE.md). 34 | -------------------------------------------------------------------------------- /tip-207.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip:207 3 | title: A proposal to improve network resources model 4 | author: sean Liu 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/207 6 | status: Final 7 | type: Standards Track 8 | category: core 9 | created: 2020-03-26 10 | ``` 11 | 12 | ## Simple Summary 13 | This proposal proposes a new scheme to try to solve the problem of the low utilization rate of network frozen resources, 14 | reduce user usage costs, and improve resource models. 15 | This optimization may lead to more accounts freezing TRX to obtain resources and further increase the TVL of the TRON network. 16 | 17 | The core idea is that freezing TRX only gets Bandwidth, Energy, or Tron Power. 18 | 19 | In order to guarantee the stability of the network and the rights of users, 20 | the Tron Power and resources obtained before can be retained at the same time. 21 | 22 | ## Motivation 23 | Currently, freezing TRX can obtain Bandwidth or Energy, while obtaining Tron Power. 24 | Many accounts freeze a large amount of TRX for voting only but do not use resources. 25 | This results in accounts that really need resources only get a small part of resources and network resources are wasted. 26 | 27 | ## Specification 28 | There are two new parameters that will be added into account data structure: 29 | "old_tron_power" and "tron_power". 30 | 31 | "old_tron_power" is used to record the Tron Power before the proposal, which is the sum of frozen TRX for the Bandwidth and Energy. 32 | 33 | "tron_power" is used to record the Tron Power after the proposal. 34 | 35 | ``` 36 | message Account { 37 | ... 38 | int64 old_tron_power = 46; 39 | Frozen tron_power = 47; 40 | } 41 | ``` 42 | 43 | 44 | In the FreezeBalanceContract and UnFreezeBalanceContract, TRON_POWER is added into ResourceCode. 45 | ``` 46 | enum ResourceCode { 47 | BANDWIDTH = 0x00; 48 | ENERGY = 0x01; 49 | TRON_POWER = 0x02; 50 | } 51 | ``` 52 | 53 | There is a new chain parameter called TOTAL_TRON_POWER_WEIGHT, which is used to record the new Tron Power in the whole network. 54 | ``` 55 | private static final byte[] TOTAL_TRON_POWER_WEIGHT = "TOTAL_TRON_POWER_WEIGHT".getBytes(); 56 | ``` 57 | 58 | Tron Power info is added into AccountResourceMessage. Users could get Tron Power info using "GetAccountResource". 59 | In AccountResourceMessage, TotalTronPowerWeight is the total new Tron Power that users freeze for TRON_POWER in the whole network. 60 | TronPowerLimit is the total Tron Power the user has, include old Tron Power and new Tron Power. 61 | TronPowerUsed is the Tron Power the user already used for votes. 62 | 63 | ``` 64 | message AccountResourceMessage { 65 | int64 TotalTronPowerWeight = 9; 66 | int64 tronPowerUsed = 10; 67 | int64 tronPowerLimit = 11; 68 | } 69 | ``` 70 | 71 | ## Implementation 72 | After the proposal, when the account sends the first voting witness or freezing TRX transaction, 73 | the "old_tron_power" of the account will be calculated and initialized. The "old_tron_power" is the sum of frozen TRX for the Bandwidth and Energy before. 74 | 75 | The "old_tron_power" will not increase even if the account freeze more TRX for the Bandwidth and Energy. 76 | 77 | Pay attention, "old_tron_power" will be clear when the account sends an unfreeze operation, includes unfreezing Bandwidth、Energy or Tron Power, and will not set anymore. 78 | 79 | If the account wants more Tron Power, the account could freeze TRX for Tron Power specifically. 80 | 81 | When the account wants to vote a witness, Tron Power is the sum of "old_tron_power" and "tron_power" in the account. 82 | 83 | In normal, the votes of an account will be clear when the account sent an unfreeze operation. 84 | But when the "old_tron_power" is equal to -1, the votes must come from the new "tron_power", 85 | unfreezing Bandwidth OR Energy should not affect the votes, so the votes are reserved. 86 | 87 | In addition, the new Tron power is also not allowed to delegate to other accounts. 88 | 89 | ## Comparison with present situation 90 | In order to further classify the change after the proposal, we make a comparison on the key points. 91 | 92 | First, before the proposal, the account could only freeze TRX for the Bandwidth and Energy to obtain Tron Power. 93 | After the proposal, the account should obtain Tron Power by freezing for Tron Power specifically. 94 | 95 | Second, before the proposal, the Tron Power of an account is the sum of frozen TRX for the Bandwidth and Energy. 96 | After the proposal, all Tron Power of an account includes the "old_tron_power", and the new "tron_power" 97 | where the "old_tron_power" representative the past Tron Power value. 98 | 99 | Later, before the proposal, the votes will be clear, when the account sends an unfreezing transaction. 100 | After the proposal, in most situation, the votes will be clear too, but when the "old_tron_power" is equal to -1, and the operation is unfreezing Bandwidth OR Energy, 101 | the votes will be reserved. 102 | 103 | 104 | ## Backward Compatibility 105 | There are no backward compatibility concerns. 106 | 107 | ## Test Cases 108 | 1. Check the "old_tron_power" is correct after a freezing operation. 109 | 2. Check the "old_tron_power" is clear after an unfreeze operation. 110 | 3. Check the Tron Power is the sum of "old_tron_power" and "tron_power". 111 | 112 | 113 | ## Copyright 114 | 115 | Copyright and related rights waived via [CC0](LICENSE.md). 116 | -------------------------------------------------------------------------------- /tip-209.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 209 3 | title: Adapt to Solidity 0.6.0. 4 | author: neo hong neo.hong@tron.network 5 | discussions to: https://github.com/tronprotocol/tips/issues/209 6 | status: Final 7 | type: Standards Track 8 | category : VM 9 | created: 2020-12-07 10 | ``` 11 | 12 | ## Simple Summary 13 | 14 | Adapt to Solidity 0.6.0. 15 | 16 | ## Abstract 17 | 18 | Update Java-Tron and Tron solidity compiler adapt to solidity 0.6.0. 19 | 20 | ## Motivation 21 | 22 | Solidity 0.6.0 provides many features which can improve development efficiency and safety. Solidity 0.6.0 is a major breaking release of the Solidity compiler and language. Changes include explicit virtual and override keywords in inheritance, support for try/catch, splitting the fallback function into a receive TRX function and an actual fallback function and limitations on how the length of an array can be changed, among others. From this release on, ABIEncoderV2 is not considered experimental any more, but developers still have to activate it through the pragma. Furthermore, the Yul optimizer is automatically activated together with the regular optimizer, but developers can still disable it through the detailed optimizer settings. 23 | 24 | ## Specification 25 | 26 | ### Breaking changes 27 | - ABI: Remove the deprecated `constant` and `payable` fields. 28 | - ABI: The type field is now required and no longer specified to default to `function`. 29 | - General: Disallow explicit conversions from external function types to `address` and add a member called `address` to them as replacement. 30 | - General: Enable Yul optimizer as part of standard optimization. 31 | - General: New reserved keywords: `override`, `receive`, and `virtual`. 32 | - General: private cannot be used together with `virtual`. 33 | - General: Split unnamed fallback functions into two cases defined using `fallback()` and `receive()`. 34 | - Syntax: `push(element)` for dynamic storage arrays do not return the new length anymore. 35 | - Syntax: Abstract contracts need to be marked explicitly as abstract by using the `abstract` keyword. 36 | - Syntax: `length` member of arrays is now always read-only, even for storage arrays. 37 | 38 | ### Language Features: 39 | - Allow explicit conversions from `address` to `address payable` via `payable(...)`. 40 | - Introduce `push()` for dynamic storage arrays. It returns a reference to the newly allocated element, if applicable. 41 | - Introduce `virtual` and `override` keywords. 42 | - Introduce `try`/`catch`-statement(`revert` and `require` can be caught now, others will be supported soon). 43 | - Modify `push(element)` for dynamic storage arrays such that it does not return the new length anymore. 44 | 45 | ### Compiler Features: 46 | - Allow revert strings to be stripped from the binary using the `--revert-strings` option or the `settings.debug.revertStrings` setting. 47 | - ABIEncoderV2: Do not warn about enabled ABIEncoderV2 anymore (the pragma is still needed, though). 48 | 49 | 50 | ## Copyright 51 | 52 | Copyright and related rights waived via [CC0](LICENSE.md). 53 | -------------------------------------------------------------------------------- /tip-222.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip:222 3 | title: Improve transaction execution speed 4 | author: Kiven 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/222 6 | status: Final 7 | type: Standards Track 8 | category: TRC 9 | created: 2021-01-06 10 | ``` 11 | 12 | ## Simple Summary 13 | This TIP provides Improve transaction execution speed for java-tron. 14 | 15 | ## Abstract 16 | In the current Tron ecosystem, the destroyed TRX is transferred to the black hole account. When performing transfers, the black hole account needs to be serialized and deserialized. Since the black hole account contains less TRC10 tokens, serialization and deserialization will hardly affect the performance. However, with the development of time, there are currently a large number of TRC10 tokens in the black hole account, which has a great impact on performance during serialization and deserialization. From our current test, the performance is reduced by 50% to 100%. 17 | 18 | ## Motivation 19 | Improve the performance of the TRON network and increase the QPS of transactions. 20 | 21 | ## Rationale 22 | void burnTrx(long number): The method of destroying TRX, the value is accumulated and recorded in the DynamicPropertiesStore database 23 | 24 | long getBurnTrxAmount(): Get the method of destroying the total TRX amount from the DynamicPropertiesStore 25 | 26 | boolean supportOptimizeBlackHole(): Whether to open the proposal to remove the blackhole account 27 | 28 | ## Desired Features: 29 | It can improve the QPS of the whole network transaction, and the performance can be improved by more than 50%. 30 | 31 | ## Technical Specifications: 32 | Since the performance degradation is caused by the serialization and deserialization of black hole accounts, to improve performance, we can remove the black hole accounts and use DynamicPropertiesStore to record the number of destroyed TRX. 33 | To make the database of the whole network consistent, we need to create a proposal to remove black hole accounts. 34 | 35 | ## Data Structures: 36 | The data structure of the amount of TRX destroyed: 37 | key: BURN_TRX; value: the number of TRX destroyed 38 | 39 | 40 | ## Copyright 41 | Copyright and related rights waived via [CC0](LICENSE.md). 42 | -------------------------------------------------------------------------------- /tip-23.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 23 3 | title: TRC-23 Add the account world status tree root to the block header 4 | author: lvs007 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/23 6 | status: Final 7 | type: Standards Track 8 | category: TRC 9 | created: 2019-03-04 10 | ``` 11 | 12 | ## Simple Summary 13 | 14 | The purpose is to verify the consistency of the entire account. 15 | 16 | ## Abstract 17 | 18 | Now it's hard to compare the consistency of each account database, so add the account world status tree root to the block header. The purpose is to verify the consistency of the entire account. 19 | 20 | ## Motivation 21 | 22 | ## Specification 23 | 24 | modify the block header structure, add the accountStateRoot 25 | ```message BlockHeader{ 26 | message raw 27 | {int64 timestamp = 1; 28 | bytes txTrieRoot = 2; 29 | bytes parentHash = 3; 30 | //bytes nonce = 5; 31 | //bytes difficulty = 6; 32 | int64 number = 7; 33 | int64 witness_id = 8; 34 | bytes witness_address = 9; 35 | int32 version = 10; 36 | bytes accountStateRoot = 11; 37 | } 38 | raw raw_data = 1; 39 | bytes witness_signature = 2; 40 | } 41 | ``` 42 | 43 | ###Account State Root Generate 44 | Introduced the Ethereum's world state tree model 45 | At a certain height, the block node starts to generate the root of the account status tree, and then adds the root to the block header. The subsequent block will generate a new account status tree with the account status tree in the previous block header as the root. 46 | The nodes of other blocks will generate a new world state tree root according to the transactions in the block, and compare whether the generated root is consistent with the root in the current block header. 47 | 48 | ###Account State Root Validate 49 | If the local account state and the account state of the block are inconsistent when the block is synchronized, a Bad Block exception will be thrown. 50 | 51 | 52 | ## Copyright 53 | 54 | Copyright and related rights waived via [CC0](LICENSE.md). 55 | -------------------------------------------------------------------------------- /tip-24.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 24 3 | title: Implement DB storage with RocksDB 4 | author: @shydesky 5 | discussions to: https://github.com/tronprotocol/tips/issues/24 6 | status: Final(core) 7 | type: Standards Track 8 | category: TRC 9 | created: 2019-03-04 10 | ``` 11 | 12 | ## Simple Summary 13 | 14 | Implement the database storage layer with RocksDB. 15 | 16 | ## Abstract 17 | 18 | Currently, the java-Tron project uses LevelDB as the only implement of the database storage layer. This Tip is created for the purpose of adding a new implementation of the database storage layer. 19 | 20 | ## Motivation 21 | 22 | RocksDB is a good storage engine built on earlier work on LevelDB and it is widely used in production environments. It has higher performance when storing key-value data benefiting from exploiting many CPU cores than LevelDB.RocksDB provides all of the features of LevelDB and some useful functions like backups and snapshots. It is very friendly to the developers to find the bottleneck of the system and contains many parameters used to tune RocksDB for your workload and your system configuration. 23 | So, it wisely adds the implementation of the database storage layer with RocksDB to make our java-Tron more effective and robust. 24 | 25 | ## Copyright 26 | 27 | Copyright and related rights waived via [CC0](LICENSE.md). 28 | -------------------------------------------------------------------------------- /tip-241.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 241 3 | title: Adaptation to solidity-v0.5.16 4 | author: yanghang8612 5 | status: Draft 6 | type: Standards Track 7 | category: VM 8 | created: 2021-03-08 9 | ``` 10 | 11 | ## Simple Summary 12 | 13 | An adaptation to solidity-v0.5.16 14 | 15 | ## Abstract 16 | 17 | Ethereum released version 0.5.16 of solidity to fix a bug. Solidity in tron should be updated to follow this release. 18 | 19 | ## Motivation 20 | 21 | The release of solidity-v0.5.16 means this bugfix about Yul Optimizer is very necessary. We should update solidity to follow this release as soon as possible. 22 | 23 | ## Specification 24 | 25 | The Yul optimizer has a stage that removes assignments to variables that are overwritten again or are not used in all following control-flow branches. This logic incorrectly removes such assignments to variables declared inside a for loop if they can be removed in a control-flow branch that ends with ``break`` or ``continue`` even though they cannot be removed in other control-flow branches. Variables declared outside of the respective for loop are not affected. So we should update Tron Solidity to fix this bug. 26 | 27 | ## Copyright 28 | 29 | Copyright and related rights waived via [CC0](LICENSE.md). 30 | 31 | -------------------------------------------------------------------------------- /tip-250.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 250 3 | title: Include transaction results on the chain 4 | author: Andy 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/250 6 | status: Final 7 | type: Standards Track 8 | category: Core 9 | created: 2021-04-06 10 | ``` 11 | ## Simple Summary 12 | This TIP provides Include transaction results on the chain for java-tron. 13 | ## Abstract 14 | Currently, the result of transaction execution is written in the block. But there is no signature, so it can be tampered with. The tampered block will cause other nodes to think it is a bad block. Then disconnect the node connected to it. It will cause certain damage to the network and affect the stability of the TRON network. 15 | ## Motivation 16 | Put the transaction results on the chain so that they cannot be tampered with and ensure the security of the TRON network. 17 | ## Rationale 18 | public Sha256Hash calcReceiptsRoot(): Calculate the Merkel root of all transaction results 19 | public Sha256Hash getReceiptsMerkleHash(): Get the hash value of each transaction result 20 | public boolean allowReceiptsMerkleRoot(): Whether to enable the function of trading results on the chain 21 | ## Technical Specifications: 22 | 23 | The receiptsRoot field is added to the block header to store the Merkel root of the transaction result. 24 | ``` proto 25 | message BlockHeader { 26 | message raw { 27 | int64 timestamp = 1; 28 | bytes txTrieRoot = 2; 29 | bytes parentHash = 3; 30 | //bytes nonce = 5; 31 | //bytes difficulty = 6; 32 | int64 number = 7; 33 | int64 witness_id = 8; 34 | bytes witness_address = 9; 35 | int32 version = 10; 36 | bytes accountStateRoot = 11; 37 | bytes receiptsRoot = 12; 38 | } 39 | raw raw_data = 1; 40 | bytes witness_signature = 2; 41 | } 42 | ``` 43 | ## Implementation 44 | In the stage of generating blocks. All transactions are executed, the transaction results are calculated to generate the transaction result Merkel root (receiptsRoot), and then the receiptsRoot is written into the block header. Finally, the block is signed. 45 | 46 | Merkel root generation method of trading results. 47 | ``` java 48 | public Sha256Hash calcReceiptsRoot() { 49 | List transactionsList = this.block.getTransactionsList(); 50 | 51 | if (CollectionUtils.isEmpty(transactionsList)) { 52 | return Sha256Hash.ZERO_HASH; 53 | } 54 | 55 | ArrayList ids = transactionsList.stream() 56 | .map(TransactionCapsule::new) 57 | .map(TransactionCapsule::getReceiptsMerkleHash) 58 | .collect(Collectors.toCollection(ArrayList::new)); 59 | 60 | return MerkleTree.getInstance().createTree(ids).getRoot().getHash(); 61 | } 62 | ``` 63 | Get the hash value of each transaction result. 64 | ``` java 65 | public Sha256Hash getReceiptsMerkleHash() { 66 | if (this.transaction.getRetCount() <= 0) { 67 | return Sha256Hash.ZERO_HASH; 68 | } 69 | byte[] transBytes = this.transaction.getRet(0).toByteArray(); 70 | return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), 71 | transBytes); 72 | } 73 | ``` 74 | When processing a block, it is necessary to verify the root of the transaction result while verifying the transaction root. 75 | ``` java 76 | if (getDynamicPropertiesStore().allowReceiptsMerkleRoot() && !block.calcReceiptsRoot().equals(block.getReceiptsRoot())) { 77 | throw new BadBlockException("The receipt merkle hash is not validated"); 78 | } 79 | ``` 80 | Due to the need to modify the protocol, a hard fork is required. By adding a proposal to open the transaction results on the chain function. Proposal id is: 50 81 | 82 | ## Copyright 83 | 84 | Copyright and related rights waived via [CC0](LICENSE.md). 85 | 86 | -------------------------------------------------------------------------------- /tip-26.md: -------------------------------------------------------------------------------- 1 | ## Simple Summary 2 | 3 | A new contract creation function called CREATE2. 4 | 5 | ## Abstract 6 | 7 | A new method of creating a contract is proposed where the resulting address can be determined by parties ahead of time. 8 | 9 | ## Motivation 10 | 11 | Allows interactions to (actually or counterfactually in channels) be made with addresses that do not exist yet on-chain but can be relied on to only possibly eventually contain code that has been created by a particular piece of init code. Important for state-channel use cases that involve counterfactual interactions with contracts. 12 | 13 | ## Specification 14 | 15 | Adds a new opcode at 0xf5, which takes 4 stack arguments: endowment, memory_start, memory_length, salt. Behaves identically to CREATE, except using `addressPrefix ++ keccak256(address ++ salt ++ keccak256(init_code))[12:]` to create a new contract address. `addressPrefix` is `0x41` forT 16 | The CREATE2 has the same `engery` schema as `CREATE`, but also an extra `hashcost` of `GSHA3WORD * ceil(len(init_code) / 32)`, to account for the hashing that must be performed. The `hashcost` is deducted at the same time as memory-expansion engery and `Creat`e is deducted: before evaluation of the resulting address and the execution of ``. 17 | 18 | - address is always 21 bytes, 19 | - salt is always 32 bytes (a stack item). 20 | - `keccak256(init_code)` 32 bytes 21 | 22 | The preimage for the final hashing round is thus always exactly 85 bytes long. 23 | 24 | ## Rationale 25 | 26 | **Address formula** 27 | - Because instruction CREATE mainly depends on `trxHash`, the CREATE2 addresses will not collide with CREATE addresses. 28 | - Deploy contract: `addressPrefix ++ keccak256(trxHash ++ txOwnerAddress)[12:]` 29 | - in internal transaction: `addressPrefix ++ keccak256(trxHash ++ nonce)[12:]` 30 | - Ensures that the hash preimage has a fixed size, 31 | 32 | **Engery cost** 33 | Since address calculation depends on hashing the `init_code`, it would leave clients open to DoS attacks if executions could repeatedly cause hashing of large pieces of `init_code`, since expansion of memory is paid for only once. This TIP uses the same cost-per-word as the `SHA3` opcode. 34 | 35 | 36 | ## Copyright 37 | 38 | Copyright and related rights waived via [CC0](LICENSE.md). 39 | -------------------------------------------------------------------------------- /tip-268.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 268 3 | title: SmartContract ABI optimization 4 | author: yanghang8612 5 | status: Final 6 | type: Standards Track 7 | category: VM 8 | created: 2021-05-19 9 | ``` 10 | 11 | ## Simple Summary 12 | 13 | Move ABI out of SmartContract and store it in a new ABI store. 14 | 15 | ## Motivation 16 | 17 | The ABI field is totally indeed when the TVM executing SmartContract. Moving out ABI can reduce execution time of some opcodes such as `EXTCODEHASH` `SLOAD` `SSTORE` `ISCONTRACT` `CREATE` and `CREATE2`. 18 | 19 | ## Specifications 20 | 21 | #### ABI Store 22 | 23 | Add a new store called ABI Store. The data stored in it is like below. 24 | 25 | ``` 26 | message ABI { 27 | message Entry { 28 | enum EntryType { 29 | UnknownEntryType = 0; 30 | Constructor = 1; 31 | Function = 2; 32 | Event = 3; 33 | Fallback = 4; 34 | Receive = 5; 35 | } 36 | message Param { 37 | bool indexed = 1; 38 | string name = 2; 39 | string type = 3; 40 | } 41 | enum StateMutabilityType { 42 | UnknownMutabilityType = 0; 43 | Pure = 1; 44 | View = 2; 45 | Nonpayable = 3; 46 | Payable = 4; 47 | } 48 | 49 | bool anonymous = 1; 50 | bool constant = 2; 51 | string name = 3; 52 | repeated Param inputs = 4; 53 | repeated Param outputs = 5; 54 | EntryType type = 6; 55 | bool payable = 7; 56 | StateMutabilityType stateMutability = 8; 57 | } 58 | repeated Entry entrys = 1; 59 | } 60 | ``` 61 | 62 | ## Rationale 63 | 64 | #### Deploy Smart Contract 65 | 66 | While committing contract cache, save ABI of the deployed contract to the ABI store, clear the ABI field of contract and save it to the Contract store. 67 | 68 | #### Determine if constant 69 | 70 | Get the ABI of contract in ABI store. 71 | 72 | ## Implementation 73 | 74 | When tron clients start, traverse all contracts in store and save every contract`s ABI to the ABI store. While doing this operation, clear the ABI field of contract and update the contract to store. 75 | 76 | ``` 77 | class MoveAbiHelper 78 | def do_traverse_work() -> None: 79 | for contract in contract_store: 80 | if !abi_store.has(contract.address): 81 | abi_store.save(contract.getABI()) 82 | contract.clear(field.ABI) 83 | contract_store.save(contract) 84 | assert contract_store.total() == abi_store.total() 85 | ``` 86 | 87 | 88 | 89 | ## Backwards Compatibility 90 | 91 | No known backward compatibility issues. 92 | 93 | 94 | ## Copyright 95 | 96 | Copyright and related rights waived via [CC0](LICENSE.md). 97 | -------------------------------------------------------------------------------- /tip-276.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 276 3 | title: Optimize block verification logic 4 | author: lucas.wu@tron.network 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/276 6 | status: Final 7 | category: Core 8 | created: 2021-06-03 9 | ``` 10 | ## Simple Summary 11 | This TIP is to optimize the block verification logic to reduce block processing time. 12 | ## Abstract 13 | According to statistics, the verification of each transaction takes about 3ms on average. After analysis, the verification of the transaction takes up nearly one-third of the time during the entire block processing. This article details the optimization of the block verification. 14 | ## Motivation 15 | In order to improve the performance of the blockchain, increase the TPS, and reduce the block loss rate, it is necessary to reduce the block processing time. 16 | ## Specifications 17 | TODO 18 | ## Implementation 19 | After testing and analysis, most of the transactions packaged in the block are also in the pending queue, and the transactions in the pending queue are successfully verified. So whether it can be considered, if the transaction in the block also exists in the pending queue, it is not necessary to verify the signature. Of course, there is a special case that needs to be considered. In the scenario of a `AccountUpdateContract` transaction, the `AccountUpdateContract` transaction will change the account permissions, so the final logic can be implemented as follows: 20 | 1. Extract the account list corresponding to the `AccountUpdateContract` transaction in the pending queue 21 | 2. If the transaction in the block also exists in the pending queue, and the corresponding account is not in the list of multiple signature accounts, you can skip the verification 22 | 3. Verify transaction signatures that have not skipped verification 23 | 24 | ## Copyright 25 | 26 | Copyright and related rights waived via [CC0](LICENSE.md). 27 | -------------------------------------------------------------------------------- /tip-28.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 28 3 | title: TRC-28 Built-in message queue for event subscribe 4 | author: jiangyy 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/28 6 | status: Final 7 | type: Standards Track 8 | category: Informational 9 | created: 2019-03-14 10 | ``` 11 | 12 | ## Simple Summary 13 | Adding built-in message queue for event subscribe in java-tron. 14 | 15 | ## Abstract 16 | The built-in message queue is designed for event subscribe. Developers could subscribe triggers directly from fullnode without event plugin. 17 | 18 | ## Motivation 19 | Developers could use event plugins to subscribe triggers from fullnode, which provide very reliable service and store very large amount of data. 20 | 21 | But in some cases, developers want to subscribe directly from fullnode, with short-term subscriptions. Native message queue is implemented to meet such requirement. 22 | 23 | ## Specification 24 | The function of native queue is configurable. It's is disabled by default. It shared the configuration of triggers with eventplugin. 25 | 26 | The communication channel between fullnode and subscription client is socket. The bindport could be configurable to avoid conflicting. 27 | 28 | event.subscribe = { 29 | native = { 30 | useNativeQueue = true // if true, use native message queue, else use event plugin. 31 | bindport = 5555 // bind port 32 | sendqueuelength = 1000 //max length of send queue 33 | } 34 | ...... 35 | } 36 | 37 | Developers should subscribe triggers very conveniently. What they need to do is: connecting to the port, subscribing the topics, then receivingthe triggers. 38 | 39 | 40 | ## Copyright 41 | 42 | Copyright and related rights waived via [CC0](LICENSE.md). 43 | -------------------------------------------------------------------------------- /tip-281.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 281 3 | title: Optimize the query of database 4 | author: forfreeday@163.com 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/281 6 | status: Final 7 | type: Standards Track 8 | category: Core 9 | created: 2021-06-18 10 | ``` 11 | 12 | ## Simple Summary 13 | Optimize the performance of underlying database queries and remove query synchronization locks. 14 | 15 | ## Abstract 16 | Optimize database queries to improve query efficiency. Remove unnecessary locking operations during queries to improve query efficiency for HTTP and RPC. 17 | 18 | ## Motivation 19 | To locate important performance issues and find that it is possible to query without adding locks without affecting the correctness of the data and significantly improving the database query performance. 20 | Also, if locks exist, there is a certain probability of lock contention during HTTP or RPC queries, which affects the processing efficiency of other threads. 21 | 22 | ## Specification 23 | 1. Remove get method query lock 24 | 2.Remove has method lock 25 | 26 | ## Implementation 27 | State-based storage is ultimately operated through the Chainbase class. Lock removal is achieved by removing the synchronized keyword from the get and getUncheck methods of this class. 28 | 29 | ## Rationale 30 | 1. The main operation methods of the database, Manager#pushBlock, Manager#generateBlock, Manager#pushTransaction, are all modified by synchronized, so there is no security problem with the operations before each other. 31 | 2. When calling the database interface to query data, there is no practical significance to add synchronized, because there is no security problem, and the methods of querying data do not use shared data, so there is no need to add synchronized. 32 | 33 | ## Copyright 34 | 35 | Copyright and related rights waived via [CC0](LICENSE.md). 36 | -------------------------------------------------------------------------------- /tip-285.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 285 3 | title: Optimize transaction cache initialization logic 4 | author: lucas.wu@tron.network 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/285 6 | status: Final 7 | category: Core 8 | created: 2021-06-21 9 | ``` 10 | ## Simple Summary 11 | This TIP is to optimize transaction cache initialization logic to improve the speed of node startup. 12 | ## Abstract 13 | The transaction cache is initialized during the node startup process. The initialization logic is like this. The system will load the transactions in the latest 65536 blocks into the cache. This will involve 65536 DB queries. The entire process will take three minutes. This article details the optimization of the transaction cache initialization logic. 14 | ## Motivation 15 | The node starts slowly, causing a lot of bad experience for users. In order to solve this problem, it is necessary to speed up the node startup speed. 16 | ## Specifications 17 | TODO 18 | ## Implementation 19 | When the node starts, the transaction cache data will be loaded, so there is no need to load from the block later, the initialization transaction cache code is as follows. 20 | ![image](https://user-images.githubusercontent.com/37210306/122703929-349b2c00-d285-11eb-9479-93d84a8d673d.png) 21 | 22 | ## Copyright 23 | 24 | Copyright and related rights waived via [CC0](LICENSE.md). 25 | -------------------------------------------------------------------------------- /tip-289.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 289 3 | title: Block Broadcast Optimization 4 | author: lucas.wu@tron.network 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/289 6 | status: Final 7 | category: Core 8 | created: 2021-07-12 9 | ``` 10 | ## Simple Summary 11 | This TIP is to optimize block broadcasting. 12 | ## Abstract 13 | The current block processing and broadcasting logic is like this: Verify block → Process block → Broadcast block. The time consumption is mainly in the block processing. Therefore, once this broadcast logic is used, the block delay will be longer. The log below shows that the block delay is close to 2 seconds. 14 | 15 | ![image](https://user-images.githubusercontent.com/37210306/125230394-46fc0900-e30b-11eb-8d9d-dac5efe156be.png) 16 | 17 | Worse, for example, if the processing of the block takes 1 second, the next SR and the previous SR exceed 2 hops, it will directly lead to a block miss. This article details the optimization of the block broadcasting. 18 | 19 | ## Motivation 20 | In order to speed up the block broadcast, let the block be broadcast on the whole network in a short time and improve the block miss rate, it is necessary to optimize the block broadcasting. 21 | 22 | ## Implementation 23 | Modify the processing and broadcast block logic: Verify block → Broadcast block → Process block. As long as the network is unblocked, the block will be broadcasted on the whole network soon, and the block will not be lost. 24 | 25 | Reasons for the feasibility of the scheme: 26 | 1. If there is no witness of cheating, it is completely feasible to broadcast first and then execute. 27 | 2. If a witness cheats, the result is only one more performance consumption of block execution. Blocks that fail to execute will not be chained, which will not have much impact on the entire system. 28 | 29 | The main need to modify the place: 30 | 1. Processing broadcast block: verify the block, including signature and witness valid verification, broadcast directly after the verification is passed, and then process the block. 31 | 2. TCP connection: the block verification fails and the connection is disconnected; the block processing fails and the connection cannot be disconnected (currently the connection will be disconnected as long as the processing fails), otherwise a bad block may cause the entire network to be disconnected. 32 | 33 | ## Copyright 34 | 35 | Copyright and related rights waived via [CC0](LICENSE.md). 36 | -------------------------------------------------------------------------------- /tip-290.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 290 3 | title: Dynamic store optimization 4 | author: lucas.wu@tron.network 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/290 6 | status: Final 7 | category: Core 8 | created: 2021-07-12 9 | ``` 10 | ## Simple Summary 11 | This TIP is to optimize dynamic store query performance. 12 | ## Abstract 13 | Through analysis, a lot of time is spent on dynamic store queries during block processing. 14 | 15 | A total of 304 blocks were counted, including 36044 transactions, the number of dynamic store queries reached 1119525, and the number of queries hitting the cache was 340416. It can be analyzed through the statistical results that, on average, each transaction requires 1119525/36044 = 31 dynamic store queries, and two-thirds of the queries cannot hit the cache, that is, 20 dynamic store queries for each transaction cannot hit the cache. 16 | 17 | In block synchronization, the cost of failing to hit the cache is very high. In the block synchronization logic, after 500 blocks are synchronized, the flash operation will be performed. Before flashing, each block will produce one session (cache). The query logic starts from the outermost cache. If the key is not in the cache, each query needs to be traversed 500 times and then retrieved from the DB. 18 | 19 | This article describes the query optimization of the dynamic store. 20 | 21 | ## Motivation 22 | In order to reduce block processing time, improve the performance of the blockchain, increase the TPS, it is necessary to optimize dynamic store query performance. 23 | 24 | ## Implementation 25 | Due to the particularity of the dynamic store, the key of the entire database is limited. You can consider loading all the data of the dynamic store into the first-level cache, so that the performance will rise sharply. 26 | 27 | Performance Testing: 28 | 29 | block count: 8000, transaction count:903262 30 | 31 |

Before optimization:

32 | 33 | dynamic store query times | cache hits | cache hit probability 34 | -- | -- | -- 35 | 26588491 | 8582259 | 32.28% 36 | 37 |
38 | 39 |

After optimization:

40 | 41 | dynamic store query times | cache hits | cache hit probability 42 | -- | -- | -- 43 | 26588491 | 26588232 | 99.999% 44 | 45 |


46 | Time-consuming comparison of block processing: 47 |
48 | 49 | Before optimization: total cost | Before optimization: average cost | After optimization: total cost | After optimization: average cost 50 | -- | -- | -- | -- 51 | 1476636 | 184 | 1085780 | 135 52 | 1399791 | 174 | 1066748 | 133 53 |
54 | 55 | Before optimization average cost: 179, After optimization average cost: 134 56 | Performance improvement: (179 - 134) / 134 = 33.58% 57 | 58 | ## Copyright 59 | 60 | Copyright and related rights waived via [CC0](LICENSE.md). 61 | -------------------------------------------------------------------------------- /tip-292.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 292 3 | title: Add a proposal to adjust the free net limit in an account 4 | author: federico 5 | discussions-to: https://github.com/tronprotocol/tips/issues/292 6 | status: Final 7 | type: Standards Track 8 | category: TRC 9 | created: 2021-07-13 10 | ``` 11 | 12 | ## Simple Summary 13 | 14 | This TIP will add a proposal to adjust the free net limit in an account. 15 | 16 | ## Abstract 17 | 18 | The free net limit is the free bandwidth resource that can be used by the users to decrease the transaction fee. At present, the free net limit is set as a fixed value `5000`. But recently, some malicious behaviors are discovered to generate lots of fraudulent TRC10 transactions by abusing the free bandwidth resources. To restrain this situation, we propose to change the free net limit. 19 | 20 | 21 | 22 | ## Motivation 23 | 24 | We can restrain the fraudulent TRC10 transactions by increasing their cost. So the free net limit value should be configurable instead of being a fixed value. The free net value limit needs to be decreased when lots of fake TRC10 transactions appeared. There should be a proposal to change the free net limit. 25 | 26 | 27 | ## Specification 28 | 29 | The `FREE_NET_LIMIT` proposal type is defined as : 30 | ```java 31 | public enum ProposalType { 32 | ... 33 | FREE_NET_LIMIT(61), // 5000, [0, 100_000] 34 | ... 35 | } 36 | ``` 37 | The proposal code is `61` and its initial value is set `5000`. The valid range of `FREE_NET_LIMIT` parameter is `[0, 100,000]`. 38 | 39 | The average bandwidth consumption of a transaction is in the range `[300, 500]`, so the `FREE_NET_LIMIT` parameter can be adjusted according to the number of free transactions the users are allowed to use in a day. 40 | 41 | ## Rationale 42 | In addition, to restrain the fraudulent TRC10 transactions, it is quite necessary to adjust the free net limit to adapt to different situations in the TRON network. 43 | 44 | ## Copyright 45 | 46 | Copyright and related rights waived via [CC0](LICENSE.md). 47 | 48 | -------------------------------------------------------------------------------- /tip-293.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 293 3 | title: Add a proposal to adjust the total net limit 4 | author: federico 5 | discussions-to: https://github.com/tronprotocol/tips/issues/293 6 | status: Final 7 | type: Standards Track 8 | category: TRC 9 | created: 2021-07-14 10 | ``` 11 | 12 | ## Simple Summary 13 | 14 | This TIP will add a proposal to adjust the total net limit. 15 | 16 | ## Abstract 17 | 18 | The total net limit stands for the bandwidth resource distributed to all the users when they freeze their TRX balances. 19 | At present, the total net limit `TOTAL_NET_LIMIT` parameter is set as a fixed value of 43.2 billion according to a rough estimate, which is not flexible enough to adapt to the rapid development of the TRON network. So we propose to change the total net limit parameter. 20 | 21 | 22 | ## Motivation 23 | The current fixed `TOTAL_NET_LIMIT` parameter is estimated by the following equation: 24 | ``` 25 | 43,200,000,000 = 500 * 1000 * 86400 26 | ``` 27 | where `500` stands for the average transaction byte size, `1000` stands for TPS, and `86400` stands for the total number of seconds in a day. 28 | 29 | However, the estimated value is not accurate. Instead of being a fixed value, it is better to make the `TOTAL_NET_LIMIT` parameter configurable. 30 | 31 | 32 | ## Specification 33 | 34 | The `TOTAL_NET_LIMIT` proposal type is defined as : 35 | ```java 36 | public enum ProposalType { 37 | ... 38 | TOTAL_NET_LIMIT(62); // 43_200_000_000L, [0, 1000_000_000_000L] 39 | ... 40 | } 41 | ``` 42 | The proposal code is `62` and its initial value is set `43,200,000,000`. The valid range of `TOTAL_NET_LIMIT` parameter is `[0, 1000,000,000,000]`. 43 | 44 | 45 | ## Rationale 46 | It is quite necessary to adjust the total net limit to adapt to different situations in the TRON network. 47 | 48 | ## Copyright 49 | 50 | Copyright and related rights waived via [CC0](LICENSE.md). 51 | -------------------------------------------------------------------------------- /tip-30.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 30 3 | title: TRC-30 Code hash instructions 4 | author: llwslc 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/30 6 | category: TRC 7 | status: Final 8 | created: 2019-03-27 9 | ``` 10 | 11 | ## Simple Summary 12 | 13 | To provide a new opcode, which returns the keccak256 hash of a contract's code. Just like EIP1052 in Ethereum. 14 | 15 | ## Abstract 16 | 17 | This TIP specifies a new opcode, which returns the keccak256 hash of a contract's code. 18 | 19 | ## Motivation 20 | 21 | Many contracts need to perform checks on a contract's bytecode, but do not necessarily need the bytecode itself. For instance, a contract may want to check if another contract's bytecode is one of a set of permitted implementations, or it may perform analyses on code and whitelist any contract with matching bytecode if the analysis passes. 22 | 23 | Contracts can presently do this using the `EXTCODECOPY` opcode, but this is expensive, especially for large contracts, in cases where only the hash is required. As a result, we propose a new opcode, `EXTCODEHASH`, which returns the keccak256 hash of a contract's bytecode. 24 | 25 | ## Specification 26 | 27 | A new opcode, `EXTCODEHASH`, is introduced, with number 0x3F. The `EXTCODEHASH` takes one argument from the stack, zeros the first 96 bits and pushes to the stack the keccak256 hash of the code of the account at the address being the remaining 160 bits. 28 | 29 | In case the account does not exist `0` is pushed to the stack. 30 | 31 | In case the account does not have code the keccak256 hash of empty data (i.e. `c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470`) is pushed to the stack. 32 | 33 | The energy cost of the `EXTCODEHASH` is 400. 34 | 35 | ## Rationale 36 | 37 | As described in the motivation section, this opcode is widely useful, and saves on wasted energy in many cases. 38 | 39 | Only the 20 last bytes of the argument are significant (the first 12 bytes are ignored) similarly to the semantics of the `BALANCE`, `EXTCODESIZE` and `EXTCODECOPY`. 40 | 41 | The `EXTCODEHASH` distincts accounts without code and non-existing accounts. 42 | This is consistent with the way accounts are represented in the state trie. 43 | This also allows smart contracts to check whenever an account exists. 44 | 45 | ## Backwards Compatibility 46 | 47 | There are no backwards compatibility concerns. 48 | 49 | ## Test Cases 50 | 51 | 1. The `EXTCODEHASH` of the account without code is `c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470` what is the keccack256 hash of empty data. 52 | 2. The `EXTCODEHASH` of non-existent account is `0`. 53 | 3. The `EXTCODEHASH` of an precompiled contract is either `c5d246...` or `0`. 54 | 4. If `EXTCODEHASH` of `A` is `X`, then `EXTCODEHASH` of `A + 2**160` is `X`. 55 | 5. The `EXTCODEHASH` of an account that selfdestructed in the current transaction. 56 | 6. The `EXTCODEHASH` of an account that selfdestructed and later the selfdestruct has been reverted. 57 | 7. The `EXTCODEHASH` of an account created in the current transaction. 58 | 8. The `EXTCODEHASH` of an account that has been newly create and later the creation has been reverted. 59 | 9. The `EXTCODEHASH` of an account that firstly does not exist and later is empty. 60 | 10. The `EXTCODEHASH` of an empty account that is going to be cleared by the state clearing rule. 61 | 62 | 63 | ## Copyright 64 | 65 | Copyright and related rights waived via [CC0](LICENSE.md). 66 | -------------------------------------------------------------------------------- /tip-306.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 306 3 | title: Adapt to solidity_0.8.4 4 | author: neo.hong@tron.network 5 | status: Final 6 | type: Standards Track 7 | category: VM 8 | created: 2021-07-29 9 | ``` 10 | 11 | ## Simple Summary 12 | 13 | Adapt to solidity_0.8.4. 14 | 15 | ## Abstract 16 | 17 | Solidity_0.8.4 supports custom errors via the `error` keyword and introduce the `revert` statement. To adapt to solidity_0.8.4 we need add `Error` type in java-tron smart contract ABI. 18 | 19 | ## Motivation 20 | 21 | To adapt to solidity_0.8.4 we need add `Error` type in java-tron smart contract ABI. 22 | 23 | ## Specifications 24 | 25 | Add `Error = 6` EntryType in message ABI in smart_contract.proto file. 26 | 27 | ``` 28 | message ABI { 29 | message Entry { 30 | enum EntryType { 31 | UnknownEntryType = 0; 32 | Constructor = 1; 33 | Function = 2; 34 | Event = 3; 35 | Fallback = 4; 36 | Receive = 5; 37 | Error = 6; 38 | } 39 | message Param { 40 | bool indexed = 1; 41 | string name = 2; 42 | string type = 3; 43 | } 44 | enum StateMutabilityType { 45 | UnknownMutabilityType = 0; 46 | Pure = 1; 47 | View = 2; 48 | Nonpayable = 3; 49 | Payable = 4; 50 | } 51 | 52 | bool anonymous = 1; 53 | bool constant = 2; 54 | string name = 3; 55 | repeated Param inputs = 4; 56 | repeated Param outputs = 5; 57 | EntryType type = 6; 58 | bool payable = 7; 59 | StateMutabilityType stateMutability = 8; 60 | } 61 | repeated Entry entrys = 1; 62 | } 63 | ``` 64 | 65 | 66 | ## Copyright 67 | 68 | Copyright and related rights waived via [CC0](LICENSE.md). 69 | -------------------------------------------------------------------------------- /tip-31.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 31 3 | title: TRC-31 Trigger constant contract 4 | author: llwslc 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/31 6 | category: TRC 7 | status: Final 8 | created: 2019-4-3 9 | ``` 10 | ## Abstract 11 | 12 | This TIP specifies a new api, which triggers the constant contract without ABI. 13 | 14 | ## Motivation 15 | 16 | Some of contracts are uploaded without the ABI. It is hard to judge whether the function is a constant function or not. So, we must provide an interface for calling the constant function explicitly. 17 | 18 | ## Specification 19 | 20 | A new api,` triggerConstantContract`, is introduced. 21 | ``` 22 | // api.proto 23 | rpc TriggerConstantContract (TriggerSmartContract) returns (TransactionExtention) {} 24 | ``` 25 | 26 | The `triggerConstantContract` parameters are the same as the `triggerContract`. 27 | 28 | `triggerConstantContract contract_address method args isHex` 29 | 30 | Http interface example: 31 | 32 | `curl -X POST http://127.0.0.1:8090/wallet/triggerconstantcontract -d {"contract_address":"4189139CB1387AF85E3D24E212A008AC974967E561","function_selector":"foo(uint256,uint256)","parameter":"00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002","owner_address":"41D1E7A6BC354106CB410E65FF8B181C600FF14292"}'` 33 | 34 | In case the type of method is not constant will gets error. 35 | 36 | ## Backwards Compatibility 37 | 38 | There are no backwards compatibility concerns. 39 | 40 | ## Test Cases 41 | 42 | 1. Trigger the constant method by` triggerConstantContract`. 43 | 2. Trigger the non-constant method by `triggerConstantContract`. 44 | 45 | 46 | ## Copyright 47 | 48 | Copyright and related rights waived via [CC0](LICENSE.md). 49 | -------------------------------------------------------------------------------- /tip-318.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 318 3 | title: Adapt to Ethereum London Upgrade 4 | author: neo.hong@tron.network 5 | status: Final 6 | type: Standards Track 7 | category: VM 8 | created: 2021-08-16 9 | ``` 10 | 11 | ## Abstract 12 | 13 | - Add a `BASEFEE(0x48)` that returns the value of the network parameter that defines the fee of 1 unit of `Energy` 14 | - Disallow new code starting with the `0xEF` byte to be deployed. Code already existing in the code store starting with `0xEF` byte is not affected semantically by this change. 15 | 16 | ## Motivation 17 | 18 | The Ethernet London Upgrade has been activated on its mainnet on August 5 2021 and this upgrade includes several new EIPs. As a fully EVM-compatible vm implementation for TRON network, TVM needs to introduce two of these changes involving virtual machines. 19 | 20 | ## Specifications 21 | 22 | ### Specification-A 23 | 24 | Add a `BASEFEE` opcode at `(0x48)`, with energy cost `E_base(2)`. 25 | 26 | The `BASEFEE` takes no operand pop up from the stack and push the value of the fee for 1 energy to the stack. 27 | 28 | ### Specification-B 29 | 30 | After the `ALLOW_TVM_LONDON` proposal approved, new contract creation (via deploy transaction, `CREATE` or `CREATE2` instructions) results in an exceptional abort if the code’s first byte is `0xEF`. 31 | 32 | The initcode is the code executed in the context of the deploy transaction, `CREATE`, or `CREATE2` instructions. The initcode returns code (via the `RETURN` instruction), which is inserted into the code store. 33 | 34 | The opcode `0xEF` is currently an undefined instruction, therefore: It pops no stack items and pushes no stack items, and it causes an exceptional abort when executed. This means initcode or already deployed code starting with this instruction will continue to abort execution. 35 | 36 | The exceptional abort due to code starting with `0xEF` behaves exactly the same as any other exceptional abort that can occur during initcode execution, i.e. in case of abort all gas provided to a `CREATE*` or deploy transaction is consumed. 37 | 38 | ## Backwards Compatibility 39 | For `Specification-A`, there are no known backward compatibility issues with the `BASEFEE` opcode. 40 | 41 | For `Specification-B`, it is a breaking change given new code starting with the `0xEF` byte will not be deployable, and contract creation will result in a failure. However, given bytecode is executed starting at its first byte, code deployed with `0xEF` as the first byte is not executable anyway. 42 | 43 | ## Copyright 44 | 45 | Copyright and related rights waived via [CC0](LICENSE.md). 46 | -------------------------------------------------------------------------------- /tip-3326.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 3326 3 | title: Wallet Switch TRON Chain Method 4 | author: Aaron 5 | discussions to: https://github.com/tronprotocol/tips/issues/464 6 | category: Interface 7 | status: Final 8 | created: 2022-09-05 9 | ``` 10 | ## Table of Contents 11 | - [Table of Contents](#table-of-contents) 12 | - [Simple Summary](#simple-summary) 13 | - [Abstract](#abstract) 14 | - [Motivation](#motivation) 15 | - [Specification](#specification) 16 | - [Examples](#examples) 17 | - [Parameters](#parameters) 18 | - [Returns](#returns) 19 | - [Error Code](#error-code) 20 | - [Backwards Compatibility](#backwards-compatibility) 21 | 22 | ## Simple Summary 23 | An method for the wallets to switch between TRON chains. 24 | 25 | ## Abstract 26 | This protocol allows DApps to call the wallets to switch to TRON chains. The calling DApp must provide the unique identifier of the chains to tell the wallets which particular TRON chain to switch to. 27 | 28 | ## Motivation 29 | Any DApp needs a chain to run, and some DApps only interact with a chain on TRON. This protocol will allow DApps to notify the wallets to switch to the corresponding chain, which improves user experience. 30 | Ethereum already has a similar protocol [EIP-3326](https://eips.ethereum.org/EIPS/eip-3326). 31 | 32 | ## Specification 33 | `wallet_switchEthereumChain` 34 | #### Examples 35 | ```javascript 36 | try { 37 | await tron.request({ 38 | method: 'wallet_switchEthereumChain', 39 | params: [{chainId: '0x2b6653dc'}] 40 | }); 41 | } catch (e) {} 42 | ``` 43 | #### Parameters 44 | `wallet_switchEthereumChain` accepts an object, type is as follows: 45 | ```typescript 46 | interface SwitchEthereumChainParameter { 47 | chainId: string; 48 | } 49 | ``` 50 | If the DApp does not provide a chainId, the wallet must reject the request. 51 | About `chainId`: 52 | - The chainId must be obtained through the RPC method of TRON's `eth_chainId`. 53 | - wallet must know chainId 54 | - wallet must be able to switch chains based on chainId 55 | #### Returns 56 | If successful, returns null. 57 | If failed, an error code and an error message will be returned. See the [Error Code](error-code) section for details. 58 | #### Error Code 59 | | Error Code | Name | Description | 60 | | ---- | ---- | ---- | 61 | | -32002 | Other requests are being processed | current DApp is processed, it cannot execute the request | 62 | | -32602 | Invalid params | invalid parameters, or added additional parameters | 63 | | 4902 | Invalid chainId | only some chainIds are supported, see the [Parameters](Parameters) section for details | 64 | | 4001 | User rejected request | the user has rejected this request | 65 | | 4200 | Unsupported method | unsupported method | 66 | 67 | ## Backwards Compatibility 68 | This protocol has no impact on existing wallets and DApps, but it is recommended that all wallets and DApps implement this protocol. 69 | 70 | ## Copyright 71 | 72 | Copyright and related rights waived via [CC0](LICENSE.md). 73 | -------------------------------------------------------------------------------- /tip-366.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 366 3 | title: TIP-366 Node startup optimization 4 | author: halibobo1205@gmail.com 5 | discussions to: https://github.com/tronprotocol/tips/issues/366 6 | status: Final 7 | type: Standards Track 8 | category: Core 9 | created: 2022-01-24 10 | ``` 11 | 12 | ## Abstract 13 | Currently, it takes about 1 minute from node starts to block synchronization. Block synchronization depends on node tcp establishment.During the start-up,the current tcp connection establishment thread is delayed by 30s to wait neighbors discovery. However, when `node.discovery.persist = true`, the current discovered node will be stored persistently at regular intervals. 14 | 15 | ## Specification 16 | 17 | Change TCP initialDelay from 30s to 100ms, TCP connection using last persistent node information instead of waiting for `30s`. 18 | 19 | ## Motivation 20 | Speed up TCP establishment for the purpose of fast node startup. 21 | 22 | ## Implementation 23 | 24 | ### SyncPool 25 | ```java 26 | 27 | public void init() { 28 | //...... 29 | poolLoopExecutor.scheduleWithFixedDelay(() -> { 30 | try { 31 | //.... node discovery 32 | } catch (Throwable t) { 33 | logger.error("Exception in sync worker", t); 34 | } 35 | }, 100, 3600, TimeUnit.MILLISECONDS); 36 | 37 | } 38 | ``` 39 | 40 | 41 | ## Rationale 42 | TCP initialDelay take up much time(30s) during node start up(about 1min). 43 | 44 | 45 | ## Copyright 46 | 47 | Copyright and related rights waived via [CC0](LICENSE.md). 48 | -------------------------------------------------------------------------------- /tip-37.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 37 3 | title: TRC-37: forbid using TransferContract & TransferAssetContract for contract account 4 | author: Taihao Fu 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/37 6 | category: TRC 7 | status: Final 8 | created: 2019-05-10 9 | ``` 10 | 11 | 12 | ## Abstract 13 | Forbidding transfer trx/trc10 to a contract account can avoid the misunderstanding of the transfer transaction would executing fallback function in smart contract. 14 | 15 | Also avoid user misuse system transfer contract to send their asset to a contract and asset would probably be locked in a contract forever. 16 | 17 | ## Motivation 18 | Several report from our community shows dApp developer try to execute fallback function when use transferContract to send trx to their smart contract. But in our origin design it should not touch TVM. So, one option to resolve the misunderstanding is a hard fork to forbid the transaction to a smart contract address. 19 | 20 | ## Specification 21 | Add validate address logic in validate() function in TransferContract & TransferAssetContract. When the toAddress account type is Contract, throw a contract validate exception. 22 | 23 | ## Rationale 24 | TransferContract & TransferAssetContract should only use bandwidth and not touch TVM. The two types of system contract would be better only for asset easy transferring on tron-network. 25 | 26 | For contract , user should trigger fallback function in the specific contract for trx/trc10 token transferring purpose. 27 | 28 | ## Backwards Compatibility 29 | 1. If old contract not implement fallback function in their contract, there would be no other way any more to send trx/trc10 to this contract. 30 | 31 | 2. tronlink or similar wallet should support a new transfer method to use bandwidth/energy to send trx/trc10 to the contract. 32 | 33 | 3. dApp developer may need to change their migration script/ dApp script a little bit for contract asset injection. 34 | 35 | 4. tronweb should do the similar change for contract asset injection. 36 | 37 | 38 | ## Copyright 39 | 40 | Copyright and related rights waived via [CC0](LICENSE.md). 41 | -------------------------------------------------------------------------------- /tip-383.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 383 3 | title: Optimize transaction cache loading 4 | author:wb_bupt@163.com 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/383 6 | status: Final 7 | type: Standards Track 8 | category: Core 9 | created: 2022-02-28 10 | ``` 11 | 12 | ## Simple Summary 13 | This TIP is to describes how to optimize transaction cache loading. 14 | 15 | ## Abstract 16 | When start the node with the official suggested machine configuration (16cores, 32G, SSD) and the provided startup script. It takes a long time to start syncing blocks each time. Through analysis, it is found that transaction cache loading consumes too much time. This article details the optimization of the transaction cache loading. 17 | 18 | ## Motivation 19 | Node startup speed is too slow, 80% of the time is spent on transaction cache loading. In order to speed up node startup and provide a better user experience, it is necessary to reduce the transaction loading time. 20 | 21 | ## Specification 22 | The storage unit corresponding to each block, each storage unit consists of two fields: block number and transaction id list, The data structure is defined as follows. 23 | ``` 24 | public class RecentTransactionItem { 25 | private long num; 26 | private List transactionIds; 27 | } 28 | ``` 29 | ## Rationale 30 | The traversal of the database is time-consuming. If there are too many keys, the consumption time will be very long. In order to speed up the traversal speed, the amount of data should be reduced. 31 | 32 | The following is the time-consuming statistics of transaction cache loading before and after optimization. It can be found that the loading speed is significantly improved after optimization. 33 | 34 | | | loading cost | 35 | | ---------------------- | -------------- | 36 | | before optimization | 52,104ms | 37 | | after optimization | 26,448ms | 38 | 39 | ## Implementation 40 | In the current design, the transaction cache database stores the transaction hashes of the last 70,000 blocks, and each transaction stores one piece of data. When processing blocks, each transaction will be written to the database, and the implementation logic is as follows. 41 | ``` 42 | Optional.ofNullable(transactionCache) 43 | .ifPresent(t -> t.put(trxCap.getTransactionId().getBytes(), 44 | new BytesCapsule(ByteArray.fromLong(trxCap.getBlockNum())))); 45 | ``` 46 | If there are 200 transactions per block, there are a total of 14,000,000 pieces of data, which is relatively large , when looping through the database, it takes nearly 30 seconds. The transaction cache database loading logic is as follows. 47 | ``` 48 | private void init() { 49 | DBIterator iterator = (DBIterator) persistentStore.iterator(); 50 | while (iterator.hasNext()) { 51 | Entry entry = iterator.next(); 52 | byte[] key = entry.getKey(); 53 | byte[] value = entry.getValue(); 54 | if (key == null || value == null) { 55 | return; 56 | } 57 | Key k = Key.copyOf(key); 58 | Long v = Longs.fromByteArray(value); 59 | blockNumMap.put(v, k); 60 | db.put(k, v); 61 | } 62 | } 63 | ``` 64 | 65 | It used to store one piece of data per transaction, but now it can be designed to store one piece of data per block, the key is `block number`, and the value is `RecentTransactionItem`, the implementation logic is as follows. This greatly reduces the amount of data and shortens the database traversal time. 66 | ``` 67 | public void updateRecentTransaction(BlockCapsule block) { 68 | List list = new ArrayList<>(); 69 | block.getTransactions().forEach(capsule -> { 70 | list.add(capsule.getTransactionId().toString()); 71 | }); 72 | RecentTransactionItem item = new RecentTransactionItem(block.getNum(), list); 73 | chainBaseManager.getRecentTransactionStore().put( 74 | ByteArray.subArray(ByteArray.fromLong(block.getNum()), 6, 8), 75 | new BytesCapsule(JsonUtil.obj2Json(item).getBytes())); 76 | } 77 | ``` 78 | 79 | ## Copyright 80 | 81 | Copyright and related rights waived via [CC0](LICENSE.md). 82 | -------------------------------------------------------------------------------- /tip-387.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 387 3 | title: Transaction memo fee 4 | author: Andy 5 | discussions to: https://github.com/tronprotocol/tips/issues/387 6 | category: Interface 7 | status: Final 8 | created: 2022-03-13 9 | ``` 10 | 11 | ## Simple Summary 12 | It is recommended that transaction memo burn trx to reduce transactions with fake memo. 13 | 14 | ## Motivation 15 | TRC10 token does not need to consume energy because of free bandwidth. Every day there are tens of thousands of transfer memo with fake news, scam links. Serious impact on TRON ecology. 16 | 17 | And there is currently no good solution to distinguish normal memo from fake memo. 18 | 19 | Maybe we can modify the resource model to fix this, the consumption of resources can be a fixed burning of 1TRX for transfers with memo, similar to the consumption of 1trx for multi-signature transactions. 20 | 21 | @zleanore made a statistic and counted the number of transactions with memo in the network in the past 3 months, as shown in the following table: 22 | 23 | | | Total value | Smart Contract Call | TRX Transfer | TRC10 Transfer | 24 | |------------------------------|--------------|----------------------|--------------|----------------| 25 | | transaction | 290,885,045 | 124,687,814 | 109,745,281 | 49,615,190 | 26 | | transaction with MEMO | 13,212,995 | 181,483 | 1,008,166 | 12,022,636 | 27 | | transaction with URL in MEMO | 5,670,600 | 3,963 | 299,309 | 5,367,328 | 28 | 29 | In the past 3 months, we saw 13,212,995 transactions with memo, of which 5,670,600 transactions were with URL, which accounted for 42.9%. We can clearly see that these memo with url are almost all deceptive, they hope users to open the url and jump to the scam they designed. 30 | 31 | 5,670,600 transactions with memo with url, of which 5,367,328 are TRC10 transfers, accounting for 94.6%, indicating that scammers prefer to use low-cost TRC10 transactions to implement their scam plans. 32 | 33 | If each memo needs to pay 1trx, the cost of scamming in the past 3 months will reach 5,670,600 TRX, which will be a huge challenge for scammers. 34 | 35 | We can also see that in the past 3 months, transactions with memo only accounted for 4.5% of the total network transaction volume, so the memo fee will have no negative impact on most users 36 | ## Specification 37 | The `raw_data.data` field in the transaction is used as memo. If `raw_data.data` is not empty, the transaction burns N TRX, N is a network parameter, and the number of N is 0 by default. It can be modified by SRs voting. Modify it to 1 first, then change it according to the number of AD transactions. 38 | 39 | ## Copyright 40 | 41 | Copyright and related rights waived via [CC0](LICENSE.md). 42 | -------------------------------------------------------------------------------- /tip-388.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 388 3 | title: Optimize light node synchronization logic 4 | author:wb_bupt@163.com 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/388 6 | status: Final 7 | type: Standards Track 8 | category: Core 9 | created: 2022-03-14 10 | ``` 11 | 12 | ## Simple Summary 13 | This TIP mainly describes how to optimize light node synchronization logic. 14 | 15 | ## Abstract 16 | This phenomenon can be found online. After the connection with a light node is established and the handshake is completed, the node enters the synchronous mode. However, when obtaining a block from the light node, the light node finds that the database cannot query the block, and then disconnects the connection. 17 | 18 | When establishing a connection, the node may repeatedly connect to these light nodes and be repeatedly disconnected by the other party, which seriously affects the connection efficiency. 19 | 20 | This article details how to optimize light node synchronization logic. 21 | 22 | ## Motivation 23 | Make the node quickly find a node that can establish an effective connection, avoid repeatedly connecting invalid nodes, and improve the efficiency of connection establishment. 24 | 25 | ## Rationale 26 | The light node only retains some blocks. If the lowest block of the light node is higher than the head block, the block cannot be synchronized, resulting in the connection interruption. 27 | 28 | ## Specification 29 | After the tcp connection is established, the handshake operation is first performed, and the interaction is completed by a pair of hello-message, including the blockchain information of the node. The data structure is as follows, `type` and `lowestBlockNum` are new fields. 30 | 31 | ``` 32 | message HelloMessage { 33 | message BlockId { 34 | bytes hash = 1; 35 | int64 number = 2; 36 | } 37 | Endpoint from = 1; 38 | int32 version = 2; 39 | int64 timestamp = 3; 40 | BlockId genesisBlockId = 4; 41 | BlockId solidBlockId = 5; 42 | BlockId headBlockId = 6; 43 | bytes address = 7; 44 | bytes signature = 8; 45 | int32 type = 9; 46 | int32 lowestBlockNum = 10; 47 | } 48 | ``` 49 | 50 | ## Implementation 51 | There are currently no light node related information fields, which can be carried in the hello-message, mainly including the node type and the lowest block information, So need to add these two fields in hello-message. 52 | 53 | The hello-message of each node needs to be saved. The cache definition is as follows, the key is the node ip. 54 | ``` 55 | private Cache helloMessageCache = CacheBuilder.newBuilder() 56 | .maximumSize(2000).expireAfterWrite(24, TimeUnit.HOURS).recordStats().build(); 57 | ``` 58 | 59 | During the handshake, if the lowest block of the neighbor node is higher than the head block, it should directly disconnect and the hello-message information of the node should be retained to obtain the node information. The logic implementation is as follows. 60 | ``` 61 | BlockCapsule.BlockId headBlockId = chainBaseManager.getHeadBlockId(); 62 | int nodeType = msg.getHelloMessage().getNodeType(); 63 | long lowestBlockNum = msg.getHelloMessage().getLowestBlockNum(); 64 | if (nodeType == NodeManager.NODE_TYPE_LIGHT_NODE && lowestBlockNum > headBlockId.getNum()) { 65 | channel.disconnect(ReasonCode.LIGHT_NODE_SYNC_FAIL); 66 | return; 67 | } 68 | ``` 69 | 70 | When selecting a node to establish a p2p connection, first check whether the neighbor node is a light node. If it is a light node, check whether the lowest block is higher than the head block. If not, you can choose to establish a connection with it. 71 | The select logic implementation is as follows. 72 | ``` 73 | public boolean test(NodeHandler handler) { 74 | long headNum = chainBaseManager.getHeadBlockNum(); 75 | InetAddress inetAddress = handler.getInetSocketAddress().getAddress(); 76 | HelloMessage message = channelManager.getHelloMessageCache().getIfPresent(inetAddress.getHostAddress()); 77 | return !(message != null && message.getNodeType() == 1 78 | && headNum < message.getLowestBlockNum()); 79 | } 80 | ``` 81 | 82 | ## Copyright 83 | 84 | Copyright and related rights waived via [CC0](LICENSE.md). 85 | -------------------------------------------------------------------------------- /tip-391.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 391 3 | title: Optimize fetch block process 4 | author: vikingzzu@163.com 5 | discussions-to: https://github.com/tronprotocol/TIPs/issues/391 6 | status: Final 7 | type: Standards Track 8 | category: Networking 9 | created: 2022-03-21 10 | ``` 11 | 12 | ## Simple Summary 13 | 14 | Optimize fetch block process between nodes 15 | 16 | ## Abstract 17 | 18 | During the process of broadcasting a block, sometimes timeouts occur between nodes fetching blocks, nodes will wait until it times out and then go through a P2P sync to fetch the block, the P2P block fetching process will send SyncBlockChainMessage, ChainInventoryMessage, FetchInvDataMessage, BlockMessage to get the block, this process is more time consuming, such a strategy is very inefficient, we should choose a new node to fetch the block, such a solution only needs to send a FetchInvDataMessage to fetch the latest block in the broadcast process, which will save a lot of time. 19 | 20 | ## Motivation 21 | 22 | Network fluctuations between nodes can cause block fetch timeouts, use a new strategy to prevent such scenarios from occurring. 23 | 24 | ## Rationale 25 | 26 | As a decentralized service, network fluctuations between nodes occur frequently, and network fluctuations can lead to very inefficient block acquisition between nodes, which can lead to a very inefficient service if such scenarios occur frequently, we should use a new strategy to prevent such scenarios from occurring. 27 | 28 | ## Implementation 29 | 30 | Add a new class to save fetch block info, 31 | 32 | ```java 33 | public class FetchBlockService{ 34 | private PeerConnection peer; 35 | private Sha256Hash hash; 36 | private long fetchBlockTimeout; 37 | public void fetchBlock(Sha256Hash sha256Hash, PeerConnection peer){} 38 | private void reSendFetchTimeOutBlock(){} 39 | public void blockFetchSuccess(Sha256Hash sha256Hash){} 40 | } 41 | ``` 42 | 43 | 44 | 45 | During the process of broadcasting a block, message service calls method fetchBlock of the FetchBlockService to record the current sha256Hash info and peer info. 46 | 47 | After fetchBlockTimeout time, FetchBlockService calls method reSendFetchTimeOutBlock to check if it got the block information of sha256Hash, if not then we find a new connection to fetch the block. 48 | 49 | When block service receive the block information of sha256Hash, block service calls method blockFetchSuccess of the FetchBlockService to remove the sha256Hash info and peer info, then the block will not be reacquired. 50 | 51 | ## Copyright 52 | 53 | Copyright and related rights waived via [CC0](LICENSE.md). 54 | -------------------------------------------------------------------------------- /tip-397.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 397 3 | title: Raise limit of the 13th network parameter 4 | author: yanghang8612@163.com 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/384 6 | status: Final 7 | type: Standards Track 8 | category: VM 9 | created: 2022-04-06 10 | ``` 11 | 12 | ## Abstract 13 | 14 | Raise the limit of the 13th(MAX_CPU_TIME_OF_ONE_TX) network parameter. 15 | 16 | ## Motivation 17 | 18 | The 13th network parameter now ranges from 10 to 100 ms. This range currently greatly limits developers from designing more diverse and complex applications such as DeFi, GameFi, etc. 19 | 20 | Therefore the purpose of this TIP is to extend the limit of the range of the 13th network parameter. 21 | 22 | ## Specifications 23 | 24 | After the `ALLOW_HIGHER_LIMIT_FOR_MAX_CPU_TIME_OF_ONE_TX` takes effect, the limit for the 13th network parameter will change from 100 ms to `400` ms. 25 | 26 | ## Rationale 27 | 28 | ### The time range for SR to produce blocks 29 | 30 | TRON network generates block every 3 seconds. According to the design of the TRON's DPOS consensus mechanism, the time range for SR to produce blocks is 450 to 1500 ms. 31 | 32 | The `timeout` calculation algorithm is shown in the following code which link is at [DposTask.java](https://github.com/tronprotocol/java-tron/blob/develop/consensus/src/main/java/org/tron/consensus/dpos/DposTask.java#L106). 33 | 34 | ``` 35 | ... 36 | long timeout = 37 | pTime + BLOCK_PRODUCED_INTERVAL / 2 * dposService.getBlockProduceTimeoutPercent() / 100; 38 | ... 39 | ``` 40 | 41 | The range of `getBlockProduceTimeoutPercent()` is set in the following code which link is at [Args.java](https://github.com/tronprotocol/java-tron/blob/develop/framework/src/main/java/org/tron/core/config/args/Args.java#L526). 42 | 43 | ``` 44 | ... 45 | if (PARAMETER.blockProducedTimeOut < 30) { 46 | PARAMETER.blockProducedTimeOut = 30; 47 | } 48 | if (PARAMETER.blockProducedTimeOut > 100) { 49 | PARAMETER.blockProducedTimeOut = 100; 50 | } 51 | ... 52 | ``` 53 | 54 | Therefore the time range for SR to produce blocks can be calculated by `3000 / 2 * 30 / 100 ~ 3000 / 2 * 100 / 100 = 450 ~ 1500` 55 | 56 | ### Why the limit cannot exceed 450ms 57 | 58 | According to the above analysis, SR can set its own block production time to a minimum of 450ms. Then assuming that the 13th network parameter is set to a value greater than 450ms, it means that the SR cannot package any other system contract transaction after it packages a smart contract transaction that exceeds 450ms. 59 | 60 | ## Backwards Compatibility 61 | 62 | This is a breaking change given proposal to set the 13th network parameter to a new value greater than 100 will be legal. So need a hard fork to achieve. 63 | 64 | ## Security Considerations 65 | 66 | There are no known security considerations issues. 67 | 68 | ## Copyright 69 | 70 | Copyright and related rights waived via [CC0](LICENSE.md). 71 | -------------------------------------------------------------------------------- /tip-41.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 41 3 | title: Optimize transactionHistoryStore occupancy space#40 4 | author: wubin1 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/40 6 | category: TRC 7 | status: Final 8 | created: 2019-5-20 9 | ``` 10 | 11 | ## Simple Summary 12 | 13 | This doc describes the solution of optimizing transactionHistoryStore occupancy space. 14 | 15 | ## Abstract 16 | 17 | In current storage model, transaction result saves in transaction history store and it occupies the most space. 18 | The optimization merges all transactions in a common block and compression the transaction history space. 19 | 20 | ## Motivation 21 | 22 | TRON database already occupied 163GB and it increases 20G each month. So how to optimize space is very import. 23 | 24 | ## Specification 25 | 26 | TransactionHistory doesn't directly save in transactionHistoryStore after the execution of transactions. 27 | **_transactionHistoryStore.put(trxCap.getTransactionId().getBytes(), transactionInfo);_** 28 | 29 | Add transaction history in memory and save in disk after executing one whole block. 30 | 31 | ` transationHistoryCapsule.addTransactionResult(result); 32 | if (block.getTransactions().size() != 0) { 33 | this.transactionHistoryStore.put(ByteArray.fromLong(block.getNum()), block.getResult()); 34 | } ` 35 | 36 | ## Rationale 37 | Saving transaction history for a whole block could reduce duplicate data and protocol buffer compression is more effective for large data. 38 | 39 | ## Backwards Compatibility 40 | 41 | There are no backwards compatibility concerns. 42 | 43 | ## Test Cases 44 | 45 | 1. Compare storage size from optimization version and not optimization version. 46 | 2. Query function for transaction history 47 | 48 | 49 | ## Copyright 50 | 51 | Copyright and related rights waived via [CC0](LICENSE.md). 52 | -------------------------------------------------------------------------------- /tip-425.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 425 3 | title: Speed up TCP connection establishment 4 | author:wb_bupt@163.com 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/425 6 | status: Final 7 | type: Standards Track 8 | category: Net 9 | created: 2022-07-11 10 | ``` 11 | 12 | # Simple Summary 13 | This TIP is to describe how to speed up TCP connection establishment. 14 | 15 | # Abstract 16 | With the increasing number of online nodes, the number of connections of many peers is full. If a connection is established with these nodes, the connection will be refused with the reason of too many peers, and it may take more than ten minutes to find a connection that can be established. This article details how to speed up TCP connection establishment. 17 | 18 | # Motivation 19 | Shorten the tcp connection establishment time, which can speed up the synchronization, and can reduce the block loss rate for SR. 20 | 21 | # Rationale 22 | 1. Too many connections may cause network congestion and packet delay, so the number of connections should be controlled within a range. 23 | 2. After the number of connections is full, you can disconnect a connection according to a certain strategy, so as to quickly access the next connection. 24 | 3. After reaching the maximum number of connections, the establishment of other connections needs to be rejected. 25 | 4. There must be an actively established connection to prevent malicious attacks. 26 | 5. Need to set a minimum threshold for the number of actively established connections. 27 | 28 | # Specification 29 | `maxConnections` The maximum number of connections, when the number of peer connections reaches this threshold, no other connection requests are accepted. 30 | `minConnections` The minimum number of connections, when the number of peer connections is lower than this threshold, you need to continue to establish connections. 31 | `minActiveConnections` Minimum number of actively initiated connections. 32 | 33 | # Implementation 34 | Start a thread to check the number of connections. When the number of connections is full, adopt a certain disconnection strategy to disconnect 1~2 nodes (this solution is recommended, the function is relatively independent, and the embedded main code is relatively small), the disconnection strategy can refer to described below. 35 | 1. Filter trusted nodes. If all connected nodes are trusted nodes and exceed the maximum configuration `maxConnections`, there is no need to disconnect. 36 | 2. Filter actively established tcp connections. 37 | 3. Filter peers that are acquiring blocks or transactions. 38 | 39 | Optimize the connection configuration, set the minimum number of connections to 8. 40 | 41 | Increase the maximum number of connections of the node. You can configure 10~20 full-nodes online to set their maximum number of connections to 50, increasing the number of available connections. 42 | 43 | ## Copyright 44 | 45 | Copyright and related rights waived via [CC0](LICENSE.md). 46 | 47 | -------------------------------------------------------------------------------- /tip-428.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 428 3 | title: Increase the probability that the block processing thread acquires the lock 4 | author:wb_bupt@163.com 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/428 6 | status: Final 7 | type: Standards Track 8 | category: Core 9 | created: 2022-07-11 10 | ``` 11 | 12 | # Simple Summary 13 | This TIP is to describe how to increase the probability that the block processing thread acquires the lock. 14 | 15 | # Abstract 16 | Online machines are generally 32 cores, and the probability of block threads competing for locks is 1/34. In high concurrency scenarios, if the average transaction execution time is 10ms, the average time for block threads to acquire locks is 340ms, which will lead to processing Block or production block delay, thereby reducing TPS and increasing the block loss rate. 17 | 18 | # Motivation 19 | Increase the probability of block thread acquiring locks, in order to improve TPS and reduce block loss rate. 20 | 21 | # Rationale 22 | 1. Transaction threads and block threads need to compete for the same lock, so reducing the number of transaction threads competing the lock at the same time can increase the probability of block threads acquiring locks. 23 | 2. It is more efficient to use interruptible locks. When processing blocks, the transaction thread that owns the lock can be interrupted, so that the block thread can acquire the lock faster. 24 | 25 | # Specification 26 | `Synchronized` is a blocking lock, there is no timeout mechanism, and it cannot be interrupted. 27 | `Lock` supports non-blocking locking, supports timeout mechanism, and can acquire locks interruptible. 28 | 29 | # Implementation 30 | There are two options to increase the probability that the block thread acquires the lock. 31 | 32 | One is to reduce the number of transaction threads competing the lock at the same time. If the number of transaction threads competing for locks at the same time is reduced to 1, the probability of the block thread acquiring the lock is 1/2. 33 | 34 | The second is to use interruptible locks, which allows block threads to quickly acquire locks through the interrupt mechanism. 35 | 36 | Comparison of the two schemes. 37 | 38 | In the first solution, the code changes are relatively simple, and the lock cannot be interrupted, which is conducive to the development of other services in the future. But it needs to wait for the transaction thread that owns the lock to finish executing before the block thread can acquire the lock 39 | 40 | The second scheme is more efficient to acquire the lock, but the implementation is more complicated, and it is necessary to add a lot of thread interrupt signal checking and processing in the process of transaction processing. And if other business threads need to acquire the lock later, other business threads may be interrupted, which makes business development very complicated. 41 | 42 | After comprehensive consideration, the first solution is recommended. 43 | 44 | 45 | ## Copyright 46 | 47 | Copyright and related rights waived via [CC0](LICENSE.md). 48 | -------------------------------------------------------------------------------- /tip-43.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 43 3 | title: TRC-43: Precompiled contract function for signature parallel verification 4 | author: Sh11thead 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/43 6 | category: TRC 7 | status: Final 8 | created: 2019-07-10 9 | ``` 10 | ## Simple Summary 11 | 12 | A new type of precompiled contract function for signature parallel verification. 13 | 14 | ## Abstract 15 | 16 | Add a new type of build-in precompiled contract function for multisign validating instead of the compiled bytecode do the same task. 17 | 18 | ## Motivation 19 | 20 | Since the multi-signature is widely used in Tron, there needs a way for low energy cost and less CPU time multisign validating, the precompiled contract for multi-signature could be a well satisfying solution. 21 | 22 | ## Specification 23 | 24 | Adds a new precompiled contract function named `batchvalidatesign` , which need 3 arguments input: 25 | 26 | - bytes32 hash 27 | - bytes[] signatures 28 | - address[] addresses 29 | 30 | Sample code 31 | 32 | ``` 33 | pragma experimental ABIEncoderV2; 34 | contract Demo { 35 | function testBatch(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns(bytes32){ 36 | return batchvalidatesign(hash, signatures, addresses); 37 | } 38 | } 39 | ``` 40 | 41 | output the result of signature validating would be a bytes32, for example `10100000000000000000000000000000` representing the first signatue and third signatue is correct 42 | 43 | for safety concern, the number of signatures is limited to 16, when count of signatures is greater than 16,all zero output will be provided. 44 | 45 | ## Energy cost 46 | 47 | energy charge for the execution cost 1500 per signature 48 | 49 | 50 | ## Copyright 51 | 52 | Copyright and related rights waived via [CC0](LICENSE.md). 53 | -------------------------------------------------------------------------------- /tip-44.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 44 3 | title: TRC-44 Address.isContract instructions 4 | author: llwslc 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/44 6 | category: TRC 7 | status: Final 8 | created: 2019-07-10 9 | ``` 10 | ## Simple Summary 11 | 12 | To provide a new opcode, which returns the type of the address. 13 | 14 | ## Abstract 15 | 16 | This TIP specifies a new opcode, which determines whether the address type is a contract address. 17 | 18 | ## Motivation 19 | 20 | Some contracts need to limit its callers, such as some functions can only be called by the user, not by the contract. 21 | 22 | ## Specification 23 | 24 | A new opcode, `ISCONTRACT`, is introduced, with number `0xD4`. The `ISCONTRACT` takes one argument from the stack, pushes to the stack the boolean value whether the address type is a contract address. 25 | 26 | In case the address does not exist `false` is pushed to the stack. 27 | 28 | example: 29 | ``` 30 | contract Test { 31 | function checkAddr(address addr) view public returns (bool) { 32 | return addr.isContract; 33 | } 34 | } 35 | ``` 36 | The energy cost of the` ISCONTRACT` is 400. 37 | 38 | ## Backwards Compatibility 39 | 40 | There are no backwards compatibility concerns. 41 | 42 | ## Test Cases 43 | 44 | 1. The `ISCONTRACT` of a contract address is `true`. 45 | 2. The `ISCONTRACT` of an account address is `false`. 46 | 3. The `ISCONTRACT` of a non-existent address is `false`. 47 | 4. The `ISCONTRACT` of a precompiled contract is `false`. 48 | 5. The `ISCONTRACT` of self address in constructor function is `true`. 49 | 6. The `ISCONTRACT` of a selfdestructed contract address is `false`. 50 | 51 | 52 | ## Copyright 53 | 54 | Copyright and related rights waived via [CC0](LICENSE.md). 55 | 56 | -------------------------------------------------------------------------------- /tip-474.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 474 3 | title: Optimize the return value of chainid opcode 4 | author: yanghang8612 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/474 6 | status: Final 7 | type: Standards Track 8 | category: VM 9 | created: 2022-11-04 10 | ``` 11 | 12 | ## Abstract 13 | 14 | This TIP aims to optimize the return value of the `chainid` opcode. 15 | 16 | ## Motivation 17 | 18 | The chainId of the TRON mainnet can be queried through the `jsonrpc` interface, as follows 19 | ```shell= 20 | curl --location --request POST 'https://api.trongrid.io/jsonrpc' \ 21 | --header 'Content-Type: application/json' \ 22 | --data-raw '{"jsonrpc":"2.0", "method": "eth_chainId", "params": [], "id": 1}' 23 | 24 | {"jsonrpc":"2.0","id":1,"result":"0x2b6653dc"} 25 | ``` 26 | 27 | After the `Istanbul` proposal takes effect, the `chainid` opcode becomes valid and it pushes the genesis block id of the current chain onto the stack (defined in [tip-174](https://github.com/tronprotocol/tips/blob/master/tip-174.md)). 28 | 29 | In different networks, the return values of the `chainid` opcode are as follows: 30 | 31 | - `mainnet`: 0x00000000000000001ebf88508a03865c71d452e25f4d51194196a1d22b6653dc 32 | - `nile`: 0x0000000000000000d698d4192c56cb6be724a558448e2684802de4d6cd8690dc 33 | - `shasta`: 0x0000000000000000de1aa88295e1fcf982742f773e0419c5a9c134c994a9059e 34 | 35 | The return value of the `chainid` opcode does not match the chainId value queried by the `jsonrpc` interface. When dApp developers use tools such as metamask to access the TRON network and send transactions, this difference will cause some transactions to fail, such as permit type transactions. 36 | 37 | Meanwhile, the return value of the `chainid` opcode is very large. For the javascript language that commonly used in web3 application development, the maximum integer value is `Number.MAX_SAFE_INTEGER`(defined in [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)), and it is clear that the above return values exceed that `Number.MAX_SAFE_INTEGER`. 38 | 39 | - `Number.MAX_SAFE_INTEGER`: 2**53 - 1 = 9007199254740991 40 | 41 | Therefore, it is necessary to optimize the return value of the `chainid` opcode in the TRON network. 42 | 43 | ## Specification 44 | 45 | After the `getAllowOptimizedReturnValueOfChainId(71th)` proposal takes effect, the `chainid` opcode pushes the same value as the `jsonrpc` interface onto the stack. 46 | 47 | The new return value of the `chainid` opcode for all networks are as follows: 48 | 49 | - `mainnet`: 50 | - In Hex: 0x2b6653dc 51 | - In Decimal: 728126428 52 | - `nile`: 53 | - In Hex: 0xcd8690dc 54 | - In Decimal: 3448148188 55 | - `shasta`: 56 | - In Hex: 0x94a9059e 57 | - In Decimal: 2494104990 58 | 59 | ## Rationale 60 | 61 | The new values above do not conflict with any chainId of the existing EVM networks. 62 | 63 | ## Backwards Compatibility 64 | 65 | Firstly, the new return values proposed in this tip are consistent with some of the TRON community's protocol standards, such as [tip-1193](https://github.com/tronprotocol/tips/issues/466) and [tip-712](https://github.com/tronprotocol/tips/issues/443). 66 | 67 | Secondly, after analyzing the bytecode of the smart contracts on the mainnet and extensive community discussions, we concluded that the proposal has no significant forward compatibility issues. See [issue](https://github.com/tronprotocol/tips/issues/474) for related analysis and discussion. 68 | 69 | ## Security Considerations 70 | 71 | There is no known security consideration. 72 | 73 | ## Copyright 74 | 75 | Copyright and related rights waived via [CC0](LICENSE.md). 76 | -------------------------------------------------------------------------------- /tip-51.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 51 3 | title: TRC-51 rate limit of API traffic 4 | author: shydesky 5 | discussions-to: https://github.com/tronprotocol/TIPs/issues/51 6 | status: Final 7 | type: Standards Track 8 | category: Interface 9 | created: 2019-07-30 10 | ``` 11 | 12 | ## Simple Summary 13 | 14 | This tip is about the flow limit of the API interface. Limiting the API traffic is necessary to every node which usually has limited resources in the Tron Network. 15 | 16 | ## Abstract 17 | 18 | The implementation of the rate limit of API traffic is various, it can be implemented at the firewall level, at the webserver level, or at the API level. This tip Limits the scope of the discussion to the JVM level. 19 | There are many mature algorithms can be used, like Token bucket, Leaky bucket. 20 | 21 | ## Motivation 22 | 23 | The reason limiting the API traffic is that node usually has limited resources to support the API requests. A large number of requests in a short time can cause node out of service. We can guarantee the normal service of the node by limiting some API requests. 24 | 25 | ## Specification 26 | 27 | The API request contains both the HTTP request and RPC request. So, we want to implement one general solution which can be used by these two types of API. So, the implementation is designed based on strategies. We can define different strategies to satisfy the different scenes and the strategies can be implemented by the user. 28 | The control granularity is set at the specific interface. 29 | 30 | 31 | ## Rationale 32 | 33 | The strategy is independent among the different API interfaces, so you can choose a suitable strategy for every API interface. The default strategy of rate limit is also provided if you don't want to define a specific strategy. 34 | 35 | ## Implementation 36 | 37 | There are three types of strategies implemented in the java-Tron right now. They are Global Preemptible Strategy, QpsStrategy, IPQPSStrategy. 38 | The Global Preemptible Strategy is implemented based on java semaphore. Every API request must require a permit before it is responded and release the permit after the response completes. 39 | The QpsStrategy and the IPQPSStrategy are implemented based on guava rate limiter provided by Google. Every API request must require a resource and the number of resources is limited in one period. 40 | 41 | 42 | ## Copyright 43 | 44 | Copyright and related rights waived via [CC0](LICENSE.md). 45 | -------------------------------------------------------------------------------- /tip-534.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 534 3 | title: Remove Vulnerable APIs 4 | author: halibobo1205@gmail.com 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/534 6 | status: Final 7 | type: Standards Track 8 | category: Core 9 | created: 2023-04-14 10 | ``` 11 | 12 | 13 | ## Simple Summary 14 | Propose to remove potential vulnerable APIs. 15 | 16 | 17 | ## Abstract 18 | Previously some APIs could lead to the leakage of sensitive information, such as private keys. 19 | Although developers have been advised not to make remote calls to these APIs, I think it is better to remove the relevant APIs for security concerns and mitigate risks for developers. 20 | 21 | 22 | ## Motivation 23 | For network stability and user data security, I suggest deleting the relevant APIs. 24 | 25 | 26 | ## Specification 27 | 28 | The following APIs should be removed. 29 | 30 | ### 1. HTTP 31 | | API | Description | 32 | | ---- | ----------- | 33 | | createaddress | create address by password| 34 | | generateaddress | create address randomly | 35 | | easytransfer | transfer TRX with password | 36 | | easytransferbyprivate | transfer TRX with private key | 37 | | easytransferasset | transfer asset with password | 38 | | easytransferassetbyprivate | transfer asset with private key| 39 | | gettransactionsign | sign transaction with private key | 40 | | addtransactionsign | sign transaction with private key| 41 | 42 | 43 | ### 2. gGRPC 44 | | API | Description | 45 | | ---- | ----------- | 46 | | CreateAddress | create address by password | 47 | | GenerateAddress | create address randomly| 48 | | EasyTransfer | transfer TRX with password | 49 | | EasyTransferByPrivate |transfer TRX with private key | 50 | | EasyTransferAsset | transfer asset with password| 51 | | EasyTransferAssetByPrivate | transfer asset with private key | 52 | | GetTransactionSign | sign transaction with private key | 53 | | GetTransactionSign2 | sign transaction with private key | 54 | | AddSign|sign transaction with private key| 55 | 56 | 57 | 58 | ## Rationale 59 | Vulnerable APIs may lead to the leakage of sensitive information, such as private keys. 60 | 61 | ## Implementation 62 | 63 | Delete the relevant APIs. 64 | 65 | ## Copyright 66 | 67 | Copyright and related rights waived via [CC0](LICENSE.md). 68 | -------------------------------------------------------------------------------- /tip-54.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 54 3 | title: TRC-54: Automatically active non-existent account when transferring TRX/TRC10 asset in a smart contract 4 | author: Jeancky 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/54 6 | category: TRC 7 | status: Final 8 | created: 2019-08-09 9 | ``` 10 | ## Abstract 11 | 12 | Currently in TRON's smart contract, when transferring to a non-existent address, the transaction will be failed. This may cause inconvenience to some DApp developers. Let's discuss whether automatic creation of non-existent address should be allowed during contract transfer. Of course, contract caller need to pay the corresponding fee. 13 | 14 | ## Motivation 15 | 16 | At TRON, when these system GRpc API transferContract, transferAssetContract are called, an non-existent address is automatically activated. However, when transferring with transfer and transferToken in a smart contract, the non-existing address is not automatically activated. This can make the user experience inconsistent, and it can also cause problems for developers. 17 | 18 | ## Specification 19 | 20 | Before implementing this function, we need to consider that when the address is activated, the instruction will charge an additional 0.1 TRX fee. 21 | 22 | There are many ways to do this, here are two possible ways: 23 | 24 | 1. Directly modify the semantics of transfer, transferToken, allowing the creation of non-existing addresses. Its drawback is that it may affect contracts that have relied on the "contract will be reverted when transfer to non-existing address" feature. Bringing unknown risks to them. 25 | 2. Adding a new auto-activation instruction in the new TRON solidity compiler, and let the compiler to automatically insert this instruction before transfer/transferToken when generating bytecode. This method allows a version to support this behavior. But when compiled with an old compiler, it will never be supported. 26 | 27 | ## Rationale 28 | 29 | In terms of instruction charging, the energy price is an adjustable variable. How to accurately charge 0.1TRX needs to be discussed. 30 | 31 | Regardless of the implementation method, we need to consider whether it will have an unknown impact on existing contracts. Also be consistent with the GRPC API. 32 | 33 | ## Backwards Compatibility 34 | 35 | 1. In terms of energy consumption, it needs to be consistent with the system GRPC interface. 36 | 2. If we want to do that, we need to review the impact of each implementation on existing contracts. 37 | 3. One of these implementations relies on TRON's Solidity compiler update, which is not compatible with historical compiler versions. 38 | 39 | 40 | ## Copyright 41 | 42 | Copyright and related rights waived via [CC0](LICENSE.md). 43 | -------------------------------------------------------------------------------- /tip-541.md: -------------------------------------------------------------------------------- 1 | ``` 2 | Tip: 541 3 | Title: Support canceling unstaking in Stake 2.0 4 | Author: CooperDepp 5 | Discussions-to: https://github.com/tronprotocol/tips/issues/541 6 | Status: Final 7 | Type: Standards Track 8 | Category: Core 9 | Created: 2023-05-05 10 | ``` 11 | 12 | 13 | ## Simple Summary 14 | Add an API in Stake 2.0 to allow users to cancel the unstaking transactions in the waiting period. 15 | 16 | ## Abstract 17 | To be consistent with TVM instructions in Stake 2.0, it is proposed to add an API to support canceling unstaking in Stake 2.0, which means that users can use this API to cancel unstaking in waiting period time, make the unstaking TRX restaked, and meanwhile help users withdraw the TRX expired waiting period to balance. 18 | 19 | 20 | ## Motivation 21 | Stake 2.0 has been launched on TRON mainnet, one of the changes is that there is a waiting period of 14 days after unstaking. As said in this issue, if users misoperate the unstaking transaction, or they change their mind during the waiting period and want to restake the TRX for earnings, for now, they can do nothing but wait for 14 days. This is detrimental to the user's benefit and the staking rate of TRX on the chain. 22 | 23 | Meanwhile, as Stake 2.0 has already supported TVM instructions to cancel the unstakings in the smart contract, I think it is reasonable to add an API in Stake 2.0 to cancel the unstaking transactions. 24 | 25 | 26 | ## Specifications 27 | 28 | Add `wallet/cancelallunfreezev2` API, the user can call this API to cancel all the ongoing unstaking transactions in the waiting period. 29 | 30 | Params: 31 | 32 | `owner_address` - address of transaction initiator, data type is string 33 | `visible` - whether the address is in base58 format, data type is bool 34 | Returns: unsigned transaction, data type is json string 35 | 36 | Example: 37 | ``` 38 | curl -X POST http://127.0.0.1:8092/wallet/cancelallunfreezev2 -d \ 39 | '{ 40 | "owner_address":"TVrukxw11XrfnXuqDgbyQEgogXr1vcoWcq", 41 | "visible":true 42 | }' 43 | ``` 44 | 45 | 46 | 47 | ## Backward Compatibility 48 | 49 | It will not influence the existed staking and unstaking related transactions. 50 | 51 | ## Copyright 52 | 53 | Copyright and related rights waived via [CC0](LICENSE.md). 54 | -------------------------------------------------------------------------------- /tip-542.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 542 3 | Title: Resource delegating supports customizable lock period 4 | Author: Tee 5 | Discussions-to: https://github.com/tronprotocol/tips/issues/542 6 | Status: Final 7 | Type: Standards Track 8 | Category: Core 9 | Created: 2023-05-12 10 | ``` 11 | 12 | 13 | ## Simple Summary 14 | Add a `lock_period` parameter in the `wallet/delegateresource` API in Stake 2.0, to support delegating bandwidth or energy resource with a specified lockup time. 15 | 16 | 17 | ## Abstract 18 | Besides the current API `wallet/delegateresource` that allows users to lockup a solid 3 days before the resouce could be undelegated, it is proposed to add a parameter `lock_period` in this API to support customizable lock period in resource delegating, with the unit of blocks. And the new resource delegating to the same address of same type should have this `lock_period` value larger than the lockup blocks left of the address. 19 | 20 | ## Motivation 21 | Currently in Stake 2.0, the lock parameter in the `wallet/delegateresource` is a `bool` type. If it is set to `false`, the delegated resources does not have a lockup time, it can be unstaked anytime after delegation. If it is set to `true`, the delegated resources cannot be undelegated within 3 days. 22 | 23 | The solid lockup time of 3 days can not meet all the scenarios and is not conducive to the two parties to agree on a lease time in advance. If it can not be defined in the transaction, there is risk that the owner may undelegate the resource before the appointed time. Making the lockup time a customizable time will enhance the flexibility and security in delegation transactions. 24 | 25 | ## Specifications 26 | 27 | Modify `wallet/delegateresource` API, the user can call this API to delegate bandwidth or energy resource with a customized lockup time to another address. 28 | 29 | Params: 30 | 31 | `owner_address` - Address of transaction initiator, data type is string 32 | `receiver_address` - Receiver address of resource to be delegated to, data type is string 33 | `balance` - Amount of TRX staked for resources to be delegated, unit is sun, data type is unit256 34 | `resource` - Resource type, "BANDWIDTH" or "ENERGY", data type is string 35 | `lock` - Whether it is locked. If it is set to false, there will not be any lockup time no matter what the lock_period value is. If it is set to true, the delegating transaction will have a lockup time, and the time is decided by the lock_period value. 36 | `lock_period` - The lockup period, unit is blocks, data type is int256, It indicates how many blocks the resource delegating is locked before it can be undelegated. If the lock time is not over, and the owner delegates the same type of resource with a new lockup time to the same address, the lockup time of all the resource of the same type will be reset to the new lockup time.That new lockup time cannot be less than (old lockup time + old transaction timestamp) - current time. 37 | `visible` - Whether the address is in base58 format, data type is bool 38 | Returns: unsigned transaction, data type is JSON string 39 | 40 | Example: 41 | ``` 42 | curl -X POST https://127.0.0.1:8092/wallet/delegateresource -d \ 43 | '{ 44 | "owner_address":"TUoHaVjx7n5xz8LwPRDckgFrDWhMhuSuJM", 45 | "receiver_address":"TZ4UXDV5ZhNW7fb2AMSbgfAEZ7hWsnYS2g", 46 | "balance":1000000000, 47 | "resource":"BANDWIDTH", 48 | "lock": true, 49 | "lock_period": 86400, 50 | "visible":true 51 | }' 52 | ``` 53 | 54 | ## Backward Compatibility 55 | 56 | It will not influence the existed staking and unstaking related transactions. 57 | 58 | If the `lock` is set to `true`, and `lock_period` is set to 0, or left blank, it also have the same consequence with that the `lock_period` is set to 86400. 59 | 60 | ## Copyright 61 | 62 | Copyright and related rights waived via [CC0](LICENSE.md). 63 | -------------------------------------------------------------------------------- /tip-543.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 543 3 | title: Implement EIP-3855 PUSH0 instruction 4 | author: yanghang8612@163.com 5 | status: Final 6 | type: Standards Track 7 | category: VM 8 | created: 2023-05-15 9 | ``` 10 | 11 | ## Summary 12 | 13 | As part of the Ethereum Shanghai upgrade, [EIP-3855: PUSH0 Instruction](https://eips.ethereum.org/EIPS/eip-3855) is required to be implemented to TRON. 14 | 15 | ## Abstract 16 | 17 | Introduce the `PUSH0` (`0x5f`) instruction, which pushes the constant value 0 onto the stack. 18 | 19 | ## Motivation 20 | 21 | The Ethereum Shanghai upgrade inclues **EIP-3855: PUSH0 Instruction**, an EIP designed to introduce a new `PUSH0` instruction to reduce gas consumption during contract deployment and invocation. 22 | 23 | So to accommodate the changes in EVM due to the Shanghai upgrade, we introduced this TIP. 24 | 25 | **Original motivation from EIP-3855:** 26 | 27 | Many instructions expect offsets as inputs, which in a number of cases are zero. A good example is the return data parameters of `CALLs`, which are set to zeroes in case the contract prefers using `RETURNDATA*`. This is only one example, but there are many other reasons why a contract would need to push a zero value. They can achieve that today by `PUSH1 0`, which costs 3 gas at runtime, and is encoded as two bytes which means `2 * 200` gas deployment cost. 28 | 29 | Because of the overall cost many try to use various other instructions to achieve the same effect. Common examples include `PC`, `MSIZE`, `CALLDATASIZE`, `RETURNDATASIZE`, `CODESIZE`, `CALLVALUE`, and `SELFBALANCE`. Some of these cost only 2 gas and are a single byte long, but their value can depend on the context. 30 | 31 | We have conducted an analysis on Mainnet (block ranges 8,567,259…8,582,058 and 12,205,970…12,817,405), and ~11.5% of all the `PUSH*` instructions executed push a value of zero. 32 | 33 | The main motivations for this change include: 34 | 1. Reducing contract code size. 35 | 2. Reducing the risk of contracts (mis)using various instructions as an optimisation measure. Repricing/changing those instructions can be more risky. 36 | 3. Reduce the need to use `DUP` instructions for duplicating zeroes. 37 | 38 | To put the "waste" into perspective, across existing accounts 340,557,331 bytes are wasted on `PUSH1 00` instructions, which means 68,111,466,200 gas was spent to deploy them. In practice a lot of these accounts share identical bytecode with others, so their total stored size in clients is lower, however the deploy time cost must have been paid nevertheless. 39 | 40 | An example for 2) is changing the behaviour of `RETURNDATASIZE` such that it may not be guaranteed to be zero at the beginning of the call frame. 41 | 42 | ## Specification 43 | 44 | The instruction `PUSH0` is introduced at `0x5f`. It has no immediate data, pops no items from the stack, and places a single item with the value 0 onto the stack. The cost of this instruction is 2 energy (aka `base`). 45 | 46 | ## Rationale 47 | 48 | ### Energy cost 49 | 50 | The `base` energy cost is used for instructions which place constant values onto the stack, such as `ADDRESS`, `ORIGIN`, and so forth. 51 | 52 | ### Opcode 53 | 54 | `0x5f` means it is in a "contiguous" space with the rest of the `PUSH` implementations and potentially could share the implementation. 55 | 56 | ## Backwards Compatibility 57 | 58 | This TIP introduces a new opcode which did not exists previously. Already deployed contracts using this opcode could change their behaviour after this TIP. 59 | 60 | ## Test Cases 61 | 62 | - `5F` -- successful execution, stack consist of a single item, set to zero 63 | - `5F5F..5F` (1024 times) -- successful execution, stack consists of 1024 items, all set to zero 64 | - `5F5F..5F` (1025 times) -- execution aborts due to out of stack 65 | 66 | ## Security Considerations 67 | 68 | There is no security considerations. 69 | 70 | ## Copyright 71 | 72 | Copyright and related rights waived via [CC0](LICENSE.md). 73 | -------------------------------------------------------------------------------- /tip-544.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 544 3 | title: Add `data` to the http interfaces interacting with smart contract 4 | author: yanghang8612@163.com 5 | status: Final 6 | type: Standards Track 7 | category: Interface 8 | created: 2023-05-15 9 | ``` 10 | 11 | ## Simple Summary 12 | 13 | This TIP is designed to optimize the http interfaces interacting with smart contract in order to make them more user-friendly. 14 | 15 | ## Abstract 16 | 17 | The http interfaces interacting with smart contract must pass the `function_selector` and `parameters` fields, the user cannot interact with smart contracts by passing `data` directly. 18 | 19 | Meanwhile it is not possible to estimate the energy consumption for creating smart contract transactions through the http interfaces. 20 | 21 | ## Specifications 22 | 23 | ### `wallet/triggersmartcontract` 24 | User can call this API to read/write the smart contract. 25 | 26 | Params: 27 | 28 | 1. `owner_address` - Required. Account address. 29 | 2. `contract_address` - Required. Contract address. 30 | 3. `call_value` - Optional. The amount of TRX transferred into the contract. 31 | 4. `call_token_value` - Optional. The amount of TRC-10 transferred into the contract. 32 | 5. `token_id` - Optional. The token id of TRC-10 transferred into the contract. 33 | 6. `function_selector` - Optional (***Used to be required***). The signature of the function (like `transfer(address,uint256)`). 34 | 7. `parameter` - Optional. Parameter encoding needs to be in accordance with the ABI rules. 35 | 8. ***New!*** `data`: Optional. The data passed along with a transaction that allows us to interact with smart contracts. 36 | 9. `fee_limit` - Required. Maximum TRX consumption, measured in SUN. 37 | 10. `permission_id` - Optional. For multi-signature transactions. 38 | 11. `visible` - Optional. Whehter the address is in `BASE58` format. 39 | 40 | Returns: unsigned transaction, data type is JSON string. 41 | 42 | Example: 43 | ``` 44 | curl --request POST \ 45 | --url https://api.shasta.trongrid.io/wallet/triggersmartcontract \ 46 | --header 'accept: application/json' \ 47 | --header 'content-type: application/json' \ 48 | --data ' 49 | { 50 | "owner_address": "TZ4UXDV5ZhNW7fb2AMSbgfAEZ7hWsnYS2g", 51 | "contract_address": "TG3XXyExBkPp9nzdajDZsozEu4BkaSJozs", 52 | "function_selector": "balanceOf(address)", 53 | "parameter": "000000000000000000000000a614f803b6fd780986a42c78ec9c7f77e6ded13c", 54 | "visible": true 55 | } 56 | ' 57 | ``` 58 | or 59 | ``` 60 | curl --request POST \ 61 | --url https://api.shasta.trongrid.io/wallet/triggersmartcontract \ 62 | --header 'accept: application/json' \ 63 | --header 'content-type: application/json' \ 64 | --data ' 65 | { 66 | "owner_address": "TZ4UXDV5ZhNW7fb2AMSbgfAEZ7hWsnYS2g", 67 | "contract_address": "TG3XXyExBkPp9nzdajDZsozEu4BkaSJozs", 68 | "data": "70a08231000000000000000000000000a614f803b6fd780986a42c78ec9c7f77e6ded13c", 69 | "visible": true 70 | } 71 | ' 72 | ``` 73 | 74 | ### `wallet/triggerconstantcontract` 75 | User can call this API to read or simulate writing the smart contract. 76 | 77 | Params: 78 | 79 | 1. `owner_address` - Same as `wallet/triggersmartcontract`. 80 | 2. `contract_address` - Optional (***Used to be required***). If this parameter is not empty, then it means that the user wants to interact with the smart contract. Otherwise, it means that the user is trying to deploy a smart contract using `data`. 81 | 3. `call_value` - Same as `wallet/triggersmartcontract`. 82 | 4. `call_token_value` - Same as `wallet/triggersmartcontract`. 83 | 5. `token_id` - Same as `wallet/triggersmartcontract`. 84 | 6. `function_selector` - Optional (***Used to be required***). Same as `wallet/triggersmartcontract`. 85 | 7. `parameter` - Same as `wallet/triggersmartcontract`. 86 | 8. ***New!*** `data`: Optional. The data passed along with a transaction that allows us to interact with smart contracts. 87 | 9. `visible` - Same as `wallet/triggersmartcontract`. 88 | 89 | Returns: 90 | 91 | 1. `result` - Run result. 92 | 2. `energy_used` - Energy consumed during execution. 93 | 3. `constant_result` - Result list of tiggered functions. 94 | 4. `transaction` - Transaction information. 95 | 96 | ### `wallet/estimateenergy` 97 | User can call this API to estimate the energy consumption of smart contract transactions. 98 | 99 | Params: 100 | 101 | Same as `wallet/triggerconstantcontract` 102 | 103 | Returns: 104 | 105 | 1. result - Run result. 106 | 2. energy_required - Energy consumption. 107 | 108 | ### Backwards Compatibility 109 | None. 110 | 111 | ### Security Considerations 112 | None. 113 | 114 | ## Copyright 115 | 116 | Copyright and related rights waived via [CC0](LICENSE.md). 117 | -------------------------------------------------------------------------------- /tip-547.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 547 3 | title: Connection precheck before P2P communication 4 | author: wb_bupt@163.com 5 | status: Final 6 | type: Standards Track 7 | category: Networking 8 | date: 2023-05-22 9 | ``` 10 | 11 | ## Simple Summary 12 | 13 | This TIP is to specify how to establish a p2p connection effectively and quickly through the node precheck. 14 | 15 | ## Abstract 16 | 17 | The node to be connected is selected by the order of the node update time, but it is impossible to know whether the other party can receive the connection. In the actual scene, the probability of the connection being rejected is rather high. The main reason for the rejection is the great number of peers in the network. To solve this problem, the node detection function is developed, which can detect whether the node can be connected in advance, avoiding invalid connections all through, which greatly improves the efficiency of connection establishment. 18 | 19 | ## Motivation 20 | 21 | Through the node precheck, the node status is negotiated in advance to achieve effective and fast connection establishment and avoid a large number of invalid connections, which affect the efficiency of block synchronization. 22 | 23 | ## Rationale 24 | 25 | 1. The function is able to obtain the status of nodes in advance. 26 | 2. Selecting nodes according to their status so that improves the efficiency of connection establishment. 27 | 3. Try to establish a connection with a node that has a relatively large number of connections remaining. 28 | 29 | ## Specification 30 | 31 | Try to establish a TCP connection with the node in advance, check whether the node is still online and see if the connection can be successfully established. After the TCP connection is established, exchange a pair of status messages to obtain node-related information, such as `maxConnections`, `currentConnections`, to determine whether the node accepts other connections 32 | 33 | The status message is designed as follows: 34 | ``` 35 | message StatusMessage { 36 | Endpoint from = 1; 37 | int32 version = 2; 38 | int32 network_id = 3; 39 | int32 maxConnections = 4; 40 | int32 currentConnections = 5; 41 | int64 timestamp = 6; 42 | } 43 | ``` 44 | `version`: the p2p version of the node 45 | `network_id`: the network id of the node 46 | `maxConnections`: the maximum number of connections for the node 47 | `currentConnections`: the number of connections the node has established 48 | 49 | ## Implementation 50 | 51 | Constant settings: 52 | - Set the maximum detection of nodes to 300. 53 | - The node detection thread is scheduled every 5s. According to the latest node update time, 3 or 10 nodes are detected each time accordingly. 54 | - If the detection fails, it would be added to the detection failure cache, and the node could not be detected for 1 hour. 55 | 56 | Functional logic: 57 | When the system starts, a new queue is created to store nodes that are being detected and a thread is started to do node detection. 58 | - When the queue size is less than 200, fast detection is performed, and 100 nodes are detected each time. 59 | - When the queue size is more than 200, slow detection is performed, and confirm the number of nodes detected each time according to the update time of the last node. 60 | - If the update time of the last updated node is less than 5 minutes, detect 3 nodes each time 61 | - If the update time of the last updated node is more than 5 minutes, detect 10 nodes each time 62 | - If the detection fails or the node’s connections are full, then remove the node from the queue, write to the detection failure cache, and stop detecting the node for 1 hour 63 | 64 | External Interface: 65 | - `public List getConnectableNodes()` returns a list of nodes that have successfully detected. 66 | 67 | 68 | ## Copyright 69 | 70 | Copyright and related rights waived via [CC0](LICENSE.md). 71 | -------------------------------------------------------------------------------- /tip-550.md: -------------------------------------------------------------------------------- 1 | ``` 2 | Tip: 550 3 | Title: P2P message snappy compression 4 | Author: allen.cheng@tron.network 5 | Status: Final 6 | Type: Standards Track 7 | Category: Networking 8 | Date: 2023-05-22 9 | ``` 10 | 11 | ## Simple Summary 12 | This TIP proposes a small extension to the TRON protocol to enable Snappy compression on all message payloads after the initial handshake. 13 | 14 | ## Abstract 15 | The base networking protocol used by TRON currently does not employ any form of compression. This results in a massive amount of bandwidth wasted in the entire network, making both initial sync and regular operation slower and laggier. This situation can be improved by compressing network messages. After extensive benchmarks, the results show that data traffic is decreased by 40-60% for block synchronization. 16 | 17 | ## Motivation 18 | Currently, the block size of the TRON ​​network is around 80k bytes. And as the TRON ​​network continues to grow, the block size may continue to increase, the network load will also increase, and the bandwidth requirements of nodes will also increase. However, most data (blocks, transactions) are highly compressible. By enabling compression at the message payload level, we can reduce the amount of data transmitted by the message, reducing bandwidth usage and data synchronization latency. 19 | 20 | ## Rationale 21 | Enable Snappy compression on all TCP channel message payloads after the initial handshake. Compress the message before sending it through the channel. When receiving a compressed message, decompress it first and then continue the subsequent business processing. The handshake message is never compressed, since it is needed to negotiate the common version. 22 | 23 | ## Specification 24 | Pack the compressed message into `CompressMessage` for network transmission. The structure of `CompressMessage` is as follows: 25 | ``` 26 | message CompressMessage { 27 | enum CompressType { 28 | uncompress = 0; 29 | snappy = 1; 30 | } 31 | CompressType type = 1; 32 | bytes data = 2; 33 | } 34 | ``` 35 | ## Implementation 36 | Snappy dependency 37 | ``` 38 | implementation group: 'org.xerial.snappy', name: 'snappy-java', version: '1.1.8.4' 39 | ``` 40 | Compression implementation when sending messages: 41 | ``` 42 | public void send(Message message) { 43 | if (finishHandshake) { 44 | data = ProtoUtil.compressMessage(message.getSendData()).toByteArray(); 45 | } 46 | ... 47 | } 48 | 49 | public static Connect.CompressMessage compressMessage(byte[] data) throws IOException { 50 | Connect.CompressMessage.CompressType type = Connect.CompressMessage.CompressType.uncompress; 51 | byte[] bytes = data; 52 | 53 | byte[] compressData = Snappy.compress(data); 54 | if (compressData.length < bytes.length) { 55 | type = Connect.CompressMessage.CompressType.snappy; 56 | bytes = compressData; 57 | } 58 | 59 | return Connect.CompressMessage.newBuilder() 60 | .setData(ByteString.copyFrom(bytes)) 61 | .setType(type).build(); 62 | } 63 | ``` 64 | 65 | Decompression implementation when receiving a compressed message: 66 | ``` 67 | @Override 68 | protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List out) { 69 | byte[] data = new byte[buffer.readableBytes()]; 70 | buffer.readBytes(data); 71 | if (channel.isFinishHandshake()) { 72 | data = ProtoUtil.uncompressMessage(Connect.CompressMessage.parseFrom(data)); 73 | } 74 | ... 75 | } 76 | 77 | public static byte[] uncompressMessage(Connect.CompressMessage message) throws IOException { 78 | if (message.getType().equals(Connect.CompressMessage.CompressType.uncompress)) { 79 | return message.getData().toByteArray(); 80 | } else { 81 | return Snappy.uncompress(message.getData().toByteArray()); 82 | } 83 | } 84 | ``` 85 | ## Backward Compatibility 86 | This proposal is fully backward compatible. Clients upgrading to the proposed new version protocol should still support skipping the compression step for older version protocol connections. 87 | ## Test 88 | Download blocks with block heights from `46314350` to `46314360`, and perform a compression and decompression test. The compression rate is about 51%. The specific test results are as follows: 89 | 90 | Block size (byte) | Compressed size (byte) | Compression rate | Compression/decompression time(ms) 91 | -- | -- | -- | -- 92 | 89803 | 44361 | 0.50 | <1 93 | 104504 | 50926 | 0.51 | <1 94 | 70970 | 35247 | 0.50 | <1 95 | 96544 | 46905 | 0.51 | <1 96 | 82820 | 41005 | 0.50 | 1 97 | 83987 | 41878 | 0.50 | <1 98 | 82296 | 40566 | 0.51 | <1 99 | 77820 | 39108 | 0.50 | <1 100 | 73715 | 36027 | 0.51 | <1 101 | 90632 | 43918 | 0.52 | <1 102 | 103 | 104 | ## Copyright 105 | 106 | Copyright and related rights waived via [CC0](LICENSE.md). 107 | -------------------------------------------------------------------------------- /tip-586.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 586 3 | title: GRPC Implementation for Resource Price Interfaces 4 | author: lxcmyf@gmail.com 5 | discussions-to: https://github.com/tronprotocol/tips/issues/586 6 | category : Core 7 | status: Final 8 | type: Standards Track 9 | created: 2023-08-29 10 | ``` 11 | ## Simple Summary 12 | GRPC is a high-performance, general-purpose RPC framework open-sourced by Google. This TIP aims to improve gRPC calls for some specific interfaces in Java-tron. 13 | ## Abstract 14 | Currently, the interfaces `/wallet/getbandwidthprices` and `/wallet/getenergyprices` provided by Java-tron do not support gRPC calls. This TIP will implement this function. 15 | ## Motivation 16 | Currently, `/wallet/getbandwidthprices` and `/wallet/getenergyprices` only support HTTP calls. However, this limits developers and users who want to use these interfaces through methods like gRPC, since they won't be able to access historical unit price information of resources through this method. Additionally, it makes it inflexible for external API use. 17 | ## Specification 18 | As mentioned above, Java-tron will modify the `api.proto` file to add gRPC implementations of `/wallet/getbandwidthprices` and `/wallet/getenergyprices`: 19 | ``` 20 | rpc GetBandwidthPrices (EmptyMessage) returns (PricesResponseMessage) { 21 | } 22 | 23 | rpc GetEnergyPrices (EmptyMessage) returns (PricesResponseMessage) { 24 | } 25 | 26 | message PricesResponseMessage { 27 | string prices = 1; 28 | } 29 | ``` 30 | ## Rationale 31 | Since the underlying implementation of the two interfaces `/wallet/getbandwidthprices` and `/wallet/getenergyprices` has been completed, it is only necessary to open the gRPC implementation entry for them. 32 | ## Implementation 33 | Since the protobuf protocol has been defined above, it is only necessary to add the gRPC implementation code in `RpcApiService.java`: 34 | ``` 35 | @Override 36 | public void getBandwidthPrices(EmptyMessage request, 37 | StreamObserver responseObserver) { 38 | try { 39 | responseObserver.onNext(wallet.getBandwidthPrices()); 40 | } catch (Exception e) { 41 | responseObserver.onError(getRunTimeException(e)); 42 | } 43 | responseObserver.onCompleted(); 44 | } 45 | 46 | @Override 47 | public void getEnergyPrices(EmptyMessage request, 48 | StreamObserver responseObserver) { 49 | try { 50 | responseObserver.onNext(wallet.getEnergyPrices()); 51 | } catch (Exception e) { 52 | responseObserver.onError(getRunTimeException(e)); 53 | } 54 | responseObserver.onCompleted(); 55 | } 56 | ``` 57 | In addition, they also support solidity and PBFT API, so gRPC implementations need to be added in `RpcApiServiceOnSolidity.java`and `RpcApiServiceOnPBFT.java`respectively as well: 58 | `RpcApiServiceOnSolidity.java 59 | ` 60 | ``` 61 | @Override 62 | public void getBandwidthPrices(EmptyMessage request, 63 | StreamObserver responseObserver) { 64 | walletOnSolidity.futureGet( 65 | () -> rpcApiService.getWalletSolidityApi().getBandwidthPrices(request, responseObserver)); 66 | } 67 | 68 | @Override 69 | public void getEnergyPrices(EmptyMessage request, 70 | StreamObserver responseObserver) { 71 | walletOnSolidity.futureGet( 72 | () -> rpcApiService.getWalletSolidityApi().getEnergyPrices(request, responseObserver)); 73 | } 74 | ``` 75 | `RpcApiServiceOnPBFT.java` 76 | ``` 77 | @Override 78 | public void getBandwidthPrices(EmptyMessage request, 79 | StreamObserver responseObserver) { 80 | walletOnPBFT.futureGet( 81 | () -> rpcApiService.getWalletSolidityApi().getBandwidthPrices(request, responseObserver)); 82 | } 83 | 84 | @Override 85 | public void getEnergyPrices(EmptyMessage request, 86 | StreamObserver responseObserver) { 87 | walletOnPBFT.futureGet( 88 | () -> rpcApiService.getWalletSolidityApi().getEnergyPrices(request, responseObserver)); 89 | } 90 | ``` 91 | 92 | 93 | ## Copyright 94 | 95 | Copyright and related rights waived via [CC0](LICENSE.md). 96 | -------------------------------------------------------------------------------- /tip-592.md: -------------------------------------------------------------------------------- 1 | ``` 2 | TIP: 592 3 | Title: Supplement Disconnect Reasons in Java-tron 4 | Author: 317787106@qq.com 5 | Status: Final 6 | Type: Standards Track 7 | Category: Networking 8 | Created: 2023-09-13 9 | ``` 10 | 11 | ## Simple Summary 12 | 13 | This TIP describes why and how we supplement disconnect reasons in java-tron. 14 | 15 | ## Abstract 16 | 17 | We supplement two disconnect reasons in java-tron, including NOT\_WITNESS used inRelayService and NO\_SUCH\_MESSAGE in P2pEventHandlerImpl, so other peers can acquire the reason why we disconnect with it better. 18 | 19 | ## Motivation 20 | 21 | Java-tron nodes send DisconnectMessage to peers before stopping the connection. When stopping, the nodes use relatedReasonCode if it exists as DisconnectMessage, otherwise, no message would be sent. Most java-tron logs record the ReasonCode of peer disconnection, but some do not. For example, the reason for disconnection with non-witness nodes in RelayService is not given. 22 | 23 | ## Specification 24 | 25 | ### Unused ReasonCode 26 | 27 | We summarize the use of ReasonCode, many of which have been abandoned and some are moved to libp2p, they may get deleted in the future: 28 | ``` 29 | enum ReasonCode { 30 | REQUESTED = 0x00; //Not used 31 | BAD_PROTOCOL = 0x02; 32 | TOO_MANY_PEERS = 0x04; //Not used 33 | DUPLICATE_PEER = 0x05; 34 | INCOMPATIBLE_PROTOCOL = 0x06; //Not used 35 | RANDOM_ELIMINATION = 0x07; //Not used 36 | PEER_QUITING = 0x08; 37 | UNEXPECTED_IDENTITY = 0x09; 38 | LOCAL_IDENTITY = 0x0A; //Not used 39 | PING_TIMEOUT = 0x0B; //Not used 40 | USER_REASON = 0x10; //Not used 41 | RESET = 0x11; //Not used 42 | SYNC_FAIL = 0x12; 43 | FETCH_FAIL = 0x13; 44 | BAD_TX = 0x14; 45 | BAD_BLOCK = 0x15; 46 | FORKED = 0x16; 47 | UNLINKABLE = 0x17; 48 | INCOMPATIBLE_VERSION = 0x18; 49 | INCOMPATIBLE_CHAIN = 0x19; 50 | TIME_OUT = 0x20; 51 | CONNECT_FAIL = 0x21; //Not used 52 | TOO_MANY_PEERS_WITH_SAME_IP = 0x22; //Not used 53 | LIGHT_NODE_SYNC_FAIL = 0x23; 54 | BELOW_THAN_ME = 0X24; 55 | UNKNOWN = 0xFF; 56 | } 57 | 58 | message DisconnectMessage { 59 | ReasonCode reason = 1; 60 | } 61 | ``` 62 | ### Add new types to Java-tron ReasonCode 63 | 64 | Add the following enumeration type to protos/core/Tron.proto 65 | 66 | enum ReasonCode { 67 | REQUESTED = 0x00; 68 | ... 69 | NOT_WITNESS = 0x25; //Added 70 | NO_SUCH_MESSAGE = 0x26; //Added 71 | ... 72 | UNKNOWN = 0xFF; 73 | } 74 | 75 | So, we can use this ReasonCode here, such as in RelayService.java : 76 | ![image](https://github.com/tronprotocol/tips/assets/23312631/b3cd8efa-8e7b-41c7-a3fc-e7f8166b1efe) 77 | 78 | ### Send ReasonCode to peer before node quits 79 | 80 | Any node should notify peers of the reason when it quits, so others can understand the network better: 81 | ``` 82 | public static void close() { 83 | ... 84 | for (PeerConnection p : new ArrayList<>(peers)) { 85 | if (!p.isDisconnect()) { 86 | p.disconnect(ReasonCode.PEER_QUITING); //added 87 | p.getChannel().close(); 88 | } 89 | } 90 | ... 91 | } 92 | ``` 93 | ## Compatibility 94 | 95 | All of the newly added unrecognized ReasonCode will be converted to UNKNOWN, and no exception will be thrown. 96 | 97 | 98 | ## Copyright 99 | 100 | Copyright and related rights waived via [CC0](LICENSE.md). 101 | -------------------------------------------------------------------------------- /tip-60.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 60 3 | title: TRC-60:Precompiled contract function for multi-signature verification 4 | author: Sh11thead 5 | discussions to: https://github.com/tronprotocol/TIPs/issues/60 6 | category: Core 7 | status: Final 8 | created: 2019-09-20 9 | ``` 10 | 11 | ## Simple Summary 12 | This doc describes a native TVM function which is used to validate multi-signature for a provided account. 13 | 14 | ## Abstract 15 | TRON provided multiple signature functions allowing for permission grading, and each permission can correspond to multiple private keys. But in TVM, currently we only have `ecrecover()` function to verify single-signed message.But multiple-signed message can not be verified in TVM ,to solve this case, we need a new function to support multiple-sign verification . 16 | 17 | ## Motivation 18 | Developer hope to validate multi-sign for account with specific permission in smart contracts. 19 | 20 | 21 | ## Specification 22 | 23 | Add a new function named ***validatemultisign*** in solidity compiler . 24 | 25 | This function could takes 4 parameters: 26 | 27 | ``` 28 | validatemultisign( 29 | address accountAddress, // account address 30 | uint256 permissionId, //permissionId for account 31 | bytes32 content, //content for verifying 32 | bytes[] signatures//signatures to be verified 33 | ) 34 | ``` 35 | 36 | Pay special attention to the parameter `signatures`, 37 | The specific signature method is implemented in java code as follows: 38 | ``` 39 | //parameters address,permissionId ,hash 40 | byte[] address = address 41 | int permissionId = permissionId ; 42 | byte[] hash= originData; 43 | 44 | //merge 45 | byte[] merged = ByteUtil.merge(address,ByteArray.fromInt(permissionId),data); 46 | //get the content to sign 47 | byte[] toSign = Sha256Hash.hash(merged); 48 | 49 | 50 | //sign content 51 | List signs = new ArrayList<>(); 52 | signs.add(Hex.toHexString(key1.sign(toSign).toByteArray())); 53 | signs.add(Hex.toHexString(key2.sign(toSign).toByteArray())); 54 | ``` 55 | This function will call to a specific address (for example,`0x000000000000000000000000000000000000000a`) which will executed precompiledContracts in TVM to validate multi-sign.Since in TRON, one transaction allow max up to 5 different account to sign,the parameter `signatures` is allow max up to 5. 56 | 57 | In TVM , we could reuse `ECKey.ECDSASignature.fromComponents(r, s, v)`method,which is already used by `ecrecover()` to recover address for signature. 58 | ## Energy cost 59 | energy charge for the execution cost 1500 per signature 60 | 61 | ## Rationale 62 | This function allows validating multi-sign in TVM could improve smart contract access to TRON blockchain which is good for both DApp developer and users. 63 | 64 | ## Backwards Compatibility 65 | 66 | Adding a new precompiledContract cause no backwards compatibility concerns. 67 | 68 | ## Test Cases 69 | 70 | 1.Verifying both correct and incorrect signatures in smart contract. 71 | 2.Verifying duplicate signatures. 72 | 3.Verifying more than 5 signatures. 73 | 74 | 75 | ## Copyright 76 | 77 | Copyright and related rights waived via [CC0](LICENSE.md). 78 | -------------------------------------------------------------------------------- /tip-621.md: -------------------------------------------------------------------------------- 1 | ``` 2 | TIP: 621 3 | Title: Add code version column to HelloMessage 4 | Author: 317787106@qq.com 5 | Status: Final 6 | Type: Standards Track 7 | discussions-to: https://github.com/tronprotocol/tips/issues/621 8 | Category: Networking 9 | Created: 2023-11-01 10 | ``` 11 | 12 | 13 | ## Simple Summary 14 | 15 | This TIP describes why the code version column needs to be added to `HelloMessage` when node handshakes with peers. 16 | 17 | ## Abstract 18 | 19 | A new column code version is added to the proto message `HelloMessage` so that the local node can learn more information about peers when handshaking. 20 | 21 | ## Motivation 22 | 23 | There have been 73 release versions of Java-tron until 2023-11-01. In the mainnet or Nile network, nodes running different versions may exist at the same time. Generally, each new version fixes some bugs from the previous one. How to verify that we have fixed this bug? Suppose one peer sends a message to the local node, but this local node with the latest code fails to process it. If the peer runs an older version, this failure could be expected. 24 | 25 | The key point is that the peer's code version can not be acquired easily. One possible way is to get it through the `/wallet/getnodeinfo` API, but in most cases, we cannot access HTTP services. Another solution is to add a `codeVersion` field in the HelloMessage when handshaking with peers. This does not rely on HTTP and can be easily implemented. Please find the details below. 26 | 27 | ## Specification 28 | 29 | In the proto file protos/core/Tron.proto, add one column codeVersion: 30 | ``` 31 | message HelloMessage { 32 | message BlockId { 33 | bytes hash = 1; 34 | int64 number = 2; 35 | } 36 | 37 | Endpoint from = 1; 38 | int32 version = 2; 39 | int64 timestamp = 3; 40 | BlockId genesisBlockId = 4; 41 | BlockId solidBlockId = 5; 42 | BlockId headBlockId = 6; 43 | bytes address = 7; 44 | bytes signature = 8; 45 | int32 nodeType = 9; 46 | int64 lowestBlockNum = 10; 47 | bytes codeVersion = 11; //new added 48 | } 49 | ``` 50 | The column codeVersion comes from `Version` of org.tron.program.Version, latest value is "4.7.3". 51 | 52 | ## Compatibility 53 | 54 | If the node parses the message without columncodeVersion, it uses default null. This column will only be logged. 55 | 56 | 57 | ## Copyright 58 | 59 | Copyright and related rights waived via [CC0](LICENSE.md). 60 | -------------------------------------------------------------------------------- /tip-652.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 652 3 | title: Announce EIP-6049 Deprecate SELFDESTRUCT 4 | author: yanghang8612@163.com 5 | status: Final 6 | type: Meta 7 | category: VM 8 | created: 2024-04-10 9 | ``` 10 | 11 | ## Summary 12 | The `SELFDESTRUCT` opcode has been deprecated after the Ethereum Shanghai upgrade and its behavior has been modified after the Ethereum Cancun upgrade. For compatibility, [EIP-6049: Deprecate SELFDESTRUCT](https://eips.ethereum.org/EIPS/eip-6049) is required to be announced in the TRON community firstly. 13 | 14 | The following compatibility issues require community attention. 15 | 16 | - Contracts that depended on re-deploying contracts at the same address using `CREATE2` (after a `SELFDESTRUCT`) may not function properly. 17 | 18 | - It may be no longer possible to burn TRX by calling `SELFDESTRUCT` targeting the executing contract as the beneficiary. 19 | 20 | **Original content from EIP-6049:** 21 | 22 | ## Abstract 23 | 24 | This EIP deprecates the `SELFDESTRUCT` opcode and warns against its use. A breaking change to this functionality is likely to come in the future. 25 | 26 | ## Motivation 27 | 28 | Discussions about how to change `SELFDESTRUCT` are ongoing. But there is a strong consensus that *something* will change. 29 | 30 | ## Specification 31 | 32 | Documentation of the `SELFDESTRUCT` opcode is updated to warn against its use and to note that a breaking change may be forthcoming. 33 | 34 | ## Rationale 35 | 36 | As time goes on, the cost of doing something increases, because any change to `SELFDESTRUCT` will be a breaking change. 37 | 38 | The Ethereum Blog and other official sources have not provided any warning to developers about a potential forthcoming change. 39 | 40 | ## Backwards Compatibility 41 | 42 | This EIP updates non-normative text in the Yellow Paper. No changes to clients is applicable. 43 | 44 | ## Security Considerations 45 | 46 | None. 47 | 48 | 49 | ## Copyright 50 | 51 | Copyright and related rights waived via [CC0](LICENSE.md). 52 | -------------------------------------------------------------------------------- /tip-653.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 653 3 | title: Adjust energy cost of SUICIDE and VOTEWITNESS opcodes in TVM 4 | author: yanghang8612@163.com 5 | status: Final 6 | type: Standards Track 7 | category: VM 8 | created: 2024-04-30 9 | ``` 10 | 11 | ## Simple Summary 12 | This TIP aims to adjust the energy cost of TVM opcodes based on actual resource consumption. 13 | 14 | ## Abstract 15 | Adjust the energy cost for several opcodes (such as `SUICIDE` and `VOTEWITNESS`) in TVM to better reflect the actual resource consumption of opcode execution and to ensure that the costs are reasonable. 16 | 17 | ## Motivation 18 | The `SUICIDE` opcode is used to destroy smart contracts and release related resources. The `VOTEWITNESS` opcode is a TRON-specific opcode that allows a contract account to perform voting operations on certain SRs just like an EOA account. 19 | 20 | However, the current energy cost mechanism may have some deficiencies, failing to effectively reflect the resources and time costs required for the execution of `SUICIDE` and `VOTEWITNESS` opcodes, potentially leading to unreasonable costs. 21 | 22 | 1. **Adjustment of Energy Cost:** The current energy cost for the `SUICIDE` and `VOTEWITNESS` opcodea may be comparatively low compared to other opcodes, failing to adequately consider the resources and time costs required for execution. It is proposed to adjust the energy cost for the `SUICIDE` and `VOTEWITNESS` opcodes appropriately to better reflect the actual costs. 23 | 24 | 2. **Consideration of Execution Time:** The execution of the `SUICIDE` and `VOTEWITNESS` opcodes may involve complex operations and require a certain amount of time to complete. Therefore, the impact of opcode execution time on energy cost should be considered to ensure that the cost is proportional to the execution time. 25 | 26 | 3. **Reasonability:** When adjusting energy costs, it should be ensured that the costs reflect the consumption of resources by the opcodes to avoid the possibility of potential DDoS attacks. 27 | 28 | ## Specification 29 | 30 | After the `getAllowEnergyAdjustment(81th)` proposal takes effect, the `SUICIDE` opcode will charge an additional `25,000` energy cost, if the recipient does not exist. Also, the `VOTEWITNESS` opcode will be charged a memory expansion energy cost of at least 32 bytes (array length) for its dynamic array parameters. 31 | 32 | ## Rationale 33 | 34 | The rationale behind proposing an adjustment to the energy cost for the `SUICIDE` and `VOTEWITNESS` opcodes in TVM stems from several key considerations: 35 | 36 | - **Efficiency**: Aligning the cost with actual resource consumption encourages developers to optimize contracts, leading to more efficient resource allocation. 37 | - **Security**: A more accurate cost reduces the risk of abuse and network disruptions, enhancing overall security and stability. 38 | - **Community Involvement**: Engaging the TRON community ensures support and alignment with network interests, promoting transparency and accountability. 39 | 40 | ## Backwards Compatibility 41 | These energy cost increases may potentially break contracts that depend on fixed energy costs. 42 | 43 | 44 | ## Copyright 45 | 46 | Copyright and related rights waived via [CC0](LICENSE.md). 47 | -------------------------------------------------------------------------------- /tip-694.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 694 3 | title: Enhance Verification of Transaction Limitation at Consensus Layer 4 | author: lxcmyf@gmail.com 5 | discussions-to: https://github.com/tronprotocol/tips/issues/694 6 | status: Final 7 | type: Standards Track 8 | category: Core 9 | created: 2024-10-24 10 | ``` 11 | # Simple Summary 12 | 13 | This TIP aims to impose restrictions on account creation transactions, excessively large transactions, multi-result transactions, and near-expiry transactions at the consensus layer to enhance the consistency and stability of transaction processing. 14 | # Motivation 15 | As the TRON network evolves, its security and efficiency continue to improve. Recently, we have identified that although restrictions are already in place for scenarios such as account activation transactions, excessively large transactions, multi-result transactions, and near-expiry transactions, these restrictions have yet to be elevated to the consensus layer, posing potential security risks. While these scenarios do not compromise the chain's asset security and data consistency, they may impact network efficiency. This proposal aims to optimize these scenarios at the consensus layer to further enhance the efficiency and stability of TRON. 16 | # Rationale 17 | This document addresses four scenarios: 18 | 19 | - By limiting the size of account creation transactions, bandwidth consumption is more reasonably managed. 20 | - Strengthening the verification of near-critical transaction sizes avoids situations where transactions within a block may exceed the maximum transaction limit. 21 | - Strictly validating the length of the transaction result list to ensure it aligns with the number of contracts, although inconsistency does not pose a consensus issue. 22 | - Implementing a stricter filtering mechanism for expired transactions to prevent near-expiry transactions from potentially occupying network bandwidth. 23 | # Implementation 24 | The specific optimizations for transaction processing at the consensus stage are implemented as follows: 25 | 26 | 1. Account creation transactions have a size limit: If a transaction has not been packaged and its size, excluding transaction results and signatures, exceeds a default threshold of 1000 bytes (modifiable through proposal voting), an exception for an overly large transaction will be thrown. 27 | 2. When transactions approach the 500KB critical size, verification is conducted during broadcasting and P2P stages: considering the result as the maximum size, if the total size (including the actual transaction body) exceeds the limit, an exception for an overly large transaction will be thrown. 28 | 3. Limiting the transaction result list: calculate the size of each result excluding ContractRet, plus an estimated maximum ContractRet size; if this exceeds 64KB, an exception will be thrown. Additionally, redundant results are verified and removed to ensure alignment with the number of contracts. 29 | 4. Stricter restrictions on near-expiry transactions: the expiry time of transactions is changed from being required to be greater than the head block time to being required to be greater than the slot time of the next block. 30 | To ensure high consistency and optimized efficiency in transaction processing at all stages, including the consensus stage, we will implement this optimization logic through a proposal, thereby further enhancing the consistency and effectiveness of transaction processing. 31 | # Backward Compatibility 32 | After implementing this optimization, there will be no impact on the consistency of existing transaction behaviors, ensuring high consistency in transaction processing during broadcasting, P2P, and consensus stages. 33 | 34 | 35 | ## Copyright 36 | 37 | Copyright and related rights waived via [CC0](LICENSE.md). 38 | -------------------------------------------------------------------------------- /tp/README.md: -------------------------------------------------------------------------------- 1 | ## What is a TP? 2 | A TRON protocol (TP) is a design document describing a particular protocol, 3 | standard, or feature which is already implemented in TRON but not published as a TIP. 4 | A TP should list the properties of the standard, explain the design rationale, and 5 | provide a concise but comprehensive technical specification that can guide developers to implement it conveniently with any other languages. 6 | A TP should not be used for indicating a specific implementation(such as java-tron) or debating governance proposals. 7 | 8 | ## Components 9 | A TP and TIP have similar components, which include a header, a concise summary, an abstract, the motivation, the specification, the rationale, the implementation and a copyright notice. TP is an implemented protocol, so the implementation module can include a core code of java-tron. 10 | All top-level sections are required. 11 | References should be included inline as links or tabulated at the bottom of the section if necessary. 12 | 13 | ## Formatting 14 | ### General 15 | TP specifications must be written in GitHub Flavoured Markdown. 16 | 17 | ### Language 18 | TP specifications should be written in simple English, avoiding obscure terminologies and unnecessary jargons. 19 | The keywords “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in specifications are to be interpreted as described in [RFC 2119](https://tools.ietf.org/html/rfc2119). 20 | ### Pseudocode 21 | Pseudocode in specifications should be language-agnostic and formatted in a simple standard, with line numbers, variables, simple conditional blocks, for loops, and 22 | the English fragments are necessary to explain further functionality. 23 | ## Copyright 24 | All content herein is licensed under [Apache2.0](https://www.apache.org/licenses/LICENSE-2.0). 25 | 26 | -------------------------------------------------------------------------------- /tp/p2p/001-Node-Discover-Protocol.md: -------------------------------------------------------------------------------- 1 | ## Abstract 2 | This specification defines the Node Discovery protocol, a Kademlia-like DHT that stores information about Tron nodes. The Kademlia structure was chosen because it is an efficient way to organize a distributed index of nodes and yields a topology of low diameter. 3 | 4 | ## Definitions 5 | ### Node ID 6 | Identity of a node, consists of 64 bytes. Each node has a unique ID. 7 | ### Node Distance 8 | It is a logical distance, the `distance` between two node IDs is the bitwise exclusive or on the hashes of the IDs, taken as the number. 9 | ``` 10 | distance(n₁, n₂) = keccak256(n₁) XOR keccak256(n₂) 11 | ``` 12 | ### Kademlia Table 13 | Nodes in the Discovery Protocol keep information about other nodes in their neighborhood. Neighbor nodes are stored in a routing table consisting of 'k-buckets'. For each `0 ≤ i < 256`, every node keeps a k-bucket for nodes of distance between `2i` and `2i+1` from itself. 14 | 15 | The Node Discovery Protocol uses `k = 16`, i.e. every k-bucket contains up to 16 node entries. 16 | 17 | ## Protocol 18 | 19 | Node discovery messages are sent as UDP datagrams. Each message contains a `timestamp` field, is an absolute UNIX time stamp, used for message expiration check. Implementations should ignore any expired packets. 20 | 21 | ```typescript 22 | message Endpoint { 23 | bytes address = 1; 24 | int32 port = 2; 25 | bytes nodeId = 3; 26 | } 27 | ``` 28 | 29 | ### Ping Packet (0x01) 30 | ```typescript 31 | message Ping { 32 | Endpoint from = 1; 33 | Endpoint to = 2; 34 | int32 version = 3; 35 | int64 timestamp = 4; 36 | } 37 | ``` 38 | `from` is the message sender. 39 | `to` is the message recipient. 40 | `version` is used to identify a P2P network. 41 | 42 | When a `Ping` packet is received, the recipient should reply with a `Pong` packet. It may also consider the sender for addition into the local table. Implementations should ignore any mismatches in version. 43 | 44 | ### Pong Packet (0x02) 45 | ```typescript 46 | message Pong { 47 | Endpoint from = 1; 48 | int32 version = 2; 49 | int64 timestamp = 3; 50 | } 51 | ``` 52 | `Pong` is the reply to `Ping`. 53 | 54 | ### FindNeighbours Packet (0x03) 55 | ```typescript 56 | message FindNeighbours { 57 | Endpoint from = 1; 58 | bytes targetId = 2; 59 | int64 timestamp = 3; 60 | } 61 | ``` 62 | `targetId` consists of 64 bytes. 63 | 64 | A `FindNeighbours` packet requests information about nodes close to `targetId`, When `FindNeighbours` is received, the recipient should reply with `Neighbors` packets containing the closest 16 nodes to `targetId` found in its local table. 65 | 66 | ### Neighbors Packet (0x04) 67 | ```typescript 68 | message Neighbours { 69 | Endpoint from = 1; 70 | repeated Endpoint neighbours = 2; 71 | int64 timestamp = 3; 72 | } 73 | ``` 74 | `Neighbours` is the reply to `FindNeighbours`. 75 | 76 | ## Implements 77 | 78 | ### K-Bucket update 79 | 80 | The k-bucket entries are sorted by the time last seen — least-recently seen node at the head, most-recently seen at the tail. Whenever a new node N₁ is encountered, it can be inserted into the corresponding bucket. If the bucket contains less than `k` entries N₁ can simply be added as the first entry. If the bucket already contains `k` entries, the least recently seen node in the bucket, N₂, needs to be revalidated by sending a Ping packet. If no reply is received from N₂ it is considered dead, removed and add N₁ to the front of the bucket. 81 | 82 | ### Recursive Lookup 83 | 84 | A lookup locates the `k` closest nodes to a node ID. 85 | 86 | The lookup initiator starts by picking `α` closest nodes to the target it knows of. The initiator then sends concurrent `FindNeighbours` packets to those nodes. `α` is a system-wide concurrency parameter, such as 3. In the recursive step, the initiator resends `FindNeighbours` to nodes it has learned about from previous queries. Of the `k` nodes the initiator has heard of closest to the target, it picks `α` that it has not yet queried and resends `FindNeighbours` to them. Nodes that fail to respond quickly are removed from consideration. 87 | 88 | If a round of `FindNeighbours` queries fails to return a node any closer than the closest already seen, the initiator resends the `FindNeighbours` to all of the `k` closest nodes it has not already queried. The lookup terminates when the initiator has queried and gotten responses from the `k` closest nodes it has seen. 89 | 90 | ```typescript 91 | MAX_STEPS = 8; 92 | ALPHA = 3; 93 | 94 | public synchronized void discover(byte[] nodeId, int round, List prevTried) { 95 | if (round == MAX_STEPS) { 96 | return; 97 | } 98 | List closest = nodeManager.getTable().getClosestNodes(nodeId); 99 | List tried = new ArrayList<>(); 100 | for (Node n : closest) { 101 | if (!tried.contains(n) && !prevTried.contains(n)) { 102 | nodeManager.getNodeHandler(n).sendFindNode(nodeId); 103 | tried.add(n); 104 | wait(50); 105 | } 106 | if (tried.size() == ALPHA) { 107 | break; 108 | } 109 | } 110 | if (tried.isEmpty()) { 111 | return; 112 | } 113 | tried.addAll(prevTried); 114 | discover(nodeId, round + 1, tried); 115 | } 116 | ``` 117 | ## Change Log 118 | -------------------------------------------------------------------------------- /tp/p2p/002-Node-State-Machine.md: -------------------------------------------------------------------------------- 1 | ## Abstract 2 | This document explains different node states and how nodes switch between states. 3 | 4 | ## Definitions 5 | 6 | ### Discovered 7 | `Discovered` is the initial state wherein the local node will send a [Ping message](https://github.com/tronprotocol/tips/blob/master/tp/p2p/001-Node-Discover-Protocol.md#ping-packet-0x01) to the node in this state. A node will be initialized to `Discovered` state in the following cases: 8 | 1. When start a node, its seed node will be initialized to `Discovered` state 9 | 2. When start a node, the nodes which was saved from the last run of [Node Discovery protocol](https://github.com/tronprotocol/tips/blob/master/tp/p2p/001-Node-Discover-Protocol.md) will be initialized to `Discovered` state 10 | 3. If a node has no information saved locally or is in `Nonactive` or `Dead` state when a [Ping message](https://github.com/tronprotocol/tips/blob/master/tp/p2p/001-Node-Discover-Protocol.md#ping-packet-0x01) is received, it will be initialized to `Discovered` state 11 | 4. The new nodes carried by [Neighbours messages](https://github.com/tronprotocol/tips/blob/master/tp/p2p/001-Node-Discover-Protocol.md#neighbors-packet-0x04) will be initialized to `Discovered` state 12 | 13 | ### Dead 14 | `Dead` means the node is offline and unable to communicate. A node will switch from `Discovered` to `Dead` state if it fails to ping. 15 | 16 | ### Alive 17 | `Alive` indicates that node is online and able to communicate with others. A node will switch from `Discovered` to `Alive` state if it pings successfully. The node will then switch from `Alive` to `Active` state if it is successfully written into K-Bucket. 18 | 19 | ### Active 20 | `Active` means the node has been written into [K-Bucket](https://github.com/tronprotocol/tips/blob/master/tp/p2p/001-Node-Discover-Protocol.md#kademlia-table) and is participating in [Node Discovery protocol](https://github.com/tronprotocol/tips/blob/master/tp/p2p/001-Node-Discover-Protocol.md). A node will have its state set to `Active` in the following two cases: 21 | 1. A node will switch from `Alive` to `Active` state if it is successfully written into [K-Bucket](https://github.com/tronprotocol/tips/blob/master/tp/p2p/001-Node-Discover-Protocol.md#kademlia-table) 22 | 2. A node will switch from `Evictcandidate` to `Active` state if it pings successfully 23 | 24 | 25 | ### Evictcandidate 26 | `Evictcandidate` is a temporary state. When a node in `Alive` state attempts to be written into [K-Bucket](https://github.com/tronprotocol/tips/blob/master/tp/p2p/001-Node-Discover-Protocol.md#kademlia-table) but at this time the corresponding bucket is full, it will challenge the node with the earliest update time in the bucket. The challenged node will switch to `Evictcandidate` state and the local node will send a [Ping message](https://github.com/tronprotocol/tips/blob/master/tp/p2p/001-Node-Discover-Protocol.md#ping-packet-0x01) to the node in this state. 27 | 28 | ### Nonactive 29 | `Nonactive` means the node is offline. A node will switch from `Evictcandidate` to `Nonactive` state if it fails to ping. 30 | 31 | ## Implements 32 | Here is the function for switching node states: 33 | ```typescript 34 | public void changeState(State newState) { 35 | State oldState = state; 36 | if (newState == State.DISCOVERED) { 37 | sendPing(); 38 | } 39 | if (!node.isDiscoveryNode()) { 40 | if (newState == State.ALIVE) { 41 | Node evictCandidate = nodeManager.getTable().addNode(**this**.node); 42 | if (evictCandidate == null) { 43 | newState = State.ACTIVE; 44 | } else { 45 | NodeHandler evictHandler = nodeManager.getNodeHandler(evictCandidate); 46 | if (evictHandler.state != State.EVICTCANDIDATE) { 47 | evictHandler.challengeWith(this); 48 | } 49 | } 50 | } 51 | if (newState == State.ACTIVE && oldState == State.ALIVE) { 52 | nodeManager.getTable().addNode(node); 53 | } 54 | if (newState == State.NONACTIVE && oldState == State.EVICTCANDIDATE) { 55 | nodeManager.getTable().dropNode(node); 56 | replaceCandidate.changeState(State.ACTIVE); 57 | } 58 | } 59 | if (newState == State.EVICTCANDIDATE) { 60 | sendPing(); 61 | } 62 | state = newState; 63 | } 64 | ``` 65 | ## Change Log 66 | -------------------------------------------------------------------------------- /tp/p2p/003-Node-Scoring-Policy.md: -------------------------------------------------------------------------------- 1 | ## Abstract 2 | This document explains the scoring policy for neighbouring nodes. Node score is used for determining the priority level to establish connections. The higher the score , the higher the priority. 3 | 4 | ## Definitions 5 | 6 | ### Scoring metrics 7 | 8 | #### Packet loss rate 9 | Packet loss rate indicates the quality of data communication between nodes. The lower the rate is, the better the data communication will be. 10 | 11 | #### Net latency 12 | Net latency reflects the quality of network between nodes. The shorter the net latency is, the better the network quality will be. 13 | 14 | #### TCP traffic 15 | TCP traffic indicates how active it is between nodes. The bigger the TCP traffic is, the more active the communication between nodes will be. 16 | 17 | #### Disconnection count 18 | The number of disconnections between nodes shows their stability. The less frequent the disconnection is, the more stable the nodes will be. 19 | 20 | #### Handshake 21 | Nodes that had successful handshakes will be connected first because they have the same blockchain information with the local node. 22 | 23 | ### Penalty state 24 | Nodes in the state of penalty have a score of 0, and won’t receive score for any other metrics. 25 | Usually, these nodes 26 | 1. disconnected less than 60 seconds ago 27 | 2. are on the badNodes list 28 | 3. have inconsistent blockchain information 29 | 30 | ## Implements 31 | It needs to be determined whether the node is in penalty state when calculating the score of the node. The node will have a score of 0 if it is in this state; otherwise, its score is the sum of all metrics. 32 | 33 | The implementation code is demonstrated as below. 34 | ```typescript 35 | public int getReputation() { 36 | if (isReputationPenalized()) { 37 | return 0; 38 | } 39 | return getPacketLossRateScore() + getNetLatencyScore() + getTcpFlowScore() + getDisconnectionScore() + getHandshakeScore(); 40 | } 41 | ``` 42 | ### Packet Loss Rate Score 43 | Packet Loss Rate Score is inversely proportional to packet loss rate. The score ranges from 0 to 100. 44 | ```typescript 45 | private int getPacketLossRateScore() { 46 | MessageStatistics s = nodeStatistics.messageStatistics; 47 | long in = s.discoverInPong.getTotalCount() + s.discoverInNeighbours.getTotalCount(); 48 | long out = s.discoverOutPing.getTotalCount() + s.discoverOutFindNode.getTotalCount(); 49 | return out == 0 ? 0 : 100 - min((int) ((1 - (double) in / out) * 200), 100); 50 | } 51 | ``` 52 | ### Net Latency Score 53 | Net Latency Score is inversely proportional to average net latency. The score ranges from 0 to 20. 54 | ```typescript 55 | private int getNetLatencyScore() { 56 | return (int) (nodeStatistics.discoverMessageLatency.getAvrg() == 0 ? 0 57 | : min(1000 / nodeStatistics.discoverMessageLatency.getAvrg(), 20)); 58 | } 59 | ``` 60 | ### TCP Traffic Score 61 | TCP Traffic Score is directly proportional to TCP traffic. The score ranges from 0 to 20. 62 | ```typescript 63 | private int getTcpFlowScore() { 64 | return (int) min(nodeStatistics.tcpFlow.getTotalCount() / 10240, 20); 65 | } 66 | ``` 67 | ### Disconnection Score 68 | Disconnection Score is a negative number directly proportional to the number of disconnections and is ten times the Disconnection count. 69 | ```typescript 70 | private int getDisconnectionScore() { 71 | return -10 * nodeStatistics.getDisconnectTimes(); 72 | } 73 | ``` 74 | ### Handshake Score 75 | Handshake Score is either 20, if there is at least 1 successful Handshake, or 0, if there is none. 76 | ```typescript 77 | private int getHandshakeScore() { 78 | return nodeStatistics.p2pHandShake.getTotalCount() > 0 ? 20 : 0; 79 | } 80 | ``` 81 | ## Change Log 82 | -------------------------------------------------------------------------------- /tp/p2p/005-Handshake.md: -------------------------------------------------------------------------------- 1 | ## Abstract 2 | 3 | This document explains a TCP Handshake process that is done by exchanging a pair of `Hello` messages which carry blockchain information. Only when two nodes’ information are compatible can make a successful Handshake. 4 | 5 | ## Definitions 6 | 7 | ### Genesis Block 8 | A blockchain is made up by a chain of blocks, each labeled with a unique ID. The very first block generated is called a Genesis Block at the block height of 0. 9 | 10 | ### Solid Block 11 | Solid Blocks are blocks that are irretrievable. A block cannot be erased from the blockchain once it is solidified. Refer to [Calculation of Solid Blocks](#calculation-of-solid-blocks). 12 | 13 | ### Head Block 14 | The latest block on the blockchain, representing the max block height. 15 | 16 | ## Protocol 17 | 18 | Handshake occurs immediately after a TCP connection is created. The node initiating the TCP connection request will send a Hello message to its neighbours; neighbours who receive and accept the message will return a Hello message to the sender. Upon completing a Handshake, nodes can have further communication under standard TRON Protocol. Here is the definition of a `Hello` message. 19 | ```typescript 20 | message HelloMessage { 21 | message BlockId { 22 | bytes hash = 1; 23 | int64 number = 2; 24 | } 25 | Endpoint from = 1; 26 | int32 version = 2; 27 | int64 timestamp = 3; 28 | BlockId genesisBlockId = 4; 29 | BlockId solidBlockId = 5; 30 | BlockId headBlockId = 6; 31 | bytes address = 7; 32 | bytes signature = 8; 33 | } 34 | ``` 35 | `BlockId.hash` consists of the hash value and block height of a specific block; each block has its unique BlockId. 36 | 37 | `BlockId.number` indicates the block height. 38 | 39 | `from` represents a node identifier and consists of node ip, port and node ID. 40 | 41 | `version` represents a p2p version; connections can only be established between nodes with same versions. 42 | 43 | `timestamp` indicates the time the connection request is made. 44 | 45 | `genesisBlockId` represents the ID of the Genesis Block; connections can only be established between nodes having identical Genesis Blocks. 46 | 47 | `solidBlockId` represents the ID of the Solid Block; connections can only be established when the blockchain of one node comprises the Solid Block of the other. 48 | 49 | `headBlockId` represents the ID of the Head Block. 50 | 51 | ## Implements 52 | 53 | ### Calculation of Solid Blocks 54 | 55 | A block is identified as Solid Block if it has been verified by two thirds of all SRs. The implementation code is demonstrated below. 56 | ```typescript 57 | SOLIDIFIED_THRESHOLD = 70; 58 | 59 | private void updateSolidBlock() { 60 | List numbers = consensusDelegate.getActiveWitnesses().stream() 61 | .map(address -> consensusDelegate.getWitness(address.toByteArray()).getLatestBlockNum()) 62 | .sorted() 63 | .collect(Collectors.toList()); 64 | long size = consensusDelegate.getActiveWitnesses().size(); 65 | int position = (int) (size * (1 - SOLIDIFIED_THRESHOLD * 1.0 / 100)); 66 | long newSolidNum = numbers.get(position); 67 | long oldSolidNum = consensusDelegate.getLatestSolidifiedBlockNum(); 68 | if (newSolidNum < oldSolidNum) { 69 | return; 70 | } 71 | consensusDelegate.saveLatestSolidifiedBlockNum(newSolidNum); 72 | } 73 | ``` 74 | 75 | ### Hello Message Verification 76 | The Hello message received by the node will be examined in the following steps. 77 | 1. Verify the P2P version. Nodes with different version numbers will be disconnected. 78 | 2. Verify the Genesis Block. Nodes with different Genesis Blocks will be disconnected. 79 | 3. Verify the Solid Blocks. Nodes will be disconnected if the max block height of the Solid Blocks on local blockchain exceeds that of the neighbouring node and the Solid Blocks of the neighbour are not on the chain. 80 | ```typescript 81 | if (msg.getVersion() != Args.getInstance().getNodeP2pVersion()) { 82 | channel.disconnect(ReasonCode.INCOMPATIBLE_VERSION); 83 | return; 84 | } 85 | 86 | if (!Arrays 87 | .equals(manager.getGenesisBlockId().getBytes(), msg.getGenesisBlockId().getBytes())) { 88 | channel.disconnect(ReasonCode.INCOMPATIBLE_CHAIN); 89 | return; 90 | } 91 | 92 | if (manager.getSolidBlockId().getNum() >= msg.getSolidBlockId().getNum() && !manager 93 | .containBlockInMainChain(msg.getSolidBlockId())) { 94 | channel.disconnect(ReasonCode.FORKED); 95 | return; 96 | } 97 | ``` 98 | ## Change Log 99 | -------------------------------------------------------------------------------- /tp/ticp/ticp-blockheader-sync/Synchronize_block_headers.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tronprotocol/tips/237567804056d5151be00e43eda80053b5b66da9/tp/ticp/ticp-blockheader-sync/Synchronize_block_headers.png -------------------------------------------------------------------------------- /tp/ticp/ticp-blockheader-sync/Synchronize_block_headers_between_chains.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tronprotocol/tips/237567804056d5151be00e43eda80053b5b66da9/tp/ticp/ticp-blockheader-sync/Synchronize_block_headers_between_chains.png -------------------------------------------------------------------------------- /tp/ticp/ticp-blockheader-sync/Synchronize_block_headers_when_new_node_add.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tronprotocol/tips/237567804056d5151be00e43eda80053b5b66da9/tp/ticp/ticp-blockheader-sync/Synchronize_block_headers_when_new_node_add.png -------------------------------------------------------------------------------- /tp/ticp/ticp-blockheader-sync/Synchronize_block_headers_within_chains.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tronprotocol/tips/237567804056d5151be00e43eda80053b5b66da9/tp/ticp/ticp-blockheader-sync/Synchronize_block_headers_within_chains.png -------------------------------------------------------------------------------- /tp/ticp/ticp-optimized-pbft/pbft-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tronprotocol/tips/237567804056d5151be00e43eda80053b5b66da9/tp/ticp/ticp-optimized-pbft/pbft-1.png -------------------------------------------------------------------------------- /tp/ticp/ticp-optimized-pbft/pbft-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tronprotocol/tips/237567804056d5151be00e43eda80053b5b66da9/tp/ticp/ticp-optimized-pbft/pbft-2.png -------------------------------------------------------------------------------- /tp/ticp/ticp-spv-proof-support/ticp-SPV-PROOF-SUPPORT.md: -------------------------------------------------------------------------------- 1 | ``` 2 | ticp: 1 3 | title: SPV proof support 4 | author: @lvs007 5 | type: Tron Inter-blockchain Communication Protocol 6 | category: CORE 7 | status: Draft 8 | created: 2020-03-09 9 | ``` 10 | 11 | ## Summary 12 | 13 | This doc describes a solution to support SPV proof 14 | 15 | ## Abstract 16 | 17 | This standard defines a way to support SPV correctness and security, In this way client can get certified block headers. The client can use transactions' Merkel root in headers to make a Merkel proof 18 | 19 | 20 | 21 | ## Motivation 22 | 23 | Support more powerful features such as IBC in the future 24 | 25 | ## Specification 26 | 27 | In DPOS consensus every slot is assigned to the only legal SR, So within one schedule if verifiers know the legal SR list they can verify every block header easily. Since verifiers don't process most transaction including vote transaction. they have no way to know the voting result. In other words they are unable to know the next legal SR list. The focus of this problem is how to handle the maintenance period correctly. 28 | Based on the above reasons we can solve this problem by recording SR list in one type of BPFT messages which are sent by the previous legal SR list we trust. The PBFT information is in here #39 29 | 30 | ## Algorithm 31 | 32 | We can use threshold signature to reduce the signature size. The new data struct includes the next SR list and a threshold signature signed by more than 2/3 SRs. This new data struct will record in the block headers of the next schedule's SRs. Verifiers can check this data to determine the new SR list is legal or not. 33 | 34 | ## Proto 35 | 36 | ```SrList 37 | 38 | message SrList { 39 | message raw { 40 | bytes nextSrList = 1; 41 | } 42 | bytes sr_signature = 2; 43 | } 44 | 45 | 46 | -------------------------------------------------------------------------------- /tp/ticp/ticp-verctor-commitment/ticp-Vector-Commitment.md: -------------------------------------------------------------------------------- 1 | ``` 2 | tip: 106 3 | title: Vector Commitment In TIBC 4 | author: @olivier 5 | type: Tron Inter-blockchain Communication Protocol 6 | discussions to: https://github.com/tronprotocol/TIPs/issues/106 7 | category: TRC 8 | status: Draft 9 | created: 2019-12-05 10 | ``` 11 | 12 | ## Summary 13 | This document introduces the major use cases of Vector Commitment in TICP(Tron Inter-blockchain Communication Protocol) and lists all possible functions and properties in the commitment scheme that may need to be included in TICP. 14 | 15 | 16 | ## Abstract 17 | The commitment scheme refers to a cryptographic scheme under which one can transmit encrypted messages to another, and then reveal the sent messages through a certain approach. The commitment scheme needs to ensure immutability after the transmitter has sent the encrypted message. A typical commitment includes two phases: the commit phase and the reveal phase. 18 | 19 | A Vector Commitment (VC) is a position-binding commitment which can be opened at any position to a unique value with a succinct membership and/or non-membership proof for any elements in the vector. Merkle tree structure is a VC solution that can be opened at a logarithmic size. 20 | 21 | ## Motivation 22 | In the actual process of cross-chain state transition, we need to transfer an existing state from one chain to another and have the state verified on the new chain at the same time. TICP requires an efficient VC solution to prove whether or not a particular state exists in a particular path. 23 | 24 | This protocol plans to implement the VC protocol framework first with the Merkle-tree structure and later with the VC framework based on RSA so as to meet demands for more complex opens. 25 | 26 | ## Rationale 27 | A Merkle Proof completes membership proof through log-size proofs. In order to prove whether Value or Hash exists in a Merkle tree, the information below is needed: 28 | 29 | 1. Merkle Root 30 | 2. Hash Value that needs to be verified 31 | 3. All Hash Values from Root Node to Leaf Node along Merkle Path 32 | 4. Hash Values at the other side of nodes in Merkle Path 33 | 34 | In normal circumstances, No.3 is optional, as all Hash Values of nodes on Merkle Path including Root Node can be calculated based on No.2 and No.4. If the calculation proves to be correct, then there truly exists a path going from Leaf Node to Root Node, which confirms the real presence of Leaf Node in the entire Merkle tree, thus completing membership proof. 35 | 36 | ## Specification 37 | 38 | #### Datatypes 39 | 40 | A VC scheme should comprise the following data type and be serialized. java-tron adopts Protobuf to serialize data. 41 | 42 | ##### Commitment Root 43 | 44 | Commitment Root, constant in size, is the commitment state of the VC framework 45 | 46 | ```typescript 47 | public class CommitmentRoot 48 | ``` 49 | 50 | ##### Commitment Path 51 | 52 | Commitment Path is a supplementary path used to verify commitment proof, and the path can be defined in any data structure. 53 | 54 | ```typescript 55 | public class CommitmentPath 56 | ``` 57 | 58 | ##### Commitment Proof 59 | 60 | Commitment Proof indicates the membership or non-membership state of one or a group of elements and is usually combined with a known commitment root to perform verification. The proof should be succinct. 61 | 62 | ```typescript 63 | public class CommitmentProof 64 | ``` 65 | 66 | #### Required functions 67 | 68 | The commitment framework must support the following functions 69 | 70 | ##### Initalisation 71 | 72 | With the getRoot function, a constant-size commitment, which can be used to verify Proofs, is generated from a set of ordinal values. 73 | 74 | ```typescript 75 | public CommitmentRoot getRoot(List values) 76 | ``` 77 | 78 | #### Adding & Removing 79 | 80 | We need to first define a commitment state sum that has all Commitment Paths to make the function more succinct. 81 | 82 | ```typescript 83 | public class CommitmentTree 84 | 85 | public CommitmentTree getTree(List paths) 86 | ``` 87 | 88 | With add function, an element is added to a particular path of VC. 89 | 90 | ```typescript 91 | public CommitmentRoot add(CommitmentTree tree, Path path, Value value) 92 | ``` 93 | 94 | With remove function, an element is removed from a particular path of VC. 95 | 96 | ```typescript 97 | public CommitmentRoot remove(CommitmentTree tree, Path path) 98 | ``` 99 | 100 | #### Proof generation 101 | 102 | createProof function produces a proof, which verifies that a particular value is included in a particular commitment. 103 | 104 | ```typescript 105 | public CommitmentProof createProof(CommitmentRoot root, CommitmentPath path, Value value) 106 | ``` 107 | 108 | #### Proof verification 109 | 110 | verifyProof function verifies whether a particular value verified in the particular commitment proof is correct. 111 | 112 | 113 | ```typescript 114 | public boolean verifyProof(CommitmentRoot root, CommitmentProof proof, Value value) 115 | ``` 116 | 117 | ## Implementation 118 | coming soon 119 | 120 | ## Reference 121 | - [Bitcoin: A Peer-to-Peer Electronic Cash System](https://bitcoin.org/bitcoin.pdf) 122 | - [Vector Commitments and their Applications](https://eprint.iacr.org/2011/495.pdf) 123 | --------------------------------------------------------------------------------