Giter Site home page Giter Site logo

tips's Introduction

TIPs

TRON Improvement Proposals (TIPs) describe standards for the TRON platform, including core protocol specifications, client APIs, and contract standards.


Contents


TIPs Guide

ID Title Author Type Category Hard fork Status
TIP 10 TRON Token Standard [email protected] Standards Track Core false Final
TIP 12 TRON Event Subscription Model [email protected] Informational TRC false Final
TIP 13 Design of TRON account [email protected] Standards Track Core false Final
TIP 16 TRON Account Multi-Signature [email protected] Standards Track Core true Final
TIP 17 TRON Adaptive Energy Limit Model [email protected] Standards Track Core true Final
TIP 19 TRC-19 Deferred transaction [email protected] Standards Track Core true Deferred
TIP 20 TRC-20 Token Standard [email protected] Standards Track TRC true Final
TIP 23 Add the account world status tree root to the block header [email protected] Standards Track Core true Accepted
TIP 24 Implement of DB storage with RocksDB [email protected] Standards Track Core false Final
TIP 26 Create2 [email protected] Standards Track VM false Final
TIP 28 Built-in Message Queue in Event Subscription Model [email protected] Informational false Final
TIP 29 Bitwise shifting instructions in Tron [email protected] Standards Track VM true Final
TIP 30 Code hash instructions [email protected] Standards Track VM true Final
TIP 31 Trigger constant contract [email protected] Standards Track VM true Final
TIP 32 Clear the ABI of contract [email protected] Standards Track VM true Final
TIP 37 Forbid using TransferContract & TransferAssetContract for contract account [email protected] Standards Track VM true Final
TIP 41 Optimize transactionHistoryStore occupancy space [email protected] Standards Track Core false Final
TIP 43 Precompiled contract function for signature parallel verification [email protected] Standards Track VM true Final
TIP 44 Address.isContract instructions [email protected] Standards Track VM true Final
TIP 51 Rate limit of API traffic [email protected] Standards Track Interface false Final
TIP 53 Optimize the current TRON delegation mechanism [email protected] Standards Track Core true Final
TIP 54 Automatically active non-existent account when transferring TRX/TRC10 asset in a smart contract [email protected] Standards Track VM true Final
TIP 60 Precompiled contract function for multi-signature verification [email protected] Standards Track VM true Accepted
TIP 62 Tron consensus algorithm introduction [email protected] Standards Track Core false Final
TIP 64 Tron tron mix consensus Analytics [email protected] Standards Track Core false Draft
TIP 101 Wallet Keystore Specification [email protected] Standards Track TRC false Last Call
TIP 102 Hierarchical Deterministic Wallet [email protected] Standards Track TRC false Last Call
TIP 104 Data Signing Specification [email protected] Standards Track TRC false Last Call
TIP 105 Multi-signature Permission Operation [email protected] Standards Track TRC true Final
TIP 120 ECDSA Signature Encoding Specification [email protected] Standards Track TRC false Final
TIP 127 Support Tron-DEX based on system contracts [email protected] Standards Track CORE false Draft
TIP 128 TIP128 Lite Fullnode support [email protected] Standards Track CORE false Draft
TIP 135 Shielded TRC-20 Contract [email protected] Standards Track TRC false Final
TIP 137 Zero-knowledge Proof Verification functions [email protected] Standards Track VM true Final
TIP 138 Pedersen hash function [email protected] Standards Track VM true Final
TIP 156 Vote instructions in TVM [email protected] Standards Track VM true Withdrawn
TIP 157 Freeze instructions in TVM [email protected] Standards Track VM true Final
TIP 165 TRC-165 Standard Interface Detection In Contract [email protected] Standards Track TRC true Final
TIP 171 STAKE instructions in TVM [email protected] Standards Track VM true Withdrawn
TIP 174 CHAINID instructions in TVM [email protected] Standards Track VM true Final
TIP 175 SELFBALANCE instructions in TVM [email protected] Standards Track VM true Final
TIP 176 altbn128 operation energy reduction in TVM [email protected] Standards Track VM true Final
TIP 178 TOKENISSUE and UPDATEASSET Instruction in TVM [email protected] Standards Track VM true Withdrawn
TIP 191 Signed Data Standard [email protected] Standards Track TRC false Final
TIP 196 Reward SRs with the transaction fees charged for bandwidth and Energy [email protected] Standards Track Core true Final
TIP 204 Make MAX_FEE_LIMIT configurable as a chain property [email protected] Standards Track VM false Final
TIP 207 A proposal to improve network resources model [email protected] Standards Track Core true Draft
TIP 209 Adapt to Solidity 0.6.0 [email protected] Standards Track VM false Final
TIP 222 Improve transaction execution speed [email protected] Standards Track TRC true Final
TIP 250 Include transaction results on the chain [email protected] Standards Track Core true Final
TIP 268 SmartContract ABI optimization [email protected] Standards Track VM false Final
TIP 269 Optimize the performance of block processing [email protected] Standards Track Core false Final
TIP 271 Vote for SR in Smart Contract [email protected] Standards Track VM true Final
TIP 272 Compatible with EVM [email protected] Standards Track VM true Final
TIP 276 Optimize block verification logic [email protected] Standards Track Core false Final
TIP 281 Optimize the query of database [email protected] Standards Track Core false Final
TIP 285 Node startup optimization [email protected] Standards Track Core false Final
TIP 289 Block Broadcast Optimization [email protected] Standards Track Core true Final
TIP 290 Dynamic store optimization [email protected] Standards Track Core true Final
TIP 292 Add a proposal to adjust the free net limit in an account [email protected] Standards Track TRC true Final
TIP 293 Add a proposal to adjust the total net limit [email protected] Standards Track TRC true Final
TIP 295 Optimize assets of account [email protected] Standards Track Core false Final
TIP 298 Reformat manifest [email protected] Standards Track Core false Final
TIP 306 Adapt to solidity_0.8.4 [email protected] Standards Track VM false Final
TIP 318 Adapt to Ethereum London Upgrade [email protected] Standards Track VM false Final
TIP 343 DB params optimization [email protected] Standards Track Core false Draft
TIP 344 Optimize instruction execution for TVM [email protected] Standards Track VM false Final
TIP 362 Optimized node broadcast data caching [email protected] Standards Track Core false Final
TIP 366 Node startup optimization [email protected] Standards Track Core false Final
TIP 369 Node support prometheus metrics [email protected] Standards Track Core false Final
TIP 370 Node support conditionalized stop [email protected] Standards Track Core false Final
TIP 382 TIP-382: Optimize the data structure of account assets [email protected] Standards Track Core false Final
TIP 383 TIP-383: Optimize transaction cache loading [email protected] Standards Track Core false Final
TIP 387 TIP-387: Transaction memo fee [email protected] Standards Track Core false Final
TIP 388 TIP-388: Optimize light node synchronization logic [email protected] Standards Track Core false Final
TIP 391 TIP-391: Optimize fetch block process [email protected] Standards Track Core false Final
TIP 397 Raise limit of the 13th network parameter [email protected] Standards Track VM true Final
TIP 425 TIP-425: Speed up TCP connection establishment [email protected] Standards Track Net false Final
TIP 428 TIP-428: Increase the probability that the block processing thread acquires the lock [email protected] Standards Track Core false Final
TIP 440 Transaction cache optimization [email protected] Standards Track Core false Final
TIP 461 Optimize data consistency for system abnormals [email protected] Standards Track Core false Final
TIP 465 New reward calculation algorithm [email protected] Standards Track Core true Final
TIP 467 Stake 2.0 - A new TRON stake model [email protected] Standards Track Core false Final
TIP 474 Optimize the return value of chainid opcode [email protected] Standards Track VM true Final
TIP 476 Delegate Data Structure Optimization [email protected] Standards Track Core false Final
TIP 491 Dynamic Energy Model [email protected] Standards Track VM true Final
TIP 534 Remove Vulnerable APIs [email protected] Standards Track Core false Final
TIP 541 Support canceling unstaking in Stake 2.0 [email protected] Standards Track Core true Final
TIP 542 Resource delegating supports customizable lock period [email protected] Standards Track Core true Final
TIP 543 Implement EIP-3855 PUSH0 instruction [email protected] Standards Track VM true Final
TIP 544 Add data to the http interfaces interacting with smart contract [email protected] Standards Track Interface false Final
TIP 547 Connection precheck before P2P communication [email protected] Standards Track Networking false Final
TIP 548 Node Discovery via DNS [email protected] Standards Track Networking false Final
TIP 549 P2P support IPv6 protocol [email protected] Standards Track Networking false Final
TIP 550 P2P message snappy compression [email protected] Standards Track Networking false Final
TIP 555 Network upgrade logic optimization [email protected] Standards Track Core false Final
TIP 586 GRPC Implementation for Resource Price Interfaces [email protected] Standards Track Core false Final
TIP 592 Supplement Disconnect Reasons in Java-tron [email protected] Standards Track Networking false Final
TIP 621 Add code version column to HelloMessage [email protected] Standards Track Networking false Final
TIP 635 Optimize Reward Withdrawal To Improve TPS [email protected] Standards Track Core true Final
TIP 652 Announce EIP-6049 Deprecate SELFDESTRUCT [email protected] Meta VM false Review
TIP 653 Adjust energy cost of SUICIDE and VOTEWITNESS opcodes in TVM [email protected] Standards Track VM true Review
TIP 712 TRON typed structured data hashing and signing [email protected] Standards Track Interface false Final
TIP 721 TRC-721 Non-Fungible Token Standard [email protected] Standards Track TRC true Final
TIP 1102 TIP-1102: Opt-in account exposure [email protected] Standards Track Interface false Final
TIP 1155 Multi Token Standard [email protected] Standards Track TRC false Final
TIP 1193 TIP-1193: TRON Provider JavaScript API [email protected] Standards Track Interface false Final
TIP 3326 TIP-3326: Wallet Switch TRON Chain Method [email protected] Standards Track Interface false Final
TIP 4906 TRC-4906: Fork from ERC-4907 Rental NFT <lopeed_prcy> Standards Track TRC false Final

To Submit a TIP

Before you submit a TIP, you need to create an issue for comment and add the issue URL to your TIP header.

1. Fork the repository by clicking "Fork" in the top right.

2. Add your TIP to your fork of the repository. There is a TIP template here.

3. Submit a Pull Request to TRON's TIPs repository.

Your first PR should be a first draft of the final TIP. It must meet the formatting criteria enforced by the build (largely, correct metadata in the header). An editor will manually review the first PR for a new TIP and assign it a number before merging it.

Make sure you include a discussions-to header with the URL to a discussion forum or open GitHub issue where people can discuss the TIP as a whole. If a TIP is about the feature development of java-tron, and a PR of the development exists, in your TIP and your java-tron's PR you need to refer each other's github link.

When you believe your TIP is mature and ready to progress past the draft phase, you should do one of two things:

  • For a Standards Track TIP of type Core, ask to have your issue added to the agenda of an upcoming All Core Devs meeting, where it can be discussed for inclusion in a future hard fork. If implementers agree to include it, the TIP editors will update the state of your TIP to 'Accepted'.

  • For all other TIPs, open a PR changing the state of your TIP to 'Final'. An editor will review your draft and ask if anyone objects to its being finalized. If the editor decides there is no rough consensus, they may close the PR and request you fix the issues in the draft before trying again.


TIP Status

TIPs are separated into several statuses.

  • Draft: A TIP that is undergoing rapid iteration and changes.

  • Last Call: A TIP that is done with its initial iteration and ready for review by a wide audience.

  • Accepted: A core TIP that has been in the Last Call for at least 2 weeks and any technical changes that were requested have been addressed by the author. The process for Core Devs to decide whether to encode a TIP into their clients as part of a hard fork is not part of the TIP process. If such a decision is made, the TIP will move to the final.

  • Final (non-Core): A TIP that has been in the Last Call for at least 2 weeks and any technical changes that were requested have been addressed by the author.

  • Final (Core): A TIP that the Core Devs have decided to implement and release in a future version or has already been released.

  • Active: If the TIPs are never meant to be completed, the TIPs may have a status of “Active”.

  • Abandoned: If a TIP is no longer pursued by the original authors or it may not be a (technically) preferred option anymore.

  • Rejected: A TIP that is fundamentally broken or a Core TIP that was rejected by the Core Devs and will not be implemented.

  • Superseded: A TIP which was previously Final but is no longer considered state-of-the-art. Another TIP will be in the Final status and cite the Superseded TIP.

  • Deferred: A TIP which isn't accepted now, it may be accepted in the future.


TIP Types

TIPs are separated into several types, and each has its list of TIPs.

  • Standard Track: Describes any change that affects most or all TRON implementations, such as a change in block or transaction validity rules, proposed application standards/conventions, or any change or addition that affects the interoperability of applications using TRON. Furthermore, Standard TIPs can be broken down into the following categories.

    1.Core: Improvements requiring a consensus fork, as well as changes that are not necessarily consensus critical but may be relevant to "core dev" discussions.

    2.Networking: Includes improvements around network protocol.

    3.Interface: Includes improvements around client API/RPC specifications and standards.

    4.TRC: Application-level standards and conventions, including contract standards such as token standards (TRC-20).

    5.TVM: Includes improvements around TRON Virtual Machine.

  • Informational: Describes a TRON design issue, or provides general guidelines or information to the TRON community, but does not propose a new feature.

For further discussion, please enter Telegram

tips's People

Contributors

317787106 avatar benson0224 avatar dbuarque avatar dorianrust avatar ethan1844 avatar federico2014 avatar forfreeday avatar halibobo1205 avatar jiangyy0824 avatar justintron avatar jwrct avatar lredhdx avatar lvs007 avatar lxcmyf avatar nanfengpo avatar renchenchang avatar sean-liu55 avatar sh11thead avatar shydesky avatar spidemen avatar ss334452 avatar taihaofu avatar tomatoishealthy avatar vikingzzu avatar vivian1912 avatar yanghang8612 avatar yrp avatar zergweak avatar zhang0125 avatar zhaohong avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tips's Issues

TRC-35: Add MMR hash to block header

tip: 35
title: TRC-35: Add MMR hash to block header
author: Tomasz Zdybał <[email protected]>
discussions to: https://github.com/tronprotocol/TIPs/issues/...
category: TRC
status: draft
created: 2019-04-24

Abstract

Merkle Mountain Ranges provide alternative, succinct way to validate consistency of blockchain.

Motivation

