In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "what is the development method of ethernet square Dapp". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "what is the development method of ethernet square Dapp"!
1. Block chain 1. Distributed decentralization
Bitcoin is designed to avoid relying on centralized institutions. There are no issuers and it is impossible to manipulate the number of issues. Since there is no centralized credit institution, in the process of the operation of electronic money, there is bound to be a mechanism to recognize the behavior running on the blockchain (including the operation of bitcoin, or other business running on the blockchain). This mechanism is the consensus mechanism. Bitcoin, which runs on a completely decentralized blockchain, uses PoW (Proof of Work, proof of workload), a mechanism that perfectly solves the Byzantine problem (it can still be agreed in the presence of anomalies). Because the basic network architecture is distributed, it is impossible to control or destroy the entire network for a single node, and it is possible to operate transactions only if you master 51% of the computing power (non-nodes) in the network, and the cost is probably more than $27 billion.
two。 No need to trust
The data in the whole blockchain network is open and transparent, and each node (participant) is free to join the network and download all the data. The data exchange between any two nodes does not need to trust each other, and completely depends on the transaction history and data traceability in the block chain, as well as the consensus mechanism to ensure the correct and irreversible execution of the data exchange.
3. Immutable and encrypted security
Similar to the encryption mechanism of the current bank online banking system (especially the corporate online banking system), the data structure of the block chain and the transaction process use a large number of public and private keys to encrypt and decrypt to ensure the security of the data. Based on this technology, group signature can even be used to ensure the security of common data. Since anything has its advantages, it also has its inadequacies. Rooted in the distributed network architecture and consensus mechanism, the transaction confirmation time running on the blockchain is relatively long (the confirmation time of Bitcoin is about 15 minutes), and the number of concurrent transactions is limited (7 transactions per second on Bitcoin. Taobao's concurrency per second can reach about 100000), block capacity limit (currently 1m, the expansion of the blockchain has been discussed), it is difficult for regulation to intervene The consensus mechanism based on workload proof has the problem of wasting system resources and bandwidth.
4. Block chain technology a. block
A block is a container that aggregates transaction information contained in the blockchain (public ledger). It consists of a block containing metadata followed by a long list of transactions that form the body of the block. The block size is 80 bytes, while the average per transaction is at least 250 bytes, and the average block contains at least 500 transactions. The block structure is as follows
The structure in the transaction (Tx) details is as follows
b. Block chain
When a node receives incoming blocks from the network, it validates those blocks and then links them to the existing block chain, as shown in the following figure:
Since each block contains the hash value of the previous block, a chain of blocks is formed from the creation block to the current block, and each block must follow the previous block in chronological order, because the current block cannot be generated if you do not know the hash value of the previous block. It is not computationally feasible to change a block that has been in the block chain for some time, because if it is changed, each block after it must change accordingly. These features make Shuanhua Bitcoin very difficult, and blockchain is the biggest innovation of Bitcoin.
5. Bitcoin wallet a. Generation of Bitcoin Wallet
First, a private key is generated using a random number generator. Generally speaking, this is a 256bits number, and with this string of numbers, you can manipulate the bitcoin in the corresponding wallet address, so it must be saved securely.
The private key is processed by the SECP256K1 algorithm to generate the public key. SECP256K1 is an elliptic curve algorithm. The public key can be calculated through a known private key, but the private key can not be calculated backwards when the public key is known. This is the algorithmic basis for ensuring the security of Bitcoin.
Like SHA256, RIPEMD160 is a Hash algorithm, and the public key hash can be calculated from the public key, but the reverse is not feasible.
Connect the address version number of one byte to the public key hash header ("0" for the pubkey address of the bitcoin network), then perform two SHA256 operations on it, and connect the first 4 bytes of the result at the end of the public key hash as the check value of the public key hash.
Encode the result of the previous step using BASE58 (a custom version of Bitcoin), and you get the wallet address.
The flow chart is as follows
B. Transfer
Transfer between Bitcoin wallets is done through Transaction. The transaction data is generated by the owner of the private key of the wallet, which means that with the private key, the Bitcoin balance of the wallet can be spent. The process of generating a deal is as follows:
The original data for the transaction include "transfer amount" and "transfer wallet address", but these alone are not sufficient because it is not possible to prove that the creator of the transaction has a right to the balance of the "transfer wallet address". So you need to sign the original data with the private key.
Generate the transfer wallet public key, which is the same process as step 2 of generating the wallet address.
The "transfer signature" and "transfer public key" are added to the original transaction data to generate the formal transaction data, so that it can be broadcast to the bitcoin network for transfer.
Second, ethernet square ethereum1. Concept a. What is Tai Tai Fong?
To put it simply, Yi Tai Fong is a new form of law. The essence of the current law is a contract. It is concluded between people (who live in a community) and their leaders, a consensus on how each other should act. There are also some contracts between individuals, which can be understood as a kind of private law, which correspondingly takes effect only for the participants in the contract.
For example, you enter into a contract with a person and lend him a sum of money, but he finally breaks the contract and does not intend to repay the money. At this point, you will probably take the other party to court. In real life, litigation is often chaotic and full of uncertainty. Taking the other person to court also usually means that you have to pay a high fee to hire a lawyer to help you argue the provisions of the law in court, and the process is usually long. Moreover, even if you eventually win the case, you may still encounter problems (for example, the other party refuses to enforce the court decision). The good news is that you wrote down the terms and entered into a contract with the borrower. But both the makers of the law and the drafters of the contract must face a challenge that cannot be ignored: ideally, the content of the law or contract should be clear and unambiguous, but the current law and contract are made up of sentences, which are notoriously ambiguous. Therefore, there have always been two huge problems in the current legal system: first, contracts or laws are defined by ambiguous statements, and second, the cost of enforcing contracts or laws is very high. Etay Fong, through the combination of digital currency and programming language, has solved these two major problems in the current legal system. The ethersquare system itself comes with a digital currency called Ether. Ethercoin and the famous digital currency Bitcoin have a lot in common. Both are digital stored-value currencies, which cannot be forged, and both operate in a decentralized way to ensure that the money supply is not controlled by one party. Both can circulate freely around the world as money, like e-mail. And because they can do things that traditional currencies cannot, users are looking forward to their future value.
In addition: 1. For details, please read the Etay Square White Paper (Chinese, English). two。 Ethernet workshop course
b. Basic knowledge
Public key encryption system. Alice has a public key and a private key. She can use her private key to create a digital signature, and Bob can use her public key to verify that the signature is indeed created with Alice's private key, that is, it is indeed Alice's signature. When you create an ethernet place or a bitcoin wallet, the long 0xdf...5f address is essentially a public key, and the corresponding private key is stored somewhere. An online wallet similar to Coinbase can help you keep your private key, or you can keep it yourself. If you lose the private key of your wallet with money, you will lose that money forever, so you'd better make a backup of the private key.
Peer-to-peer network. Like BitTorrent, all nodes in the Ethernet Square distributed network are of equal status and have no central server.
Block chain. Blockchain is like a global only account book, or database, that records the history of all transactions in the network.
Ethernet Square Virtual Machine (EVM). It allows you to write more powerful programs on Ethernet Square (script programs can also be written on Bitcoin). It is also sometimes used to refer to the etheric block chain, which is responsible for the execution of smart contracts and everything.
Node. You can run the node to read and write the ethernet block chain, even for the Taifang virtual machine. The full node needs to download the entire block chain. The light node is still under development.
Miners. Mining, that is, dealing with the nodes of the blocks on the block chain. This page can see the currently active part of Yi Tai Fong miners: stats.ethdev.com.
Proof of workload. Miners are always competing to solve some math problems. The first person to work out the answer (to figure out the next block) will be rewarded with Ethernet coins. Then all nodes update their own blockchain. All miners who want to figure out the next block have the motivation to keep pace with other nodes and maintain the same block chain, so the whole network can always reach a consensus. (note: Etay Fong is planning to switch to a miner's entitlement proof system (POS), but that is beyond the scope of this article.)
Etheric coins. Abbreviated ETH. A real digital currency that you can buy and use. Here is a chart of one of the exchanges where etheric currencies can be traded. At the time of writing, one etheric coin was worth 65 cents.
Gas. It takes a certain amount of etheric currency to execute the program and save the data in the etheric place. Gas is converted from etheric currency. This mechanism is used to ensure efficiency.
DApp. The etheric community calls applications based on smart contracts decentralized applications (Decentralized App). The goal of DApp is (or should be) to give your smart contract a friendly interface, plus something extra, such as IPFS (a decentralized network that can store and read data, not from the ethernet team but with a similar spirit). DApp can run on a centralized server that can interact with Ethernet Fong nodes, or it can run on any of the Ethernet Fong equal nodes. Here we share an ethernet DApp tutorial, which can efficiently learn how to develop a DApp, which is very suitable for getting started.
two。 Workflow a. Environment building
It is recommended to use the Mac OS environment, otherwise various pits may occur.
Install NodeJS, install Python.
Install testrpc (for use in the test environment) and install go-ethereum (for real-world use).
Install solc.
Install truffle.
If it is windows, it is recommended to use the tool ethbox to install the tools of the ethernet development environment: ethbox
B. brief introduction of Solidity language
The following is a sample code about intelligent voting contracts on the official website
Contract Ballot {/ / A voter's constructor struct Voter {uint weight; / / weight (that is, how many votes he can vote) bool voted; / / whether he has voted address delegate; / / represents the address (he can vote for someone) uint vote / / index of the voted proposal} / / the constructor of the voting proposal struct Proposal {bytes32 name; / / proposal name uint voteCount; / / number of votes obtained} address public chairperson;// meeting Chairman / / address-voter's map mapping (address = > Voter) public voters; / / dynamic array of voting types Proposal [] public proposals / / Constructor function Ballot (bytes32 [] proposalNames) {chairperson = msg.sender;// initialization meeting Chairman [chairperson] .weight = 1; / / initialize all proposal for (uint I = 0; I
< proposalNames.length; i++) { proposals.push(Proposal({ name: proposalNames[i], voteCount: 0 })); } } // 给予投票权 function giveRightToVote(address voter) returns (bool b) { if (msg.sender != chairperson || voters[voter].voted) { //对于会议主席和已经投过票的选民这里不处理 return false;; } voters[voter].weight = 1; return true; } /// 投票权转移函数 function delegate(address to) { // 投票权转移的发起人 Voter sender = voters[msg.sender]; if (sender.voted) throw; //递归找到没有转移投票权的 选民 while ( voters[to].delegate != address(0) && voters[to].delegate != msg.sender ) { to = voters[to].delegate; } if (to == msg.sender) { throw; } //将发起人设置为已经投过票的状态 sender.voted = true; //将代表设置为刚才递归获取的选民 sender.delegate = to; Voter delegate = voters[to]; if (delegate.voted) { //如果代表已经投过票就在他投票的提案的票数增加 proposals[delegate.vote].voteCount += sender.weight; } else { //将代表的的票数增加 delegate.weight += sender.weight; } } /// 投票函数 function vote(uint proposal) { Voter sender = voters[msg.sender]; if (sender.voted) throw; sender.voted = true; sender.vote = proposal; //将投的提案票数增加 proposals[proposal].voteCount += sender.weight; } ///获得票数最多的提案 function winningProposal() constant returns (uint winningProposal) { uint winningVoteCount = 0; for (uint p = 0; p < proposals.length; p++) { if (proposals[p].voteCount >WinningVoteCount) {winningVoteCount = propositions [p] .voteCount; winningProposal = p;}
Unscramble
Address. Address type. Chairperson is the wallet address of the chairman of the meeting. This address is assigned in the contract constructor function Ballot (). Many times this kind of address is also called 'owner''.
Public. This keyword indicates that the variable can be used by objects other than the contract. The private modifier means that the variable can only be used by objects in this contract (or derivative contract). If you want to use a variable in the contract through web3.js in the test, remember to declare it as public.
Mapping or array. Mapping (address = > Voter) is the key-value pair of the voter wallet address and the voter construct. Proposal [] public proposals is an array of proposal constructs.
There are special variables and functions that are always present in the global namespace and are mainly used to provide information about blockchain, such as msg,block,tx, where msg.sender is the address of the initiator.
You can read the official documentation for a deeper understanding of the solidity language.
c. Deploy contracts using geth
Start a test node
Geth-testnet-fast-cache=512-genesis CustomGenesis.json console
The CustomGenesis.json here is to assign Ethernet coins to the tested accounts.
{"coinbase": "0x0000000000000000000000000000000000000000", "difficulty": "0x20000", "extraData": "," gasLimit ":" 0x2fefd8 "," nonce ":" 0x0000000000000042 "," mixhash ":" 0x0000000000000000000000000000000000000000000000000000000000000000 "," parentHash ":" 0x0000000000000000000000000000000000000000000000000000000000000000 "," timestamp ":" 0x00 "," alloc ": {" 0xe49c283bc6bf92c5833cc981b97679238dd3b5da ": {" balance ":" 11111111100000000000000000000000 "} "0xd8927c296b3ebe454a6409770a0c323ec4ed23ba": {"balance": "2222222220000000000000000000000000000000"}}
Replace the content under solc with the address of your test account. For more information on the use of geth, please see the official documentation and source code introduction.
Use solc to compile the smart contract and get the binary code such as the following code
Contract test {function multiply (uint a) returns (uint d) {return a * 7;}}
Enter in geth
Source = "contract test {function multiply (uint a) returns (uint d) {return a * 7;}}"
ClientContract = eth.compile.solidity (source) .test
The JSON format of the result returned by the compilation is as follows
Among them
Code: compiled EVM bytecode
Info: the metadata returned by the compiler
AbiDefination:Application Binary Interface definition. For specific interface rules, please see here.
CompilerVersion: the solidity compiler version in which this code was compiled
DeveloperDoc: Natural Specification Format for developers, similar to Doxygen
Language: contract language
LanguageVersion: contract language version
Source: source code
UserDoc: the Natural Specification Format for the user's Ethereum.
The JSON structure returned by the compiler reflects two different paths to contract deployment. Info information really exists in the zone-centric cloud, as metadata information to publicly verify the implementation of the contract code in Blockchain. The code information is deployed to the blockchain by creating a transaction.
Before you get a binary deployment contract, make sure you have an unlocked account and a balance in the account before you use solc to compile the smart contract, as etheric currency will be consumed during the deployment contract. Enter web3.fromWei (eth.getBalance (eth.accounts [0]), "ether") to view the account balance. Unlock an account
Personal.unlockAccount (eth.accounts [0])
Get an account
PrimaryAddress = eth.accounts [0]
Define an abi (abi is an array of js, otherwise unsuccessful)
Abi = [{constant: false, inputs: [{name: 'asides, type:' uint256'}]}]
Create a smart contract
MyContract = eth.contract (abi)
Send deal deployment contract
Contract = MyContract.new ({from: primaryAddress, data: "0x6060604052602a8060106000396000f3606060405260e060020a6000350463c6888fa18114601a575b005b6007600435026060908152602090f3"})
If the transaction is pending, as shown in the figure, your miner is not mining.
Start a miner miner.setEtherbase (eth.primaryAddress) / / set up a mining account miner.start (8)
Eth.getBlock ("pending", true). Transactions found that the transaction was already in the block.
However, you will find that the transaction is still pending, because there is no one to assist in the operation verification in the trading block, so you only need to start one more miner to miner.start (8).
Interact with the contract
Multiply7 = eth.contract (clientContract.info.abiDefinition); var myMultiply7 = Multiply7.at (contract.address); myMultiply7.multiply.call (3) or myMultiply7.multiply.sendTransaction (3, {from: contract.address})
d. Use the truffle framework
To deploy a smart contract using truffle:
Truffle init (in the new directory) = > create the truffle project directory structure
Write the contract code and save it to contracts/YourContractName.sol file. For example, Ballot .sol, to find the migrations folder, add deployer.deploy (Ballot) to the deploy_contracts.js file
Truffile compile compiles the contract code.
Start the Ethernet Fong node (for example, run testrpc in another terminal).
Truffle migrate (in the truffle project directory).
1. Write unit tests
Create a new ballot.js file in the test folder
Contract ('Ballot',function (accounts)) {/ / accounts is the it of all accounts ("get voting rights", function () {var meta = Ballot.deployed (); return meta.giveRightToVote (accounts [1]). Then (function (b) {assert.equal (Boolean (b), true, "failed to get voting rights");})
Run truffle test under the root of the project, and you should see that the test passes. If you use the ballot object you constructed, you can write:
Contract ('Ballot',function (accounts)) {/ / accounts is the it ("get voting rights", function () {var proposals = []; proposals.push ("proposal0"); Ballot.new (proposals) .then (function (meta) {return meta.giveRightToVote (accounts [1]) .then (function (b) {assert.equal (Boolean (b), true, "failed to get voting rights") });})
The etheric currency is sent in the contract. This is the address of the contract instance to check the balance of this address next (or use this.balance directly)
When you call a transaction function through web3.js (using web3.eth.sendTransaction), the transaction is not executed immediately. In fact, the transaction is submitted to the miner's network, and the transaction code is not executed until one of the miners creates a new block to record the transaction into the blockchain. So you must wait for the transaction to enter the blockchain and synchronize back to the local node before you can verify the result of the transaction execution. Using testrpc may seem real-time, because the test environment is fast, but the formal network is slow.
Gas. (translation note: the fuel on Tai Fong, because the execution of the code must consume Gas. The literal translation of gasoline is more abrupt, so the original text is retained as a proper noun. Until now, we have not covered the concept of Gas, because explicit settings are not usually required when using testrpc You will need it when you turn to geth and the official network. In the transaction function call, you can set the Gas parameter in the {from: _, value: _, gas: _} object. Web3.js provides a web3.eth.gasPrice call to get the current Gas price, and the Solidity compiler also provides a parameter that allows you to get a summary of the contract's Gas overhead from the command line: solc-- gas YouContract.sol.
two。 Create an interface for the contract
In the app directory, you can write your own html and js files, and the interaction between js and smart contracts is basically the same as unit tests, such as an interface with an input box and a button to get voters' right to vote.
Ballot App Ballot Example Truffle Dapp
Send
Account:
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.