Adding MMR hash to block header enables new, lightweight, fast transaction validation method and implementation of thin-client software - FlyClient.
Synchronization of entire blockchain is a very time and disk space consuming process, it's not feasible for mobile and IoT devices. Growing disk-space requirements is a scalability problem.
Adding MMR hash to block header enables creation of very-lightweight client, that are able to validate blocks within constant space bound and in non-interactive manner.

Specification

MMR hash should be added to block header, for all blocks after activation of this TIP.
All the implementation details can be found in FlyClient paper and for example in Grin documentation - this issue is not a good place to duplicate all the theoretical and practical details.

Rationale

Adding new field (instead of replacing parent hash with MMR hash) makes enabling of this feature easier. Older clients will simply ignore the new field (thanks to GRPC). Only SR nodes must be updated, to ensure that all new blocks contains MMR hash.

Backwards Compatibility

This change is targeted at new clients. Old clients can ignore the new field.

TRC: Code hash instructions

tip: 30
title: TRC-30 Code hash instructions
author: llwslc<[email protected]> 
discussions to: https://github.com/tronprotocol/TIPs/issues/30
category: TRC
status: accepted
created: 2019-03-27

Simple Summary

To provide a new opcode, which returns the keccak256 hash of a contract's code. Just like EIP1052 in Ethereum

Abstract

This TIP specifies a new opcode, which returns the keccak256 hash of a contract's code.

Motivation

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.

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.

Specification

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.

In case the account does not exist 0 is pushed to the stack.

In case the account does not have code the keccak256 hash of empty data (i.e. c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470) is pushed to the stack.

The energy cost of the EXTCODEHASH is 400.

Rationale

As described in the motivation section, this opcode is widely useful, and saves on wasted energy in many cases.

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.

The EXTCODEHASH distincts accounts without code and non-existing accounts.
This is consistent with the way accounts are represented in the state trie.
This also allows smart contracts to check whenever an account exists.

Backwards Compatibility

There are no backwards compatibility concerns.

Test Cases

  1. The EXTCODEHASH of the account without code is c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470
    what is the keccack256 hash of empty data.
  2. The EXTCODEHASH of non-existent account is 0.
  3. The EXTCODEHASH of an precompiled contract is either c5d246... or 0.
  4. If EXTCODEHASH of A is X, then EXTCODEHASH of A + 2**160 is X.
  5. The EXTCODEHASH of an account that selfdestructed in the current transaction.
  6. The EXTCODEHASH of an account that selfdestructed and later the selfdestruct has been reverted.
  7. The EXTCODEHASH of an account created in the current transaction.
  8. The EXTCODEHASH of an account that has been newly create and later the creation has been reverted.
  9. The EXTCODEHASH of an account that firstly does not exist and later is empty.
  10. The EXTCODEHASH of an empty account that is going to be cleared by the state clearing rule.

TRC-CRS02: SPV proof support

Simple Summary

This doc describes a solution to support SPV proof

Abstract

This standard defines a way to support SPV proof, In this way client can get certified block headers. The client can use transactions' Merkel root in headers to make a Merkel proof

Motivation

Support more powerful features such as IBC in the future

Specification

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.
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

Algorithm

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.

Proto

message SrList {
message raw {
bytes currentSrList = 1;
bytes nextSrList = 2;
}
bytes sr_signature = 3;
}

TRC: Tron event subscribe model

tip: 12
title: TRC-12 Tron event subscribes model
author: jiangyy<[email protected]> 
discussions to: https://github.com/tronprotocol/TIPs/issues/12
status: accepted
type: Standards Track
category: TRC
created: 2018-12-20

Simple Summary

This doc describes event subscribe model of Tron.

Abstract

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.

Motivation

This will allow dapps developers or exchange to subscribe any event triggered on Tron.

Specification

Events to subscribe

  • transactionTrigger, triggered after the transaction is processed
  • blockTrigger, triggered after a block is inserted into block chain
  • contractLogTrigger, triggered after smart contract is executed
  • contractEventTrigger, triggered after smart contract is executed

Filter

  • 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.
  • toBlock: end of the range, it could be set to "", "latest" or specified block number, the default value is "latest".
  • contractAddress: restricts matches to events created by specific contracts.
  • 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.

Notice: No support the historical data query.

Smart Contract log

contractLogTrigger is used to represent the object of smart contract log, which has following parameters:

  • transactionId, transaction id.
  • contractAddress, contract address.
  • callerAddress, contract caller address.
  • blockNumber, the block number of transaction.
  • blockTimestamp, the packing time of a transaction in block.
  • contractTopics, list of topics that Log can output in Solidity language.
  • data, data filed that Log can output in Solidity language.

Smart Contract event

contracteventTrigger is used to represent the object of smart contract log, which has following parameters:

  • transactionId, transaction id.
  • contractAddress, contract address.
  • callerAddress, contract caller address.
  • blockNumber, the block number of transaction.
  • blockTimestamp, the packing time of a transaction in block.
  • eventSignature, signature string of event.
  • contractTopicMap, It is a map from a topic name to topic value that event can output in Solidity language.
  • data, data filed that log can output in Solidity language.

Trigger event

  • Triggering block event, create a blockTrigger when the block is inserted.
  • Triggering transaction event, create a txsTrigger before the transaction is executed.
  • Triggeingr smart contract log, create a contractLogTrigger after the contract is executed.
  • Triggering smart contract event, create a contractEventTrigger after the contract is executed.

Send trigger

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.

  • fromBlock: 0x1000000
  • toBlock: 0x1200000
  • contractAddress: "AddressA"
  • topics: ["TopicA"]

Plugin implementation

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.

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.

Developers are flexible in defining plug-in configuration files, including message queue server addresses, defined Trigger types, and so on.

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.

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.

TRC1700: Non-Exhaustible Token Standard

This standard is co-authored by @yhuag @Roger-Wu @dAAAb

This standard is also submitted on Ethereum as ERC1700.

Preamble

TIP: <to be assigned>
Title: Non-Exhaustible Token Standard (NET)
Author: Lee Ting-Ting <[email protected]>, Hu Yao-Chieh <[email protected]>
Type: Standard
Category: TRC
Status: Draft
Created: 2019-01-15

Simple Summary

Non-Exhaustible Token (NET)

  • Each NET can have non-exhaustible copies
  • Specify a pool of NET for copy creation

Solidity Interface

interface IERC {

  event PoolAdded(
    uint256 indexed photoPoolId
  );

  event PhotoAdded(
    uint256 indexed photoId,
    uint256 indexed modelId,
    uint256 indexed photographerId
  );

  event CardDrawn(
    uint256 indexed cardId,
    uint256 indexed photoId,
    uint256 rarityScore,
    address indexed to
  );

  event Transfer(
    uint256 indexed cardId,
    address indexed from,
    address indexed to
  );

  function addPhoto(uint256 _modelId, uint256 _photographerId) external;

  function addPhotoPool(uint256[] _photoIds) external;

  function drawCard(uint256 _photoPoolId) external payable;

  function transfer(uint256 _cardId, address _to) external;

  function drawnCardIdsOf(address _user) external view returns(uint256[] cardIds);

  function playerDrawnCardIdIsHeldOf(address _user, uint256 _cardId) external view returns(bool);

  function drawnCardsOf(address _user) external view returns(uint256[] cardIds, uint256[] photoIds, uint256[] rarityScores);

}

A sample implementation can be found on CryptoBeauty.

A DApp sample based on the ERC1700 Standard on TRON.

Copyright

Copyright and related rights waived via CC0.

TRC-60:Precompiled contract function for multi-signature verification

tip: 60
title: TRC-60:Precompiled contract function for multi-signature verification
author: Sh11thead <[email protected]>
discussions to: https://github.com/tronprotocol/TIPs/issues/60
category: TRC
status: accepted
created: 2019-09-20

Simple Summary

This doc describes a native TVM function which is used to validate multi-signature for a provided account.

Abstract

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 .

Motivation

Developer hope to validate multi-sign for account with specific permission in smart contracts.

Specification

Add a new function named validatemultisign in solidity compiler .

This function could takes 4 parameters:

validatemultisign(
address accountAddress, // account address  
uint256 permissionId, //permissionId for account
bytes32 content, //content for verifying
bytes[] signatures//signatures to be verified
)

Pay special attention to the parameter signatures,
The specific signature method is implemented in java code as follows:

//parameters address,permissionId ,hash
byte[] address  = address
int permissionId = permissionId ;
byte[] hash= originData;

//merge
byte[] merged =  ByteUtil.merge(address,ByteArray.fromInt(permissionId),data);
//get the content to sign
byte[] toSign = Sha256Hash.hash(merged);


//sign content
List<Object> signs = new ArrayList<>();
signs.add(Hex.toHexString(key1.sign(toSign).toByteArray()));
signs.add(Hex.toHexString(key2.sign(toSign).toByteArray()));

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.

In TVM , we could reuse ECKey.ECDSASignature.fromComponents(r, s, v)method,which is already used by ecrecover() to recover address for signature.

Energy cost

energy charge for the execution cost 1500 per signature

Rationale

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.

Backwards Compatibility

Adding a new precompiledContract cause no backwards compatibility concerns.

Test Cases

1.Verifying both correct and incorrect signatures in smart contract.
2.Verifying duplicate signatures.
3.Verifying more than 5 signatures.

TRC: TRC10 Precision issue

Tokens originally created on the Tron Blockchain, prior to the approval of the proposal "allow the TRC-10 token transfer in smart contracts" were not able to set a "precision" value. As such all of tokens created are set to a default precision value of 0. We recommend allowing tokens from prior to this period the opportunity to set their precision value.

TRC92: To reduce the probability of producing empty blocks

tip: 92
title: To reduce the probability of producing empty blocks
author: yrp <[email protected]>
discussions to: https://github.com/tronprotocol/TIPs/issues/92
category: TRC
status: Draft
created: 2019-10-17

Simple Summary

This document describes a mechanism aiming at reducing the empty blocks producing rate on TRON’s public chain. It is a supplement to TIP #53 .

Abstract

An empty block refers to a block with no transaction inside. At a special circumstance, if there are only few transactions in the network to deal with, producing empty blocks is normal. For SRs, producing empty blocks appears for two reasons: firstly, SRs cut costs by lowering resource consumption for running machines on their nodes; secondly, they are less likely to miss blocks due to faster synchronization with other nodes, which is guaranteed by shorter block generation time and smaller binary data size. SRs receive full block rewards no matter how many transactions they pack into the block, even if there is nothing inside. To the public chain network, however, empty blocks are detrimental. They waste public chain resources, increase transaction-blocking risks and compromise network performance, posing a threat to the rights of TRX holders and other SRs who produce normal blocks. Therefore, a mechanism is needed to prevent producing empty blocks deliberately.

Motivation

The motivation is to reduce the empty block producing rate and minimize transaction-blocking risks so as to improve the operational efficiency of the public chain and uphold TRX holders’ rights and interests.

Specification

Empty block: an empty block refers to a block with no transaction inside. At a special circumstance, if there are only few transactions in the network to deal with, producing empty blocks is normal. The empty block we discuss here is the block that SRs subjectively produced deliberately.

Rationale

Currently there is no effective solution to empty blocks on the public chain. We won’t tend to adopt punitive measures on nodes that generate empty blocks, which are clearly negative. Instead, we will give out incentives to SRs who have done a good job in block producing. To that end, we have come up with a mechanism that scores and rewards SR’s contributions accordingly.

Implementation

Specifically, we will draw 10% of each block reward, namely 176 * 10% = 17.60 TRX, into a bonus pool. The remaining 90%, namely 176 * 90% = 158.40 TRX, will go straightly to nodes instantly after they produce blocks. For one maintenance period (the six-hour block generation period), there will be 17.60 TRX * (6 * 60 * 60 / 3) = 126,720 TRX in the bonus pool.

For each maintenance period (the six-hour block generation period), we will rank SRs by several metrics including Bandwidth and Energy (r = m * Energy + n * Bandwidth) and distribute bonus according to their ranks. The table below shows the bonus reward each rank is entitled to.

Ranking Percentage of Bonus pool(%) Reward(TRX)
1 5 6336
2 5 6336
3 5 6336
4 5 6336
5 4 5068.8
6 4 5068.8
7 4 5068.8
8 4 5068.8
9 4 5068.8
10 4 5068.8
11 4 5068.8
12 4 5068.8
13 3.2 4055.04
14 3.2 4055.04
15 3.2 4055.04
16 3.2 4055.04
17 3.2 4055.04
18 3.2 4055.04
19 3.2 4055.04
20 3.2 4055.04
21 3.2 4055.04
22 3.2 4055.04
23 3.2 4055.04
24 3.2 4055.04
25 3.2 4055.04
26 3.2 4055.04
27 3.2 4055.04

In theory, the more transactions are packed in a block, the more energy is consumed, and so is the overall energy consumed at each maintenance period. In return, node that generates a block in each round ranks higher on the list if more energy is consumed. Another point worth mentioning is that it takes longer to pack more transactions in a block, and for other nodes, to receive and process the associated block, therefore increasing the chances of missing the block. 
 

Discussion

  • How much from each block reward should we transfer into the bonus pool?
  • How to rank SRs fairly to share the bonus pool? This proposal is just one of the many options we may have. Discussion is welcome on other possible solutions that contribute to the long-term health of the TRON ecosystem.  
  • Who should be eligible for the bonus? All SRs or only those who make great contributions?
  • What are some better mechanisms to prevent producing empty blocks except rewards and punishments?

TRC102: Hierarchical Deterministic Wallets

TIP: 102
Title: Hierarchical Deterministic Wallets
Author: federico<[email protected]>
discussions-to: https://github.com/tronprotocol/tips/issues/102
status: draft
type: Standards Track
category: TRC
Created: 2019-10-22

Simple Summary

This proposal defines a mechanism for extending hierarchical deterministic wallets, as described in BIP32
and BIP44, to support both Tron's transparent and shielded addresses.

Abstract

BIP32 and BIP44 are the standard mechanism by which wallets for Bitcoin and its derivatives generate keys and addresses deterministically.
However, they only support the transparent address generation. This specification will provide support for the hierarchically shielded addresses derivation in a similar way as BIP32, which can offer users better privacy protection.

Motivation

At present, Tron network has scheduled to support the shielded addresses by ZK-SNARKs, so it is necessary to provide the standard compatibility for shielded hierarchical deterministic wallets.

Specification

In this specification, transparent address indicates the address which is public in the transaction, while the shielded address stands for the address which
is not available from the transaction.

Wallet Key Path

Existing HD wallets all use BIP44 to organize their derived keys. In order to
improve existing user experiences, we broadly follow BIP 44's design here. However, we have
altered the design where it makes sense to leverage features of shielded addresses.

m / purpose' / coin_type' / account' / transparent' / change / address_index

Apostrophe in the path indicates that BIP32 hardened derivation is used.

  • m: a seed generated by the mnemonic codes to generate the master key.

  • purpose: a constant set to 102' (or 0x80000066) following the BIP43 recommendation. It indicates that
    the subtree of this node is used according to this specification.

  • coin_type: a constant identifying the cybercoin that this subtree's keys are used with. For Tron, coin_type is 195 as assigned in SLIP44.

  • account: numbered from index 0 in sequentially increasing manner. Defined as in BIP44.

  • transparent: for transparent addresses, transparent is set 1; for the shielded addresses, transparent is set 0;

  • change: for transparent addresses, constant 0 is used for external chain and constant 1 for internal chain (also known as change addresses) as in BIP44;
    for shielded addresses, change field is omitted, because shielded addresses are never publicly visible in transactions.

  • address_index: numbered from index 0 in sequentially increasing manner. Defined as in BIP44.

Mnemonic Codes

BIP39 should be used to derive binary seed from a mnemonic code.

We strongly recommend using 24 word mnemonic (256 bits of entropy).

Transparent Multi-Account Hierarchy for Deterministic Wallets

We adapt BIP44 for generating transparent address, except an extra transparent field is added. This is an upgrade of TIP001. We will focus on the shielded addresses derivation in the following section.

Hierarchical Derivation for Shielded Addresses

The shielded addresses derivation process described here are mainly based on the ZIP32 standard proposed by Zcash team.

Conventions

Most of the notation and functions used in this TIP are defined here for convenience:

  • truncatek(S) means the sequence formed from the first k elements of S.

  • a || b means the concatenation of sequences a then b.

  • [k] P means scalar multiplication of the elliptic curve point P by the scalar k.

  • LEOS2IPl (S) is the integer in range {0..2l -1} represented in little-endian order
    by the byte sequence S of length l/8.

  • I2LEBSPl (k) is the sequence of l bits representing k in little-endian order.

  • LEBS2OSPl (B) is defined as follows when l is a multiple of 8: convert each group of 8 bits
    in B to a byte value with the least significant bit first, and concatenate the resulting bytes in the
    same order as the groups.

  • reprJ (P) is the representation of the Jubjub elliptic curve point P as a bit sequence.

  • BLAKE2b-256(p, x) refers to unkeyed BLAKE2b-256 in sequential mode, with an output digest length of
    32 bytes, 16-byte personalization string p, and input x.

  • BLAKE2b-512(p, x) refers to unkeyed BLAKE2b-512 in sequential mode, with an output digest length of
    64 bytes, 16-byte personalization string p, and input x.

  • PRFexpand (sk, t) := BLAKE2b-512("Tron_ExpandSeed", sk || t )

  • ToScalar(x) := LEOS2IP512 (x) (mod rJ ), where rJ is the order
    of the Jubjub large prime subgroup.

  • DiversifyHash(d) maps a diversifier d to a base point on the Jubjub elliptic curve, or to ⊥ if the
    diversifier is invalid.

The following FPE algorithm standardized is used:

  • FF1-AES256.Encrypt(key, tweak, x) refers to the FF1 encryption algorithm using AES with a
    256-bit key, and parameters radix = 2, minlen = 88, maxlen = 88. It will be used only with
    the empty string "" as the tweak. x is a sequence of 88 bits, as is the output.

We also define the following conversion function:

  • I2LEOSPl (k) is the byte sequence S of length l/8 representing in little-endian order the
    integer k in range {0..2l -1}. It is the reverse operation of LEOS2IPl (S).

We adapt the path notation of BIP32 to describe shielded HD paths, using apostrophes to
indicate hardened derivation (i' = i + 231 ) as in BIP44:

  • CDKsk(CDKsk(CDKsk(m, a'), b), c) is written as m / a' / b / c
  • CDKfvk(CDKfvk(CDKfvk(M, a), b), c) is written as M / a / b / c

Specification: Key Derivation

Extended Keys

BIP 32 defines a method to derive a number of child keys from a parent key. In order to prevent these from
depending solely on the parent key itself, both the private and public keys are extended with a 32-byte chain
code. We similarly extend Sapling keys with a chain code here. However, the concepts of "private" and "public"
keys in BIP 32 do not map cleanly to shielded key components. We take the following approach:

  • We derive child expanded spending keys, rather than spending keys. This enables us to
    implement both hardened and non-hardened derivation modes.

  • We do not derive public keys directly, as this would prevent the use of diversified addresses.
    Instead, we derive full viewing keys, from which payment addresses can be generated. This maintains
    the trust semantics of BIP 32: someone with access to a BIP 32 extended public key is able to view all
    transactions involving that address, which a full viewing key also enables.

We represent a extended spending key as (ask, nsk, ovk, dk, c), where (ask, nsk, ovk)
is the normal expanded spending key, dk is a diversifier key, and c is the chain code.

We represent a extended full viewing key as (ak, nk, ovk, dk, c), where (ak, nk, ovk)
is the normal full viewing key, dk is the same diversifier key as above, and c is the chain code.

The helper functions

Define EncodeExtSKParts(ask, nsk, ovk, dk) := I2LEOSP256 (ask) || I2LEOSP256 (nsk) || ovk || dk.

Define EncodeExtFVKParts(ak, nk, ovk, dk) := LEBS2OSP256 (reprJ (ak)) || LEBS2OSP256 (reprJ (nk)) || ovk || dk.

Master Key Generation

Let pathi= m / xx' / 195' / i' / 0', i denotes the i-th account. Let skpathi, pkpathi, cpathi
denotes the private key, public key and chain code at pathi derived by BIP32.

  • Calculate I = BLAKE2b-512 ("TronIP102", skpathi || pkpathi || cpathi ).

  • Split I into two 32-byte sequences, IL and IR .

  • Use IL as the master spending key skm , and IR as the master chain code
    cm.

  • Calculate askm , nskm , and ovkm via the standard derivation function:

    • askm = ToScalar(PRFexpand (skm , [0x00]))
    • nskm = ToScalar(PRFexpand (skm , [0x01]))
    • ovkm = truncate32 (PRFexpand (skm , [0x02]))
  • Calculate dkm similarly:

    • dkm = truncate32 (PRFexpand (skm , [0x10]))
  • Return (askm , nskm , ovkm , dkm , cm ) as the
    master extended spending key m.

Child Key Derivation

As in BIP 32, the method for deriving a child extended key, given a parent extended key and an index i,
depends on the type of key being derived, and whether this is a hardened or non-hardened derivation.

Deriving a child extended spending key

CDKsk((askpar , nskpar , ovkpar , dkpar , cpar ), i) →
(aski , nski , ovki , dki , ci )

  • Check whether i ≥ 231 (whether the child is a hardened key).

    • If so (hardened child): let I = PRFexpand (cpar , [0x11] || EncodeExtSKParts(askpar , nskpar , ovkpar , dkpar ) || I2LEOSP32 (i))
    • If not (normal child): let I = PRFexpand (cpar , [0x12] || EncodeExtFVKParts(akpar , nkpar , ovkpar , dkpar ) || I2LEOSP32 (i))
      where (nkpar , akpar , ovkpar ) is the full viewing key derived from
      (askpar , nskpar , ovkpar ).
  • Split I into two 32-byte sequences, IL and IR .

  • Let Iask = ToScalar(PRFexpand (IL , [0x13]))

  • Let Insk = ToScalar(PRFexpand (IL , [0x14]))

  • Return:

    • aski = Iask + askpar
    • nski = Insk + nskpar
    • ovki = truncate32 (PRFexpand (IL , [0x15] || ovkpar ))
    • dki = truncate32 (PRFexpand (IL , [0x16] || dkpar ))
    • ci = IR

Deriving a child extended full viewing key

Let G and H be the base point in elliptic curve.

CDKfvk((akpar , nkpar , ovkpar , dkpar , cpar ), i) →
(aki , nki , ovki , dki , ci )

  • Check whether i ≥ 231 (whether the child is a hardened key).

    • If so (hardened child): return failure
    • If not (normal child): let I = PRFexpand (cpar , [0x12] || EncodeExtFVKParts(akpar , nkpar , ovkpar , dkpar ) || I2LEOSP32 (i))
  • Split I into two 32-byte sequences, IL and IR .

  • Let Iask = ToScalar(PRFexpand (IL , [0x13]))

  • Let Insk = ToScalar(PRFexpand (IL , [0x14]))

  • Return:

    • aki = [Iask] G + akpar
    • nki = [Insk] H + nkpar
    • ovki = truncate32 (PRFexpand (IL , [0x15] || ovkpar ))
    • dki = truncate32 (PRFexpand (IL , [0x16] || dkpar ))
    • ci = IR

Diversifier derivation

The 88-bit diversifiers for a extended key are derived from its diversifier key dk. To prevent the
diversifier leaking how many diversified addresses have already been generated for an account, we make the
sequence of diversifiers pseudorandom and uncorrelated to that of any other account. In order to reach the
maximum possible diversifier range without running into repetitions due to the birthday bound, we use
FF1-AES256 as a Pseudo-Random Permutation as follows:

  • Let j be the index of the desired diversifier, in the range 0 .. 288 -1.
  • dj = FF1-AES256.Encrypt(dk, "", I2LEBSP88 (j)).

A valid diversifier dj is one for which DiversifyHash(dj) ≠ ⊥.
For a given dk, approximately half of the possible values of j yield valid diversifiers.

The default diversifier for an extended key is defined to be dj , where j is the
least nonnegative integer yielding a valid diversifier.

Fingerprints and Tags

Full Viewing Key Fingerprints and Tags

A full viewing key fingerprint with raw encoding FVK is given by:

BLAKE2b-256("TronFVFP", FVK)

It MAY be used to uniquely identify a particular full viewing key.

A "full viewing key tag" is the first 4 bytes of the corresponding full viewing key
fingerprint. It is intended for optimizing performance of key lookups, and MUST NOT be assumed to
uniquely identify a particular key.

Key Encodings

The following encodings are analogous to the xprv and xpub encodings defined
in BIP 32 for transparent keys and addresses. Each key type has a raw representation
and a Bech32 encoding.

Extended Spending Keys

An extended spending key (ask, nsk, ovk, dk, c), at some path,
with parent full viewing key tag parent_fvk_tag and child number i, is
represented as a byte sequence:

I2LEOSP8 (depth) || parent_fvk_tag || I2LEOSP32 (i) || c || EncodeExtSKParts(ask, nsk, ovk, dk)

For the master extended spending key, depth is 0, parent_fvk_tag is 4 zero bytes,
and i is 0.

When encoded as Bech32, the Human-Readable Part is secret-extended-key-main
for the production network, or secret-extended-key-test for the test network.

Extended full viewing keys

A extended full viewing key (ak, nk, ovk, dk, c), at depth depth,
with parent full viewing key tag parent_fvk_tag and child number i, is
represented as a byte sequence:

I2LEOSP8 (depth) || parent_fvk_tag || I2LEOSP32 (i) || c || EncodeExtFVKParts(ak, nk, ovk, dk)

For the master extended full viewing key, depth is 0, parent_fvk_tag is 4 zero bytes,
and i is 0.

When encoded as Bech32, the Human-Readable Part is txviews for the production
network, or txviewtest for the test network.

Rationale

Based on BIP32, BIP44 and ZIP32, We provide a standard mechanism for both transparent and shielded hierarchical deterministic wallets for Tron.

Implementation

None

Reference

TRC: Built-in message queue for event subscribe

tip: 28
title: TRC-28 Built-in message queue for event subscribe
author: jiangyy [email protected]
discussions to: #28
status: accepted
type: Standards Track
category: TRC
created: 2019-03-14

Simple Summary
Adding built-in message queue for event subscribe in java-tron.

Abstract
The built-in message queue is designed for event subscribe. Developers could subscribe triggers directly from fullnode without event plugin.

Motivation
Developers could use event plugins to subscribe triggers from fullnode, which provide very reliable service and store very large amount of data.

But in some cases, developers want to subscribe directly from fullnode, with short-term subscriptions. Native message queue is implemented to meet such requirement.

Specification
The function of native queue is configurable. It's is disabled by default. It shared the configuration of triggers with eventplugin.

The communication channel between fullnode and subscription client is socket. The bindport could be configurable to avoid conflicting.

event.subscribe = {
native = {
useNativeQueue = true // if true, use native message queue, else use event plugin.
bindport = 5555 // bind port
sendqueuelength = 1000 //max length of send queue
}
......
}

Developers should subscribe triggers very conveniently. What they need to do is: connecting to the port, subscribing the topics, then receivingthe triggers.

TRC: Adaptive Energy Limit Model

tip: 17
title: Adaptive Energy Limit Model
author: nanfengpo <[email protected]> 
discussions to: https://github.com/tronprotocol/TIPs/issues/17
status: Draft
type: Standards Track
category: TRC
created: 2018-12-29

Simple Summary

This doc describes the standard interface of Adaptive Energy Limit Model

Abstract

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.

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 Enegy limit for that account is 32400 Energy.

However, if some accounts freeze TRX and have the corresponding energy, but do not use it, energy resources will be wasted. To this end, 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,

  • when energy consumption is low, increase the energy limit so that each account can get more energy
  • when energy consumption is high, lower the energy ceiling so that each account has less energy

Motivation

  1. Avoid waste of energy resources;
  2. Each account has more energy resources;

Implementation

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 wave field network, there are the following measures:

  • Real Energy Limit: An upper limit on the real capacity of the TRON network within 24 hours. The current value is $100 billion. Only the committee can change this value.
  • 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
  • Target Energy Limit: The target upper limit of Energy consumed in one minute (equal to 10% * 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. [will change as the RealEnergyLimit changes]
  • Average energy usage over the past minute: changes per block

Adjustment strategy:
The width of the sliding window is 1 minute. Calculate the average Energy usage in a window:

  • 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 1000 times the Real Energy Limit
  • 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

For example, the initial Virtual Energy Limit is 500_000_000_000L and the target ceiling is 500_000_000L.
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

TRC: Event subscribe to support contract without ABI

tip: 34
title: TRC-34 Event subscribe to support contract without ABI
author: wubin1<[email protected]> 
discussions to: https://github.com/tronprotocol/TIPs/issues/34
category: TRC
status: accepted
created: 2019-4-19

Abstract

To support contract without ABI, contract log parsing is separated from java-tron main program.
Moreover, developers could upload self ABI string to parse contract log and contract event, which could be more convenient to support some contracts without ABI.

Motivation

The contract does not need ABI anymore after the introduction of triggerConstantContract api, so tron-eventquery service could support developers to upload ABI and parse contract log and contract event.

Specification

In order to support contract without ABI, contract log parsing is separated from java-tron main program and we parse contract log in event plugin.
In addition, the function of parse contract log is configurable. It's is true by default.

event.subscribe = {
contractParse = true,
......

If it is false, we only pass the raw data to developers who subscribe events.

Moreover, event query service adds three new http api for supporting developers to developers parse contract log and contract event by self upload ABI string.

Developers could subscribe triggers more conveniently.

Backwards Compatibility

There are no backwards compatibility concerns.

Test Cases

  1. Emitting events from contract that without ABI.
  2. Emitting events from contract that with ABI.

shielded transaction

Contents

  1. Overview

  2. Notation

  3. Cryptographic Primitives
    3.1. Encoding rules
    3.2. Constants
    3.3. Hash Functions
    3.3.1. BLAKE2 Hash Function
    3.3.2. CRHivk Hash Function
    3.3.3. DiversifyHash Function
    3.3.4. Pedersen Hash Function
    3.3.5. Mixing Pedersen Hash Function
    3.4. Pseudo Random Function
    3.5. Authenticated One-Time Symmetric Encryption
    3.6. Key Agreement and Derivation
    3.7. Jubjub and RedJubjub
    3.7.1. Spend Authorization Signature
    3.7.2. Binding Signature
    3.8. Group Hash into Jubjub
    3.9. Commitment Schemes
    3.9.1. Note Commitments
    3.9.2. Value Commitments

  4.  Concepts        
    

4.1. Payment Addresses and Keys
4.2. Notes
4.3. Transactions and Treestates
4.4. Spend Descriptions and Output Descriptions
4.5. Nullifier Sets

  1.  zk-SNARK        
    

5.1. Zero-Knowledge Proof Model
5.2. Construct zk-SNARK
5.2.1. Generate Arithmetic Circuit
5.2.2. R1CS
5.2.3. QAP

  1.  Shielded Transaction    
    

6.1. Setup
6.2. Wallet
6.2.1. Create Payment Address
6.2.2. Scan Blockchain
6.2.3. Create Spend Proof
6.2.4. Signature with Re-randomizable Keys
6.2.5. Create Output Proof
6.2.6. Binding Signature
6.2.7. Note Encryption
6.2.8. Note Decryption
6.2.8.1. Note Decryption with ivk
6.2.8.2. Note Decryption with ovk
6.2.9. Broadcast Transaction
6.3. Block chain
6.3.1. Verify Transaction
6.3.1.1. Verify Spend Authority Signature
6.3.1.2. Verify Spend Proof
6.3.1.3. Verify Output Proof
6.3.1.4. Verify Binding Signature
6.3.1.5. Verify Nullifier
6.3.1.6. Verify others
6.3.2. Execute Transaction
6.3.2.1. Save Transaction
6.3.2.2. Save CM, Update Tree
6.3.2.3. Save Nullifier
6.4. Contract
6.4.1. User APIs
6.4.2. Shielded Transfer Contract

TRC: Trigger constant contract

tip: 31
title: TRC-31 Trigger constant contract
author: llwslc<[email protected]> 
discussions to: https://github.com/tronprotocol/TIPs/issues/31
category: TRC
status: in process
created: 2019-4-3

Abstract

This TIP specifies a new api, which triggers the constant contract without ABI.

Motivation

Many developers hope not upload the ABI, and trigger the contract by their judgment.

Specification

A new api, triggerConstantContract, is introduced.

// api.proto
rpc TriggerConstantContract (TriggerSmartContract) returns (TransactionExtention) {}

The triggerConstantContract parameters are the same as the triggerContract.

triggerConstantContract contract_address method args isHex

Http interface example:

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"}'

In case the type of method is not constant will gets error.

Backwards Compatibility

There are no backwards compatibility concerns.

Test Cases

  1. Trigger the constant method by triggerConstantContract.
  2. Trigger the non-constant method by triggerConstantContract.

TRC: Create2

Simple Summary

A new contract creation function called CREATE2

Abstract

A new method of creating a contract is proposed where the resulting address can be determined by parties ahead of time.

Motivation

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.

Specification

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

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 Create is deducted: before evaluation of the resulting address and the execution of init_code.

  • address is always 21 bytes,
  • salt is always 32 bytes (a stack item).
  • keccak256(init_code) 32 bytes

The preimage for the final hashing round is thus always exactly 85 bytes long.

Rationale

Address formula

  • Because instruction CREATE mainly depends on trxHash, the CREATE2 addresses will not collide with CREATE addresses.
    • Deploy contract: addressPrefix ++ keccak256(trxHash ++ txOwnerAddress)[12:]
    • in internal transaction: addressPrefix ++ keccak256(trxHash ++ nonce)[12:]
  • Ensures that the hash preimage has a fixed size,

Engery cost

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.

TRC: Reduce block confirm time with PBFT

tip: 39
title: TRC-39 Reduce block confirm time with PBFT
author: [email protected], jiangyy<[email protected]> 
discussions to: https://github.com/tronprotocol/TIPs/issues/39
status: draft
type: Standards Track
category: TRC
created: 2019-5-17

Simple Summary

This doc describes the PBFT solution to reduce block confirm time.

Abstract

In current consensus model, block need to be confirmed by 2/3 SR nodes. In that case, there is a gap of 18 blocks between the main-network's chain height and consensus height, and it takes about 1 minutes for the solidification/confirmation. With PBFT, the confirmation time could be reduced to seconds level.

It could also help improving the TPS on main-net, and providing technical support for Cross-Chain.

Motivation

Support more business scenarios and provide better user experience.

Specification

The reason of the block gap is TRON's consensus algorithm. For example, SR0 produces a new block BLK0, other SR nodes need to wait until their schedule to confirm BLK0. Other SR nodes verify BLK0 one after another according to the block produce schedule. After more than 2/3 of SR confirm the block, the block is Irreversible. The transaction confirm time is: 27 * 2/3 *3 = 54 seconds.

To reach a real-time consensus speed, the block currently being produced should be confirmed by other SR nodes immediately. PBFT needs to be integrated.

Challenges

  1. Network overhead, additional PBFT messages are needed.
  2. Compatibility with current consensus model DPOS.
  3. Security issues.

Optimization of PBFT

1.Combined with Dpos, the pbft algorithm is used to implement block consensus.
2.Remove view changes and data requests
3.Sr node's block productivity will not be influenced.
4.The fullnode node is free to choose the number of consensus(confirmed) SR nodes.

Algorithm

1.Each SR node will only sign a block of a specific height once.
2.A block will be treated as a timeout if it is not confirmed by more than 2/3 SR nodes.
3.The fullNode node can fix the current block by setting a commit message that receives 27 SR signatures to achieve security and reliability, except two consecutive SR node is cheating together.

Proto

message PbftMessage {
enum Type {
VIEW_CHANGE = 0;
REQUEST = 1;
PREPREPARE = 2;
PREPARE = 3;
COMMIT = 4;
}
message Raw {
Type pbftMsgType = 1;
int64 blockNum = 2;
int64 time = 3;
bytes publicKey = 4;
bytes data = 5;
}
Raw raw_data = 1;
bytes sign = 2;
}

TRC: Implement solidity fallback function logic in transfer transaction

Simple Summary

Trigger fallback function for a smart contract, when we transfer trx to it.

Abstract

Fallback Function (from Ethereum)

A contract can have exactly one unnamed function. This function cannot have arguments, cannot return anything and has to have external visibility. It is executed on a call to the contract if none of the other functions match the given function identifier (or if no data was supplied at all).
Furthermore, this function is executed whenever the contract receives plain Ether (without data). Additionally, in order to receive Ether, the fallback function must be marked payable. If no such function exists, the contract cannot receive Ether through regular transactions.
It does not trigger a fallback function for the smart contract,When we transfer trx to a smart contract on tron mainet. And we are allowed to use transferContract sending trx to a smart contract account even with a non-payable type fallback function in it.

Motivation

For some specific contracts, such as ICO, developers would like to record msg.sender, msg.value information in it. Fallback function would be a proper way to record all these data. And it would also be a convenient way for contract to handle different logic related to trx transferring.

Specification

A normal transfer can trigger a fallback function for a smart contract.

Proposal to remove plaintext inclusion of private key in virtual machine on which node is running

In this command that we have to send (which includes the private key) in plain text in setting up the java full node,

  1. is it possible to avoid having to send this private key at all or keep it on this virtual machine on which the node is running?
  2. if it is absolutely necessary to provide this key, is there a way to allow this command to work with the key held in some sort of encrypted file on this machine rather than in plain next?

Would be best to avoid private key being mentionedi n plaintext anywhere.

about DUP_TRANSACTION_ERROR error

问题现象:
1、创建一个转账交易,A转B,1trx
2、用C的私钥,对结果签名
3、调用广播交易接口(grpc),得到错误:SIGERROR
4、重复3的步骤,再次发送,得到错误:DUP_TRANSACTION_ERROR

官方微信开发群的解释是:交易第一次广播到节点A,节点A会先缓存起来(可能没上链),交易再次广播到节点A,就会报重复交易

问题:
当重复步骤3的时候,得到的DUP_TRANSACTION_ERROR错误,不再是这个交易原本的错误,即原始错误已经丢失了

希望的结果:
无论重复多少次步骤3,得到的结果应该还是原始错误SIGERROR

注:不止SIGERROR,很多错误,重复发送之后都会得到DUP_TRANSACTION_ERROR

TRC-44: Address.isContract instruction

tip: 44
title: TRC-44 Address.isContract instructions
author: llwslc<[email protected]> 
discussions to: https://github.com/tronprotocol/TIPs/issues/43
category: TRC
status: accept
created: 2019-07-10

Simple Summary

To provide a new opcode, which returns the type of the address.

Abstract

This TIP specifies a new opcode, which determines whether the address type is a contract address.

Motivation

Some contracts need to limit its callers, such as some functions can only be called by the user, not by the contract.

Specification

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.

In case the address does not exist false is pushed to the stack.

example:

contract Test {
    function checkAddr(address addr) view public returns (bool) {
        return addr.isContract;
    }
}

The energy cost of the ISCONTRACT is 400.

Backwards Compatibility

There are no backwards compatibility concerns.

Test Cases

  1. The ISCONTRACT of a contract address is true.
  2. The ISCONTRACT of an account address is false.
  3. The ISCONTRACT of a non-existent address is false.
  4. The ISCONTRACT of a precompiled contract is false.
  5. The ISCONTRACT of self address in constructor function is true.
  6. The ISCONTRACT of a selfdestructed contract address is false.

TRC: Clear the ABI of contract

tip: 32
title: TRC-32 Clear the ABI of contract
author: llwslc<[email protected]> 
discussions to: https://github.com/tronprotocol/TIPs/issues/32
category: TRC
status: in process
created: 2019-4-3

Abstract

This TIP specifies a new api, which clears the ABI of contract.

Motivation

The contract does not need ABI anymore after the introduction of triggerConstantContract api.

Specification

A new api, clearContractABI, is introduced.

// api.proto
rpc ClearContractABI (ClearABIContract) returns (TransactionExtention) {}

// Contract.proto
message ClearABIContract {
  bytes owner_address = 1;
  bytes contract_address = 2;
}

// Tron.proto
ClearABIContract = 47;

The clearContractABI parameters are shown as follows:

clearContractABI contract_address

Http interface example:
Step 1. Call api: wallet/clearabi to build the transaction

curl -X POST  http://127.0.0.1:8090/wallet/clearabi -d '{"owner_address": "415A523B449890854C8FC460AB602DF9F31FE4293F","contract_address": "416162AFF58D27A5FBD15B2F8F7EF752B2F4256086"}'

Return:

{"visible":false,"txID":"b33337e74de5ca8f6155003b588ae8a4d6580432d41a86d9086a244fb2960ab2","raw_data":{"contract":[{"parameter":{"value":{"owner_address":"415a523b449890854c8fc460ab602df9f31fe4293f","contract_address":"416162aff58d27a5fbd15b2f8f7ef752b2f4256086"},"type_url":"type.googleapis.com/protocol.ClearABIContract"},"type":"ClearABIContract"}],"ref_block_bytes":"0c19","ref_block_hash":"4b4f1264c3f9d924","expiration":1558685682000,"timestamp":1558685622423},"raw_data_hex":"0a020c1922084b4f1264c3f9d92440d092a0c7ae2d5a630830125f0a2d747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e436c656172414249436f6e7472616374122e0a15415a523b449890854c8fc460ab602df9f31fe4293f1215416162aff58d27a5fbd15b2f8f7ef752b2f42560867097c19cc7ae2d"}

Step 2. Call api: wallet/gettransactionsign to sign (use the private key of the transparent address)

curl -X POST  http://127.0.0.1:8090/wallet/gettransactionsign -d '{"privateKey":"","transaction":{"visible":false,"txID":"b33337e74de5ca8f6155003b588ae8a4d6580432d41a86d9086a244fb2960ab2","raw_data":{"contract":[{"parameter":{"value":{"owner_address":"415a523b449890854c8fc460ab602df9f31fe4293f","contract_address":"416162aff58d27a5fbd15b2f8f7ef752b2f4256086"},"type_url":"type.googleapis.com/protocol.ClearABIContract"},"type":"ClearABIContract"}],"ref_block_bytes":"0c19","ref_block_hash":"4b4f1264c3f9d924","expiration":1558685682000,"timestamp":1558685622423},"raw_data_hex":"0a020c1922084b4f1264c3f9d92440d092a0c7ae2d5a630830125f0a2d747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e436c656172414249436f6e7472616374122e0a15415a523b449890854c8fc460ab602df9f31fe4293f1215416162aff58d27a5fbd15b2f8f7ef752b2f42560867097c19cc7ae2d"}}'

Return:

{"visible":false,"signature":["0e7e750226f01096f2f4aa0c2d03ad17d7ff57277ac3b655ecd692e3d9bd9bb822426dc779f046d79eedf23bb2534f8fa2c2fab8e48900e66d61af6f3262546c01"],"txID":"b33337e74de5ca8f6155003b588ae8a4d6580432d41a86d9086a244fb2960ab2","raw_data":{"contract":[{"parameter":{"value":{"owner_address":"415a523b449890854c8fc460ab602df9f31fe4293f","contract_address":"416162aff58d27a5fbd15b2f8f7ef752b2f4256086"},"type_url":"type.googleapis.com/protocol.ClearABIContract"},"type":"ClearABIContract"}],"ref_block_bytes":"0c19","ref_block_hash":"4b4f1264c3f9d924","expiration":1558685682000,"timestamp":1558685622423},"raw_data_hex":"0a020c1922084b4f1264c3f9d92440d092a0c7ae2d5a630830125f0a2d747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e436c656172414249436f6e7472616374122e0a15415a523b449890854c8fc460ab602df9f31fe4293f1215416162aff58d27a5fbd15b2f8f7ef752b2f42560867097c19cc7ae2d"}

Step 3. Call api: wallet/broadcasttransaction to broadcast the transaction

curl -X POST  http://127.0.0.1:8090/wallet/broadcasttransaction -d '{"signature":["0e7e750226f01096f2f4aa0c2d03ad17d7ff57277ac3b655ecd692e3d9bd9bb822426dc779f046d79eedf23bb2534f8fa2c2fab8e48900e66d61af6f3262546c01"],"txID":"b33337e74de5ca8f6155003b588ae8a4d6580432d41a86d9086a244fb2960ab2","raw_data":{"contract":[{"parameter":{"value":{"owner_address":"415a523b449890854c8fc460ab602df9f31fe4293f","contract_address":"416162aff58d27a5fbd15b2f8f7ef752b2f4256086"},"type_url":"type.googleapis.com/protocol.ClearABIContract"},"type":"ClearABIContract"}],"ref_block_bytes":"0c19","ref_block_hash":"4b4f1264c3f9d924","expiration":1558685682000,"timestamp":1558685622423},"raw_data_hex":"0a020c1922084b4f1264c3f9d92440d092a0c7ae2d5a630830125f0a2d747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e436c656172414249436f6e7472616374122e0a15415a523b449890854c8fc460ab602df9f31fe4293f1215416162aff58d27a5fbd15b2f8f7ef752b2f42560867097c19cc7ae2d"}'

Return:

{"result": true}

The clearContractABI can clear the ABI of contract at the address if the account is the owner of the contract.

In case the account is not the owner of contract will throw an exception.

Backwards Compatibility

triggerContract a function will push transactions on Blockchain after clear the ABI of contract.
See TriggerConstantContract for a more detailed discussion.

Test Cases

  1. The clearContractABI caller is the owner of contract will clear the ABI of contract at the address.
  2. The clearContractABI caller is not the owner of contract will throw an exception.
  3. The clearContractABI of non-existent address will throw an exception.

TRC:Bitwise shifting instructions


tip: 29
title: Bitwise shifting instructions in Tron
author: @ithinker1991
type: Standards Track
discussions to: #29
category: TRC
status: in process
created: 2019-03-07


Simple Summary

To provide native bitwise shifting with cost on par with other arithmetic operations. Just like EIP145 in Ethereum

Abstract

Native bitwise shifting instructions are introduced, which are more efficient processing wise on the host and are cheaper to use by a contract.

Motivation

TVM is lacking bitwise shifting operators, but supports other logical and arithmetic operators. Shift operations can be implemented via arithmetic operators, but that has a higher cost and requires more processing time from the host. Implementing SHL and SHR using arithmetics cost each 35 engine, while the proposed instructions take 3 engine.

Specification

The following instructions are introduced:

0x1b: SHL (shift left)

The SHL instruction (shift left) pops 2 values from the stack, first arg1 and then arg2, and pushes on the stack arg2 shifted to the left by arg1 number of bits. The result is equal to

(arg2 * 2^arg1) mod 2^256

Notes:

  • The value (arg2) is interpreted as an unsigned number.
  • The shift amount (arg1) is interpreted as an unsigned number.
  • If the shift amount (arg1) is greater or equal 256 the result is 0.
  • This is equivalent to PUSH1 2 EXP MUL.

0x1c: SHR (logical shift right)

The SHR instruction (logical shift right) pops 2 values from the stack, first arg1 and then arg2, and pushes on the stack arg2 shifted to the right by arg1 number of bits with zero fill. The result is equal to

floor(arg2 / 2^arg1)

Notes:

  • The value (arg2) is interpreted as an unsigned number.
  • The shift amount (arg1) is interpreted as an unsigned number.
  • If the shift amount (arg1) is greater or equal 256 the result is 0.
  • This is equivalent to PUSH1 2 EXP DIV.

0x1d: SAR (arithmetic shift right)

The SAR instruction (arithmetic shift right) pops 2 values from the stack, first arg1 and then arg2, and pushes on the stack arg2 shifted to the right by arg1 number of bits with sign extension. The result is equal to

floor(arg2 / 2^arg1)

Notes:

  • The value (arg2) is interpreted as a signed number.
  • The shift amount (arg1) is interpreted as an unsigned number.
  • If the shift amount (arg1) is greater or equal 256 the result is 0 if arg2 is non-negative or -1 if arg2 is negative.
  • This is not equivalent to PUSH1 2 EXP SDIV, since it rounds differently. See SDIV(-1, 2) == 0, while SAR(-1, 1) == -1.

The cost of the shift instructions is set at verylow tier (3 engine).

Rationale

Instruction operands were chosen to fit the more natural use case of shifting a value already on the stack. This means the operand order is swapped compared to most arithmetic insturctions.

Backwards Compatibility

The newly introduced instructions have no effect on bytecode created in the past.

Test Cases

SHL (shift left)

  1. PUSH 0x0000000000000000000000000000000000000000000000000000000000000001
    PUSH 0x00
    SHL
    ---
    0x0000000000000000000000000000000000000000000000000000000000000001
    
  2. PUSH 0x0000000000000000000000000000000000000000000000000000000000000001
    PUSH 0x01
    SHL
    ---
    0x0000000000000000000000000000000000000000000000000000000000000002
    
  3. PUSH 0x0000000000000000000000000000000000000000000000000000000000000001
    PUSH 0xff
    SHL
    ---
    0x8000000000000000000000000000000000000000000000000000000000000000
    
  4. PUSH 0x0000000000000000000000000000000000000000000000000000000000000001
    PUSH 0x0100
    SHL
    ---
    0x0000000000000000000000000000000000000000000000000000000000000000
    
  5. PUSH 0x0000000000000000000000000000000000000000000000000000000000000001
    PUSH 0x0101
    SHL
    ---
    0x0000000000000000000000000000000000000000000000000000000000000000
    
  6. PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    PUSH 0x00
    SHL
    ---
    0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    
  7. PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    PUSH 0x01
    SHL
    ---
    0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe
    
  8. PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    PUSH 0xff
    SHL
    ---
    0x8000000000000000000000000000000000000000000000000000000000000000
    
  9. PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    PUSH 0x0100
    SHL
    ---
    0x0000000000000000000000000000000000000000000000000000000000000000
    
  10. PUSH 0x0000000000000000000000000000000000000000000000000000000000000000
    PUSH 0x01
    SHL
    ---
    0x0000000000000000000000000000000000000000000000000000000000000000
    
  11. PUSH 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    PUSH 0x01
    SHL
    ---
    0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe
    

SHR (logical shift right)

  1. PUSH 0x0000000000000000000000000000000000000000000000000000000000000001
    PUSH 0x00
    SHR
    ---
    0x0000000000000000000000000000000000000000000000000000000000000001
    
  2. PUSH 0x0000000000000000000000000000000000000000000000000000000000000001
    PUSH 0x01
    SHR
    ---
    0x0000000000000000000000000000000000000000000000000000000000000000
    
  3. PUSH 0x8000000000000000000000000000000000000000000000000000000000000000
    PUSH 0x01
    SHR
    ---
    0x4000000000000000000000000000000000000000000000000000000000000000
    
  4. PUSH 0x8000000000000000000000000000000000000000000000000000000000000000
    PUSH 0xff
    SHR
    ---
    0x0000000000000000000000000000000000000000000000000000000000000001
    
  5. PUSH 0x8000000000000000000000000000000000000000000000000000000000000000
    PUSH 0x0100
    SHR
    ---
    0x0000000000000000000000000000000000000000000000000000000000000000
    
  6. PUSH 0x8000000000000000000000000000000000000000000000000000000000000000
    PUSH 0x0101
    SHR
    ---
    0x0000000000000000000000000000000000000000000000000000000000000000
    
  7. PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    PUSH 0x00
    SHR
    ---
    0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    
  8. PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    PUSH 0x01
    SHR
    ---
    0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    
  9. PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    PUSH 0xff
    SHR
    ---
    0x0000000000000000000000000000000000000000000000000000000000000001
    
  10. PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    PUSH 0x0100
    SHR
    ---
    0x0000000000000000000000000000000000000000000000000000000000000000
    
  11. PUSH 0x0000000000000000000000000000000000000000000000000000000000000000
    PUSH 0x01
    SHR
    ---
    0x0000000000000000000000000000000000000000000000000000000000000000
    

SAR (arithmetic shift right)

  1. PUSH 0x0000000000000000000000000000000000000000000000000000000000000001
    PUSH 0x00
    SAR
    ---
    0x0000000000000000000000000000000000000000000000000000000000000001
    
  2. PUSH 0x0000000000000000000000000000000000000000000000000000000000000001
    PUSH 0x01
    SAR
    ---
    0x0000000000000000000000000000000000000000000000000000000000000000
    
  3. PUSH 0x8000000000000000000000000000000000000000000000000000000000000000
    PUSH 0x01
    SAR
    ---
    0xc000000000000000000000000000000000000000000000000000000000000000
    
  4. PUSH 0x8000000000000000000000000000000000000000000000000000000000000000
    PUSH 0xff
    SAR
    ---
    0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    
  5. PUSH 0x8000000000000000000000000000000000000000000000000000000000000000
    PUSH 0x0100
    SAR
    ---
    0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    
  6. PUSH 0x8000000000000000000000000000000000000000000000000000000000000000
    PUSH 0x0101
    SAR
    ---
    0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    
  7. PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    PUSH 0x00
    SAR
    ---
    0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    
  8. PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    PUSH 0x01
    SAR
    ---
    0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    
  9. PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    PUSH 0xff
    SAR
    ---
    0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    
  10. PUSH 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    PUSH 0x0100
    SAR
    ---
    0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    
  11. PUSH 0x0000000000000000000000000000000000000000000000000000000000000000
    PUSH 0x01
    SAR
    ---
    0x0000000000000000000000000000000000000000000000000000000000000000
    
  12. PUSH 0x4000000000000000000000000000000000000000000000000000000000000000
    PUSH 0xfe
    SAR
    ---
    0x0000000000000000000000000000000000000000000000000000000000000001
    
  13. PUSH 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    PUSH 0xf8
    SAR
    ---
    0x000000000000000000000000000000000000000000000000000000000000007f
    
  14. PUSH 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    PUSH 0xfe
    SAR
    ---
    0x0000000000000000000000000000000000000000000000000000000000000001
    
  15. PUSH 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    PUSH 0xff
    SAR
    ---
    0x0000000000000000000000000000000000000000000000000000000000000000
    
  16. PUSH 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    PUSH 0x0100
    SAR
    ---
    0x0000000000000000000000000000000000000000000000000000000000000000
    

TRC:Implement DB storage with RocksDB

Preamble

author: @shydesky [email protected]
discussions to: #24
status: Final(core)
type: Standards Track
category: TRC
created: 2019-03-04

Simple Summary

Implement the database storage layer with RocksDB.

Abstract

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.

Motivation

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.
So, it wisely adds the implementation of the database storage layer with RocksDB to make our java-Tron more effective and robust.

update abi

Simple Summary

update contract abi

Abstract

provide a solution to update old ABIs on the block chain.

Motivation

Considering security and privacy issues, developers sometimes need to modify the abi for the deployed contract to hide some key information

Specification

add "UpdateContractABI" in Transaction.Contract.ContractType defined in Tron.proto

update contract abi structure:

message UpdateContractABI {
  bytes owner_address = 1;
  bytes contract_address = 2;
  bytes abi = 3;
}

rpc api:

// modify abi in contract
rpc UpdateContractABI (UpdateContractABI) returns (TransactionExtention) {
};

provide implementation of UpdateContractABIActuator, add entrance of http and rpc service

when developer set contract abi empty, it is impossible to determine whether it is a constant call through the ABI when the contract is triggered, so it is necessary to add a new interface to trigger constant call to contract

api:

// tigger constant call
rpc ConstantTriggerContract (TriggerSmartContract) returns (TransactionExtention) {
}

TRC101: Tron Keystore Specification

tip: 101
title: Tron Keystore Specification
author: federico<[email protected]>
discussions-to: https://github.com/tronprotocol/tips/issues/101
status: draft
type: Standards Track
category: TRC
created: 2019-10-17

Simple Summary

This TIP describes the keystore generation method to store the private key in wallet.

Abstract

Private key is fatally important for users, which should be kept carefully. Mnemonic code specified in BIP39 is used to
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
about keystore specification, which includes the procedures of key derivation, symmetric encryption and message authentication.

Motivation

The proposal presents the explicit cryptographic method to generate the keystore file and guarantee the security of users' private keys.

Specification

There are mainly three steps as follows.

Key Derivation Function

First, the user needs to provide the passphrase as the input of PBKDF2. The key derivation function has five input parameters:

DK = PBKDF2(PRF, Passphrase, Salt, c, dkLen)

where

  • PRF is a pseudorandom function generated by SHA256
  • Passphrase is the master password from which a derived key is generated
  • Salt is a sequence of bits, known as a cryptographic salt
  • c is the number of iterations desired
  • dkLen is the desired bit-length of the derived key
  • DK is the generated derived key

Symmetric Encryption

The derived key DK is used as key of AES to encrypt the real private key of user.

C = AES-128(DK, PrivK, CTR, iv)

where

  • DK is the derived key
  • PrivK is the private key of user,which is generated by mnemonic codes specified in BIP39
  • CTR is the counter encryption mode
  • iv is 128-bit initialisation vector for the cipher
  • C is the generated cipher text

Message Authentication Code

MAC (Message authentication code) is used to check the correctness of derived key DK when the user try to decrypt the private key
with the passphrase. SHA3 is used to produce the MAC:

mac = SHA3-256 (DK || C)

where

  • DK is the derived key
  • C is the cipher text of private key
  • mac is the generated MAC

Rationale

The SHA256 and AES used in the proposal are all international cryptography standard, which are sufficient to ensure the security of the private key.

Test Cases

For Passphrase = dark1234, the generated keystore file is:

 {"crypto":
    {"cipher":"aes-128-ctr",
      "cipherparams":{"iv":"faa1c1b73bb9630b8abb7930eccc85f0"},
      "ciphertext":"3c46834a29e69fc206277838fdeb395320d7da10d2c067f5b1e0a8a52524fde3",
      "kdf":"pbkdf2",
      "kdfparams":
         {"c":10240,
          "dklen":32,
          "prf":"hmac-sha256",
          "salt":"aaf471468f1030229004f5a189be470fde806685ede147b1694be60fb15b70f1"
         }, 
      "mac":"ff7679e803175ba739fadbffe38959282f45aefa3458f083eedc76fc220b201e"
    },
    "id":"e40c9b94-369c-4b75-a2cd-8c68d542e093",
    "version":3,
    "address":"fdf9ae6a88fd403cdd2433c23230e729d12d6de4"
 }

Implementation

None

Reference

https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition

TRC: Support interact with built-in dex in smartcontract

1. What did you do?
Interact with built-in TRC10 dex in smartcontract for auto swap token.

2. What did you expect to see?
Support interact with built-in TRC10 dex in smartcontract

3. What did you see instead?
Not supported

TRC-43: Precompiled contract function for signature parallel verification

tip: 43
title: TRC-43: Precompiled contract function for signature parallel verification
author: Sh11thead<[email protected]> 
discussions to: https://github.com/tronprotocol/TIPs/issues/43
category: TRC
status: accept
created: 2019-07-10

Simple Summary

A new type of precompiled contract function for signature parallel verification

Abstract

Add a new type of build-in precompiled contract function for multisign validating instead of the compiled bytecode do the same task.

Motivation

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.

Specification

Adds a new precompiled contract function named batchvalidatesign , which need 3 arguments input:

  • bytes32 hash
  • bytes[] signatures
  • address[] addresses

Sample code

pragma experimental ABIEncoderV2;
contract Demo {
    function testBatch(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns(bytes32){
        return batchvalidatesign(hash, signatures, addresses);
    }
}

output of the result of signature validating would be a bytes32, for example :
10100000000000000000000000000000 representing the first signatue and third signatue is correct

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.

Energy cost

energy charge for the execution cost 1500 per signature

ERC20 Token Proposal

Currently it's not possible to exchange tokens inside TRON Network. However the industry standard ERC20 have been developed. Our proposal is to taken advantage of the open source standard ERC20 and create a new ERC20 standard for TRON. ERC20 is an interface that allows any tokens on TRON to be re-used and exchanged by other applications: from wallets to decentralized exchanges.

TRC-CRS01: Protocol field definition

Simple Summary

This doc describes the a solution to protocol field definition

Abstract

Protocol field definitions required for cross-chain

Motivation

Implement cross-chain communication

Specification

Implement across-chain need to add fields:

In order to implement SPV we need to add two fields in the block header, namely: srList, genesisBlockId.

For message routing, we need to add the two fields of version and genesisBlockId to the block and transaction.

In order to achieve cross-chain trading, the transaction adds a cross-chain type CrossContract

In order to achieve cross-chain communication, node identification needs to add two fields, version and genesisBlockId.

Algorithm

Proto

message BlockHeader {
message raw {
int64 timestamp = 1;
bytes txTrieRoot = 2;
bytes parentHash = 3;
//bytes nonce = 5;
//bytes difficulty = 6;
int64 number = 7;
int64 witness_id = 8;
bytes witness_address = 9;
int32 version = 10;
bytes accountStateRoot = 11;
SrList srList = 12;
bytes genesisBlockId = 13;
}
raw raw_data = 1;
bytes witness_signature = 2;
}

message SrList {
message raw {
bytes currentSrList = 1;
bytes nextSrList = 2;
}
bytes sr_signature = 3;
}

message Transaction {
message Contract {
enum ContractType {
AccountCreateContract = 0;
TransferContract = 1;
TransferAssetContract = 2;
VoteAssetContract = 3;
VoteWitnessContract = 4;
WitnessCreateContract = 5;
AssetIssueContract = 6;
WitnessUpdateContract = 8;
ParticipateAssetIssueContract = 9;
AccountUpdateContract = 10;
FreezeBalanceContract = 11;
UnfreezeBalanceContract = 12;
WithdrawBalanceContract = 13;
UnfreezeAssetContract = 14;
UpdateAssetContract = 15;
ProposalCreateContract = 16;
ProposalApproveContract = 17;
ProposalDeleteContract = 18;
SetAccountIdContract = 19;
CustomContract = 20;
// BuyStorageContract = 21;
// BuyStorageBytesContract = 22;
// SellStorageContract = 23;
CreateSmartContract = 30;
TriggerSmartContract = 31;
GetContract = 32;
UpdateSettingContract = 33;
ExchangeCreateContract = 41;
ExchangeInjectContract = 42;
ExchangeWithdrawContract = 43;
ExchangeTransactionContract = 44;
UpdateEnergyLimitContract = 45;
AccountPermissionUpdateContract = 46;
ClearABIContract = 48;
CrossContract = 49;
}
ContractType type = 1;
google.protobuf.Any parameter = 2;
bytes provider = 3;
bytes ContractName = 4;
int32 Permission_id = 5;
}

message Result {
enum code {
SUCESS = 0;
FAILED = 1;
}
enum contractResult {
DEFAULT = 0;
SUCCESS = 1;
REVERT = 2;
BAD_JUMP_DESTINATION = 3;
OUT_OF_MEMORY = 4;
PRECOMPILED_CONTRACT = 5;
STACK_TOO_SMALL = 6;
STACK_TOO_LARGE = 7;
ILLEGAL_OPERATION = 8;
STACK_OVERFLOW = 9;
OUT_OF_ENERGY = 10;
OUT_OF_TIME = 11;
JVM_STACK_OVER_FLOW = 12;
UNKNOWN = 13;
TRANSFER_FAILED = 14;
}
int64 fee = 1;
code ret = 2;
contractResult contractRet = 3;

string assetIssueID = 14;
int64 withdraw_amount = 15;
int64 unfreeze_amount = 16;
int64 exchange_received_amount = 18;
int64 exchange_inject_another_amount = 19;
int64 exchange_withdraw_another_amount = 20;
int64 exchange_id = 21;

}

message raw {
bytes ref_block_bytes = 1;
int64 ref_block_num = 3;
bytes ref_block_hash = 4;
int64 expiration = 8;
repeated authority auths = 9;
// data not used
bytes data = 10;
//only support size = 1, repeated list here for extension
repeated Contract contract = 11;
// scripts not used
bytes scripts = 12;
int64 timestamp = 14;
int64 fee_limit = 18;
int32 version = 19;
bytes genesisBlockId = 20;
}

raw raw_data = 1;
// only support size = 1, repeated list here for muti-sig extension
repeated bytes signature = 2;
repeated Result ret = 5;
}

message CrossContract {
bytes owner_address = 1;
bytes owner_version = 2;
bytes owner_genesisBlockId = 3;
bytes to_address = 4;
bytes to_version = 5;
bytes to_genesisBlockId = 6;
int64 amount = 7;
}

message Neighbours {
Endpoint from = 1;
repeated Endpoint neighbours = 2;
int64 timestamp = 3;
bytes version = 4;
bytes genesisBlockId = 5;
}

TRC-23: Add the account world status tree root to the block header

tip: 23
title: TRC-23 Add the account world status tree root to the block header
author: lvs007 [email protected]
discussions to: #23
status: in progress
type: Standards Track
category: TRC
created: 2019-03-04

Simple Summary
The purpose is to verify the consistency of the entire account.
Abstract
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.
Motivation

Specification
modify the block header structure, add the accountStateRoot
message BlockHeader {
message raw {
int64 timestamp = 1;
bytes txTrieRoot = 2;
bytes parentHash = 3;
//bytes nonce = 5;
//bytes difficulty = 6;
int64 number = 7;
int64 witness_id = 8;
bytes witness_address = 9;
int32 version = 10;
bytes accountStateRoot = 11;
}
raw raw_data = 1;
bytes witness_signature = 2;
}

Account State Root Generate
Introduced the Ethereum's world state tree model
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.
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.

Account State Root Validate
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.

TRC-CRS03: Node interconnect communication

Simple Summary

This doc describes the solution to node interconnect communication

Abstract

It defines how nodes connect and communicate with each other. Cross-chain node communication needs to be relayed, the relay is the main chain, and other chains connected to the main chain are called branches.

Motivation

Support the IBC communication

Specification

Configure the main chain and the branch chain seeds. When the node is connected to the handshake, we need to exchange the node information of each other. The link pool contains this chain connection and cross-chain connection.

Previously, if the version or genesisBlockId were inconsistent, the connection would be disconnected. Now, after adding the cross-chain mechanism, it will not be disconnected. Only the branch and the main chain are allowed to be interconnected, and the branches cannot be interconnected.

The main chain can also act as a branch chain character. When the node is started, it is determined whether to start a main or branch by setting a parameter. If it is to start the main, it needs to manage the connection and block header of different branches, which is responsible for the cross-chain forwarding function. If it is a branch, it needs to register with the main and download the main chain block header.

Algorithm

Proto

message HelloMessage {
message BlockId {
bytes hash = 1;
int64 number = 2;
}

Endpoint from = 1;
int32 version = 2;
int64 timestamp = 3;
BlockId genesisBlockId = 4;
BlockId solidBlockId = 5;
BlockId headBlockId = 6;
}

TRC: Deferred transaction

tip: 19
title: TRC-19 Deferred transaction
author: jiangyy [email protected]
discussions to: #19
status: in progress
type: Standards Track
category: TRC
created: 2019-01-30

Simple Summary
Deferred transaction will be supported in Tron. Transaction can be delayed and revoked before it expires. This would provide developers with more flexible and efficient experience.

Abstract
Currently, the transaction in Tron will be executed immediately. In certain scenarios, developers need to trigger transactions at a specified time and be able to cancel the transaction before it expires. It is necessary to take into account the potential security issue caused by deferred transactions, such as transaction congestion attack. Fee for deferred transactions should also be modified.

Motivation
This will allow developers to execute deferred transactions in Tron. More business scenarios can be satisfied.

Specification

Transaction structure
Add "delaySeconds" in the transaction structure which is defined in Tron.proto.

MessageTransaction{
Message raw{

Bytes ref_block_bytes = 1;
Int64 ref_block_num = 3;
Bytes ref_block_hash = 4;
Int64 expiration = 8;
Repeated authority auths = 9;
// data not used
Bytes data = 10;
// Only support size = 1, repeated list here for extension
Repeated Contract contract = 11;
// scripts not used

Bytes scripts = 12;
Int64 timestamp = 14;
Int64 fee_limit = 18;
Int64 delaySeconds = 19; // seconds of delay
}
}

"delaySeconds" is placed in the raw field, so that it could be protected using permissions.

Message DeferredTransaction{
Bytes transactionId = 1;
Int64 publishTime = 2;
Int64 delayUntil = 3;
Int64 expiration = 4;
Bytes senderAddress = 5;
Bytes receiverAddress = 6;
Transaction transaction = 7;
}

Deferred transaction stored in chain.

DeferredTransactionStore
For storing delayed transactions waiting to be executed, including the following fields:

  • Transactionid
  • Delay_until// The time at which the transaction is expected to execute
  • Publish // Publish Time
  • Expiration // delayed transaction expiration time
  • Sender // sender address
  • Payer // receiver address

DeferredTransactionIdIndexStore
An index database of delayed transactions with transaction ID as key is used to quickly retrieve delayed transactions.

Settings/Cancels/Trigger
Wallet and java-tron need to be modified for transaction types that support delayed transactions

1. AccountUpdateContract
2. TransferContract
3. TransferAssetContract
4. AccountCreateContract
5. UnfreezeAssetContract
6. FreezeBalanceContract
7. UnfreezeBalanceContract
8. WithdrawBalanceContract
9. UpdateAssetContract
10. SetAccountIdContract
11. UpdateSettingContract
12. UpdateEnergyLimitContract
13. AccountPermissionUpdateContrac

Cancellation of deferred transactions:

CancelDeferred Transaction, entered as transactionid, is deleted from the database if the transaction has not expired when fullnode is executed. Cancellation of transactions is linked.

Cancellation of delayed transactions requires authorization, and only an account created for delayed transactions can be authorized to cancel.

Delayed Transaction Trigger

The execution of a delayed transaction includes two stages: submitting the delayed transaction and executing the delayed transaction.

Users need to login account on Wallet-cli , then transaction would include the account address.

Delayed transaction submitted

When the fullnode node receives the delayed transaction, the transaction data is inserted into the Deferred Transaction Store, indexed and inserted into the Deferred Transaction IdIndexStore.

Delayed transaction execution

When a transaction expires, the transaction data is read from the Deferred Transaction Store, the transaction is executed, and the records in the Deferred Transaction Store are deleted.

Note: The transaction ID and transaction receipt of the two transaction records are different. For example, the Wallet-cli side executes sendcoin and generates a transaction ID of TransactionA.

When a delayed transaction is executed for the first time, the corresponding transaction ID is TransactionA, and a new transaction ID is generated for the second execution to identify the transaction that is actually executed.

Default parameter & Configuration

  • DEFERED_TRANSACTION_FEE//Cost of creating delayed transactions, default 0.1 TRX
  • CANCEL_DEFERED_TRANSACTION_FEE//Cost of cancelling delayed transactions, default 0.05 TRX
  • MAX_DEFERED_TRANSACTION_PROCESS_TIME // Maximum processing time for delayed transactions per block, default to 100 ms

All three parameters can be modified by proposals.

Delayed transactions are charged according to the number of days, and the cost per day is 0.1 trx. Assuming a delay of 10 days, the total charge is 10 * 0.1 TRX = 1 trx.

Generate block loginc

The priority of deferred transaction is higher than that of ordinary transaction. First, the deferred transaction due is executed, and then the ordinary transaction is executed.

The total execution time limit of delay transaction is set to 100 ms to prevent congestion attack.

Pressure measurement is used to verify the maximum number of delayed transactions per block, and the setting of timeout parameters can be adjusted.

Wallet/browser support
Add RPC / HTTP interface settings and cancel transaction.
Transaction query command, which can display fields related to delayed transactions.

GetTransactionById: Enter the transactionid returned by wallet-cli and return the first record of the delayed transaction.

GetDeferredTransactionById: Enter the transactionid returned for wallet-cli, return the real transaction information, corresponding to the second record of the delayed transaction.

Proposal support
In order to dynamic change config, we add three new proposals to support the deferred transaction.
Proposal 24: change the deferred transaction fee.
Proposal 25: change cancel fee of the deferred transaction.
Proposal 26: change max deferred transaction process time in one block.

TRC: Rate Limit of Api Traffic

tip: 51
title: TRC-51 rate limit of API traffic
author: shydesky<[email protected]>
discussions-to: https://github.com/tronprotocol/TIPs/issues/51
status: Draft
type: Standards Track
category: Interface
created: 2019-07-30

Simple Summary

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.

Abstract

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.
There are many mature algorithms can be used, like Token bucket, Leaky bucket.

Motivation

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.

Specification

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.
The control granularity is set at the specific interface.

Rationale

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.

Implementation

There are three types of strategies implemented in the java-Tron right now. They are Global Preemptible Strategy, QpsStrategy, IPQPSStrategy.
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.
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.

TRC-54: Automatically active non-existent account when transferring TRX/TRC10 asset in smart contract

tip: 54
title: TRC-54: Automatically active non-existent account when transferring TRX/TRC10 asset in a smart contract
author: Jeancky <[email protected]>
discussions to: https://github.com/tronprotocol/TIPs/issues/54
category: TRC
status: accepted
created: 2019-08-09

Abstract

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.

Motivation

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.

Specification

Before implementing this function, we need to consider that when the address is activated, the instruction will charge an additional 0.1 TRX fee.

There are many ways to do this, here are two possible ways:

  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.

  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.

Rationale

In terms of instruction charging, the energy price is an adjustable variable. How to accurately charge 0.1TRX needs to be discussed.

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.

Backwards Compatibility

  1. In terms of energy consumption, it needs to be consistent with the system GRPC interface.

  2. If we want to do that, we need to review the impact of each implementation on existing contracts.

  3. One of these implementations relies on TRON's Solidity compiler update, which is not compatible with historical compiler versions.

TRC-CRS04: Block header download

Simple Summary

This doc describes a solution to block header downloading.

Abstract

The main chain and the branch chain need to synchronize the block header of the other party. The block header synchronization is to provide security for the SPV.

Motivation

Support SPV features in the future

Specification

Block header synchronization:
The main chain needs to synchronize their block headers from different branches. The branch chain needs to synchronize the block header of the main chain from the main chain.

The main chain node preferentially synchronizes from the corresponding branch chain sync block header. If there is no corresponding branch chain connection,the block header of the branch chain is synchronized from the other main chain nodes.

The branch chain node preferentially synchronizes the main chain block header from the main chain. If there is no main connection, the main chain block header is synchronized from the other nodes of the branch chain.

Block header broadcast:
Main chain broadcasts its own block header to all branches (if main chain node does not have a corresponding connection to main chain node, it does not need to be processed).
Branch chain broadcasts its own block header to main chain (if there is no main chain connection, it does not need to be processed).
If the received block header occurs unlink, then trigger synchronization.

Block header storage:
Main is based on version and genesisBlockId as a chain key, corresponding to <key, <blockId, head>>; branch only needs to store the main header so only one storage structure <blockId, head>.

Algorithm

Proto

message BlockHeader {
message raw {
int64 timestamp = 1;
bytes txTrieRoot = 2;
bytes parentHash = 3;
//bytes nonce = 5;
//bytes difficulty = 6;
int64 number = 7;
int64 witness_id = 8;
bytes witness_address = 9;
int32 version = 10;
bytes accountStateRoot = 11;
SrList srList = 12;
bytes genesisBlockId = 13;
}
raw raw_data = 1;
bytes witness_signature = 2;
}

message SrList {
message raw {
bytes currentSrList = 1;
bytes nextSrList = 2;
}
bytes sr_signature = 3;
}

TRC-CRS05: Cross-chain asset transfer

Simple Summary

This doc describes the a solution to cross-chain asset transfer

Abstract

Motivation

Realize the transfer of assets between different chains

Specification

Add a trade-type CrossContract, the transfer process is as follows:

  1. Chain A receives a cross-chain transaction, checks the legality of the transaction (signature balance, etc.), and if it is legally placed in pending, waits for the sr node to pack into the block.

  2. When the transaction is packaged into the block and cannot be rolled back, the transaction is forwarded to the main chain (sr signature with A chain more than 2/3), and the main chain will verify whether the transaction has more than 2/3 Signature, if it is, package it into the block

  3. When the transaction is packaged into the main chain block and cannot be rolled back, the transaction is sent to the B chain (sr signature with the main chain more than 2/3), and the B chain will verify to the main chain whether the transaction has More than 2/3 of the signature, if you have it, package it into the block

Until it is ensured that the transaction is solidified in the B chain, repackage the transaction if the block is rolled back

Algorithm

Proto

message CrossContract {
bytes owner_address = 1;
int32 owner_version = 2;
bytes owner_genesisBlockId = 3;
bytes to_address = 4;
int32 to_version = 5;
bytes to_genesisBlockId = 6;
int64 amount = 7;
}

TRC53:Optimize the current TRON delegation mechanism

tip: 53
title: TRC53: Optimize the current TRON delegation mechanism
author: lvs007 <[email protected]>
discussions to: https://github.com/tronprotocol/TIPs/issues/53
category: TRC
status: final
created: 2019-07-31

Simple Summary

This doc describes a solution to optimize the current TRON delegation mechanism

Abstract

At present, the TRON's delegation mechanism is that the user votes for the node. If the node is elected sr, then each block will reward sr with 32 TRX, and the top 100 votes will receive additional rewards; if the node does not give the user dividends, then users can not get rewards, it can not improve the enthusiasm of users to vote, resulting in a lower mortgage rate on the whole network.

Current Situation

The current setting for block production rewards is 32 TRX per block. The block production cycle is 3 seconds. For every six hours, there will be two production cycles counting the votes without packing the blocks. Thus, the number of blocks packed by TRON blockchain is 86400 / 3 - 2 * 4 = 28792.
Thus, the daily rewards for block production are 32TRX/block * 28792 block = 921344 TRX.
The voting rewards are 16 TRX per block. So the daily voting rewards stands at 16TRX/block * 28800 block = 460800 TRX.

Such incentive mechanism encourages nodes to participate in the election of supernodes. By being a part of the production process and benefiting from it, the nodes have a stake in the game and keep the network runs smoothly. Those who didn't get elected would also receive voting rewards depending on the number of votes they got. The combination of production rewards and voting rewards takes all parties in the network into consideration and provides an enabling environment for nodes to contribute to the TRON network.

Let's look deeper into the on-chain data and the operation of TRON blockchain.
Currently, the volume of votes in the network is around 8.2 billion, taking up only less than 10% of the total number of votes. The reasons for such low participation, judging by the current operating parameters, is the low return rate. The daily voting rewards for each vote is 60672TRX / 8200000000 votes /day = 5.7584e-05 TRX/vote/day; the average annual return is 5.7584e-05 * 365 = 2.1%. Due to the unimpressive return rate, nodes that have TRX are not motivated to participate in the voting process.
From the perspective of block production rewards, the first 27 supernodes receive a total number of 7.5 billion votes. With the same formula, the daily block production rewards are
921344TRX / 7500000000 votes / day = 1.2284e-04 TRX/vote/day, which means the annual rewards rate is about 1.2284e-04*365 = 4.4%.
The comparison shows that block production rewards are higher than voting rewards.

The other problem is that the first and the twenty-seventh nodes produce the same amount of blocks in one day. But the first supernode has a total of 520 million votes and an annual production rewards rate of 2.4%, the twenty-seventh supernode has 180 million votes and 6.9% production rewards rate. This data shows that the node with more votes is rewarded even less than those who have fewer votes, which creates an unfair situation.

Therefore, the incumbent incentive mechanism has the following three issues:

  1. High threshold for participating in the election
    Judging by the on-chain data, the 27th and the 28th candidate are 50 million votes apart. That's over 40% of the total votes of the 28th candidate. Because voting rewards is only half as much as the production rewards, the profit gained by the 28th candidate is significantly lower than that of the 27th candidate, which causes drastic competition for the slot of the 27th candidate. In order to keep its slot, the node that is elected as the 27th will try to safeguard its position and widen the gap between the 28th and itself.

  2. Rewards distribution are not fully decentralized.
    The current mechanism is to have both production rewards and voting rewards directly distributed to the nodes. This method can only achieve a certain level of decentralization instead of making the system fully decentralized, for the rewards cannot get to the individual voters. After the nodes obtain the rewards, they will distribute them to the voters. However, this process itself is centralized and out of the scope of blockchain management.

  3. On-chain governance and incentive mechanism not separated
    Under current mechanism, production reward is far higher than the voting reward. Those who are not able to take part in the on-chain governance have lost the interest and the will to contribute to the community, which in a way severs the connection between the government body and the entire community. In the long run, that will make TRON blockchain become a somewhat centralized ecosystem, dampening its long-term growth. Once a supernode is down, it will be hard to fill its place right away, undermining the efficiency of the network.

Motivation

Improve the mortgage rate of the entire network TRX, while increasing the user's income more fairly

Specification

Two types of rewards: block reward and voting reward.
Block reward: the SR will get 16 TRX for each block it has generated.
Voting reward: for each block, the most-voted 127 SRs will receive TRX in proportion to the votes they get. Each block will reward 160 TRX in total, and each SR will get (SR’s votes/ total votes) * 160 TRX.
The rewarded TRX will not be added to the “allowance” field of the SR immediately. Users (including SRs) will have to withdraw TRX by themselves so that the rewards will show up on their account balance.
Meanwhile, SRs can take a percentage of commission from the dividends distributed to the users. For the commission, SRs can specify a value from 0 to 100. 0 means that no TRX will be extracted from users’ dividends, while 100 means that all dividends will be taken by the SRs. Also, SRs can modify the percentage and the new percentage will take effect from the next maintenance period.

Algorithm

Dividends SRs:

The starting cycle(current cycle) defaults to 0, and each time the maintenance period is changed, it is automatically incremented by 1 (that is, the current cycle is incremented by 1 for each maintenance period).
After the user votes, the node is rewarded from the next maintenance period, the reward period is a maintenance period, the reward is recalculated in the next maintenance period, the reward period is also a maintenance period, and so on.
Each block will give the generating block node and other sr dividends, give the generating block node 16TRX reward, and give the reward of the top 127 nodes 160TRX (according to the proportion of votes), one record per maintenance period for each node
The format is: <key, value>, key:cycle + "-" + address + "-reward"; value: the number of TRX rewarded.
In this way, the overall delegation mechanism dividend will be changed into a dividend for each block, which includes the 16TRX reward to the current generate block sr and 127 candidate sr nodes dividend 160TRX (the current generate block sr can get two dividends; other Candidate sr gets a bonus)

Dividends to users:

How to distribute dividends to users adopts active trigger mechanism: it is divided into three parts when the user re-votes when the user unfreezes when the user withdraws the reward
Calculation Rules:
Whether there is the last period (begin and end both exist and begin+1=end), if there is a need to calculate the dividends of this part, and calculate the current dividend from begin+1; if not, then from begin calculating the current dividends (this time you need to determine whether the current user's voting information is empty, if the empty setting is set begin=current+1, and return)
And re-recording the start cycle(begin) of the vote, and the end cycle: end=begin+1, and the current user vote information

New block reword distribution plan:

The current block distribution plan is 32 TRX reword to SR who produce the block and 16 TRX reword equally distributed to SRs and stand-by SRs according to the voting number.
To encourage SRs to have more voters, we will change the 32 TRX(reword to block producer) to 16TRX and 16TRX (reword to all SRs according to the voting number) to 160 TRX.

Advantages:

  1. A decentralized dividend distribution mechanism featuring fairness that encourages
    greater user participation. Moving the distribution process on the chain and keeping the record on the blockchain makes the rewards distribution completely decentralized and trackable.

  2. Greater voter turnout and higher delegation rate, which vitalizes the community and
    strengthens the economic system across the network

  3. Fewer unnecessary dividend distribution transactions, leading to less bandwidth
    consumption and thus a more robust network

  4. The foundation for more complex consensus and incentive plans, signaling more
    possibilities and convenience for future development

Future goals:

A Brand New Consensus Mechanism

A new hybrid consensus mechanism has been running smoothly on TRON for 15 months. The stability of the DPOS consensus mechanism plays a significant part in this success, but we should also notice there is room for the DPOS mechanism to improve - for example, shorter block confirmation time and SPV support.

Therefore, we plan on developing a new hybrid consensus mechanism based on DPOS+PBFT, under which the new automatic dividend distribution system will help to realize a new set of complex token dividend distribution rules.

The new hybrid consensus mechanism will help to expand the scalability of the TRON ecosystem, unify cross-chain protocols and improve DApp usability.

Punishment Mechanism

TRON’s sound progress is closely related to the stable and efficient block generation of our excellent SR nodes. That being said, we have also noticed a relatively high block missing rate and low packaging rate in some nodes due to undesirable equipment and network performance.

These nodes are slowing down the overall network speed, which can be harmful to the network and unfair to other SRs. To address this problem, we plan to introduce the automatic dividend distribution mechanism. By punishing unreliable and malicious nodes more directly, efficiently and accurately, the mechanism will be of great use in improving the performance of the whole network.

Proposal Prize Pool

As of today, 26 proposals have been initiated in the TRON network, each contributing to the development of the network. Nevertheless, we believe that the proposals can help us achieve autonomy in the community to a greater extent.

In order to encourage more community members to take part in the proposals, we plan to add a “prize pool” with an automatic dividend distribution scheme to the existing proposal mechanism. The prize pool will be created by each proposal initiator. SRs who actively participate in voting will receive incentives directly.

Moving on, we will also innovate and modify the way we organize proposals, e.g. participant eligibility, initiator eligibility, participant number, etc., so as to improve community activity and lower the cost for an efficient community autonomy.

Giving Back To The Community

The new delegation mechanism and staking rewards distribution mechanism will be an important milestone in the evolution of our TRON protocol. Fair and transparent reward distribution mechanism will attract a wide range of nodes to participate in the TRON Blockchain network governance. At the same time, excluding the dividend payout transactions, the operation of the TRON Blockchain network will be more efficient.

In order to express our gratitude to all SRs for their outstanding contributions to TRON networks over the past year, TRON Foundation proposes a 50 million TRX distribution:

The detail of the distribution rule is:
SR(i) Reward = 50 millions * M(i) / N
M(i) = The amount of blocks SR(i) has produced till Oct 15, 2019
N = The number of blocks all the SRs (exclude the GRs) have produced till Oct 15, 2019

For example, one SR produce 100,000 blocks in this period and the total amount of blocks all SR produced is 20,000,000, then this SR can receive 50 million * 100,000 / 2,000,000 = 2.5 million TRX.

The proposal will be created on about Oct 15, 2019. Only after the proposal is approved, so can the 50 million TRX distribution be executed.

TRC: Optimize transactionHistoryStore occupancy space

tip: 41
title: Optimize transactionHistoryStore occupancy space#40
author: wubin1<[email protected]> 
discussions to: https://github.com/tronprotocol/TIPs/issues/40
category: TRC
status: accepted
created: 2019-5-20

Simple Summary

This doc describes the solution of optimizing transactionHistoryStore occupancy space

Abstract

In current storage model, transaction result saves in transaction history store and it occupies the most space.
The optimization merges all transactions in a common block and compression the transaction history space.

Motivation

TRON database already occupied 163GB and it increases 20G each month. So how to optimize space is very import.

Specification

TransactionHistory doesn't directly save in transactionHistoryStore after the execution of transactions.

transactionHistoryStore.put(trxCap.getTransactionId().getBytes(), transactionInfo);

Add transaction history in memory and save in disk after executing one whole block.

    transationHistoryCapsule.addTransactionResult(result); 
     if (block.getTransactions().size() != 0) {
      this.transactionHistoryStore.put(ByteArray.fromLong(block.getNum()), block.getResult());
    } 

Rationale

Saving transaction history for a whole block could reduce duplicate data and protocol buffer compression is more effective for large data.

Backwards Compatibility

There are no backwards compatibility concerns.

Test Cases

  1. Compare storage size from optimization version and not optimization version.
  2. Query function for transaction history

TRC-58:Add a native TVM function to validate multi-signature for provided account

Simple Summary

This doc describes a native TVM function which is used to validate multi-signature for a provided account.

Motivation

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.Multiple-signed message can not be verified in TVM , so we need a new function to support multiple-sign case.

Specification

Add a new function validatemultisign in solidity compiler .

This function takes 4 parameters:

validatemultisign(
address accountAddress, // account address  
uint256 permissionId, //permissionId for account
bytes32 hash, //content for verifying
bytes[] signatures//signatures to be verified
)

This function will call to a specific address 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.

Rationale

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.

Backwards Compatibility

Adding a new precompiledContract cause no backwards compatibility concerns.

Test Cases

1.Verifying both correct and incorrect signatures in smart contract.
2.Verifying duplicate signatures.
3.Verifying more than 5 signatures.

TRC104: Data Signing Specification

tip: 104
title: Data Signing Specification
author: federico<[email protected]>
discussions-to: https://github.com/tronprotocol/tips/issues/104
status: draft
type: Standards Track
category: TRC
created: 2019-10-31

Simple Summary

It not only need to sign the transaction, but also some ordinary bytestrings in practical applications. It is necessary
to distinguish the two kinds of data when signing because risks may exist if an attacker tricks users to sign semantically meaningless bytes
which can de decoded as a valid transaction. This TIP aims to provide explicit method to distinguish between transaction
and ordinary bytestrings when signing.

Abstract

This is a standard for hashing and signing of data to distinguish the transactions and ordinary bytestrings. Furthermore, to make the users be clear of what the message they has signed instead of opaque bytestrings,
we also includes the typed structured data processing as opposed to just bytestrings based on
EIP712.

Motivation

To prevent the potential risk when user is tricked to sign forged message, it's necessary to provide the standard method to distinguish between transaction and ordinary message when signing.
Since signed messages are an opaque hex string displayed to the user with little context about the items that make up the message, so we present the scheme to encode data along with its structure which allows it to be displayed to the user for verification when signing.

Specification

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, this is a function from bytestrings, 𝔹⁸ⁿ, to 256-bit strings, 𝔹²⁵⁶.

Transactions and bytestrings

There are two kinds of messages, transactions 𝕋 and bytestrings 𝔹⁸ⁿ. These are signed using signTransaction and signString respectively. Originally the encoding function encode : 𝕋 ∪ 𝔹⁸ⁿ → 𝔹⁸ⁿ was defined as follows:

  • encode(t : 𝕋) = Protobuf(t)
  • encode(b : 𝔹⁸ⁿ) = b

Note: Protobuf is an encoding method for serializing structured data.

If an attacker take b = Protobuf(t), it can mislead the user to sign a valid transaction as opaque bytestrings. To avoid the problem, we can modify the second encoding function:

  • encode(b : 𝔹⁸ⁿ) = "\x19TRON Signed Message:\n" ‖ len(b) ‖ b where len(b) is the ascii-decimal encoding of the number of bytes in b.

This can solve the problem since Protobuf(t : 𝕋) in our implementation never starts with \x19. Actually, the first byte should be \x15, which denotes the byte length of "TRON Signed Message:\n". In order to keep consistent with the current implementation, we will leave it as it is.
For the same reason, len(b) is set as the fixed 32.

Hash selection

Different Hash algorithms are used for transactions and bytestring when signing. Actually, when signing the transaction, SHA256 is used; when signing the bytestrings, Keccak256 is used.

  • Hash(t : 𝕋) = SHA256(encode(t : 𝕋))
  • Hash(b : 𝔹⁸ⁿ) = Keccak256(encode(b : 𝔹⁸ⁿ))

Arbitrary messages

The signString call assumes messages to be bytestrings. In practice we are not hashing bytestrings but the collection of all semantically different messages of all different DApps 𝕄. Unfortunately, this set is impossible to formalize. Instead we approximate it with the set of typed named structures 𝕊. This standard formalizes the set 𝕊 and provides a deterministic injective encoding function for it.

Just encoding structs is not enough. It is likely that two different DApps use identical structs. When this happens, a signed message intended for one DApp would also be valid for the other. The signatures are compatible. This can be intended behaviour, in which case everything is fine as long as the DApps took replay attacks into consideration. If it is not intended, there is a security problem.

The way to solve this is by introducing a domain separator, a 256-bit number. This is a value unique to each domain that is 'mixed in' the signature. It makes signatures from different domains incompatible. The domain separator is designed to include bits of DApp unique information such as the name of the DApp, the intended validator contract address, the expected DApp domain name, etc. The user and user-agent can use this information to mitigate phishing attacks, where a malicious DApp tries to trick the user into signing a message for another DApp.

Note on replay attacks

This standard is only about signing messages and verifying signatures. In many practical applications, signed messages are used to authorize an action, for example an exchange of tokens. It is very important that implementers make sure the application behaves correctly when it sees the same signed message twice. For example, the repeated message should be rejected or the authorized action should be idempotent. How this is implemented is specific to the application and out of scope for this standard.

Structured Data

The set of signable messages is extended from transactions and bytestrings 𝕋 ∪ 𝔹⁸ⁿ to also include structured data 𝕊. The new set of signable messages is thus 𝕋 ∪ 𝔹⁸ⁿ ∪ 𝕊. They are encoded to bytestrings suitable for hashing and signing as follows:

  • encode(transaction : 𝕋) = Protobuf(transaction)
  • encode(message : 𝔹⁸ⁿ) = "\x19TRON Signed Message:\n" ‖ len(message) ‖ message where len(message) is the non-zero-padded ascii-decimal encoding of the number of bytes in message.
  • encode(domainSeparator : 𝔹²⁵⁶, message : 𝕊) = "\x19\x01" ‖ domainSeparator ‖ hashStruct(message) where domainSeparator and hashStruct(message) are defined below.

This encoding is deterministic because the individual components are. The encoding is injective because the three cases always differ in first two bytes. (Protobuf(transaction) in our implementation does not start with \x19.)

The 'version byte' is fixed to 0x01, the 'version specific data' is the 32-byte domain separator domainSeparator and the 'data to sign' is the 32-byte hashStruct(message).

Definition of typed structured data 𝕊

To define the set of all structured data, we start with defining acceptable types. Here is an example:

struct Mail {
    address from;
    address to;
    string contents;
}

Definition: A struct type has valid identifier as name and contains zero or more member variables. Member variables have a member type and a name.

Definition: A member type can be either an atomic type, a dynamic type or a reference type.

Definition: The atomic types are bytes1 to bytes32, uint8 to uint256, int8 to int256, bool and address. These correspond to their definition in Solidity. Note that there are no aliases uint and int. Note that contract addresses are always plain address. Fixed point numbers are not supported by the standard. Future versions of this standard may add new atomic types.

Definition: The dynamic types are bytes and string. These are like the atomic types for the purposed of type declaration, but their treatment in encoding is different.

Definition: The reference types are arrays and structs. Arrays are either fixed size or dynamic and denoted by Type[n] or Type[] respectively. Structs are references to other structs by their name. The standard supports recursive struct types.

Definition: The set of structured typed data 𝕊 contains all the instances of all the struct types.

Definition of hashStruct

The hashStruct function is defined as

  • hashStruct(s : 𝕊) = keccak256(typeHash ‖ encodeData(s)) where typeHash = keccak256(encodeType(typeOf(s)))

Note: The typeHash is a constant for a given struct type and does not need to be runtime computed.

Definition of encodeType

The type of a struct is encoded as name ‖ "(" ‖ member₁ ‖ "," ‖ member₂ ‖ "," ‖ … ‖ memberₙ ")" where each member is written as type ‖ " " ‖ name. For example, the above Mail struct is encoded as Mail(address from,address to,string contents).

If the struct type references other struct types (and these in turn reference even more struct types), then the set of referenced struct types is collected, sorted by name and appended to the encoding. An example encoding is Transaction(Person from,Person to,Asset tx)Person(address wallet,string name)Asset(address token,uint256 amount).

Definition of encodeData

The encoding of a struct instance is enc(value₁) ‖ enc(value₂) ‖ … ‖ enc(valueₙ), i.e. the concatenation of the encoded member values in the order that they appear in the type. Each encoded member value is exactly 32-byte long.

The atomic values are encoded as follows: Boolean false and true are encoded as uint256 values 0 and 1 respectively. Addresses are encoded as uint160. Integer values are sign-extended to 256-bit and encoded in big endian order. bytes1 to bytes31 are arrays with a beginning (index 0) and an end (index length - 1), they are zero-padded at the end to bytes32 and encoded in beginning to end order.

The dynamic values bytes and string are encoded as a keccak256 hash of their contents.

The array values are encoded as the keccak256 hash of the concatenated encodeData of their contents (i.e. the encoding of SomeType[5] is identical to that of a struct containing five members of type SomeType).

The struct values are encoded recursively as hashStruct(value). This is undefined for cyclical data.

Definition of domainSeparator

domainSeparator = hashStruct(tip104Domain)

where the type of tip104Domain is a struct named TIP104Domain with one or more of the below fields. Protocol designers only need to include the fields that make sense for their signing domain. Unused fields are left out of the struct type.

  • string name the user readable name of signing domain, i.e. the name of the DApp or the protocol.
  • string version the current major version of the signing domain. Signatures from different versions are not compatible.
  • uint256 chainId the chain id. The user-agent should refuse signing if it does not match the currently active chain.
  • address verifyingContract the address of the contract that will verify the signature. The user-agent may do contract specific phishing prevention.
  • bytes32 salt an disambiguating salt for the protocol. This can be used as a domain separator of last resort.

Future extensions to this standard can add new fields with new user-agent behaviour constraints. User-agents are free to use the provided information to inform/warn users or refuse signing.

Rationale

By adding the bytestrings with given prefix when signing, it's effective to prevent a malicious attacker from tricking the user to sign opaque bytestrings which
can be decoded as a transaction. Furthermore, to make the users be clear of of what message they have signed, we also includes the typed structured data processing method,
which can be more secure and convenient.

Test Cases

None

Implementation

None

TRC-37: Prohibit using TransferContract & TransferAssetContract for contract account

tip: 37
title: TRC-37: forbid using TransferContract & TransferAssetContract  for contract account
author: Taihao Fu <[email protected]>
discussions to: https://github.com/tronprotocol/TIPs/issues/37
category: TRC
status: accepted
created: 2019-05-10

Abstract

Forbidding transfer trx/trc10 to a contract account can avoid the misunderstanding of the transfer transaction would executing fallback function in smart contract.

Also avoid user misuse system transfer contract to send their asset to a contract and asset would probably be locked in a contract forever.

Motivation

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.

Specification

Add validate address logic in validate() function in TransferContract & TransferAssetContract. When the toAddress account type is Contract, throw a contract validate exception.

Rationale

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.

For contract , user should trigger fallback function in the specific contract for trx/trc10 token transferring purpose.

Backwards Compatibility

  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.

  2. tronlink or similar wallet should support a new transfer method to use bandwidth/energy to send trx/trc10 to the contract.

  3. dApp developer may need to change their migration script/ dApp script a little bit for contract asset injection.

  4. tronweb should do the similar change for contract asset injection.

TRC57: Allow burning TRX in deployer account for contract triggering energy payment

tip: 57
title: TRC57: Allow burning TRX in deployer account for contract triggering energy payment
author: Taihao Fu <[email protected]>
discussions to: https://github.com/tronprotocol/TIPs/issues/56
category: TRC
status: draft
created: 2019-09-17

Simple Summary

This doc present a new option for contract owner pay for their contract user energy consumption.

Abstract

Current design allow contract deployer/owner to to pay none/part/all energy fee for their customer which is a way to attract more customer to participate in their contract. However, only frozen energy is allowed for the payment. In current TRON network, frozen energy is expensive since the global frozen energy is raising. Some contract owner thought it is more convenient by simply consuming their TRX in their account for their customer rather than use “free" frozen energy which cost lot of frozen TRX to gain.

Motivation

Contract owner hope to use TRX burning mechanism directly for their user consumption.

Specification

  1. We have a parameter called consume_user_resource_percent which represent the percentage user should pay for the contract calling. The rest part is the target fee we would like to discuss in this TRC.
  2. In current design, only energy gain from frozen TRX in contract deployer account can be use to pay the developer side consumption.
  3. When the frozen energy is used up, we can implement a new logic to burn TRX in deployer’s account if the deployer willing to consume its TRX.

Advantages:

  1. Expensive frozen energy problem can be resolved.

  2. TRX burning can be a convenient way and a flexible way for deployer to set the strategy.

  3. It would be a good way to attract more customer for developer's contract.

Downsides:

  1. It’s unsafe. Anyone can trigger a fallback function without any punishment and deployer has to suffer from all the consequences(TRX consuming).

  2. We will break the law that nobody should let the TRX in someone else account to reduce. Now, this kind of attacking can not be avoid.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.