1. Why does the DAPP ecosystem need its own wallet function?

Blockchain is a great invention that has changed the relationship of production. Many ecosystems, with blockchain technology, can be changed from the “full partner” of the whole company to the “full partner” of the whole platform, which is a real sharing economy model.

What does that mean? For example, in many current Internet platforms, such as Taobao, ordinary consumers are only a contributor to the benefits of the platform. Whether the platform operates well or not has nothing to do with users. But on platforms with tokens, every user’s role has changed: they’re not just a user of a platform, they’re holding tokens. These tokens are generally limited. The more people use the platform, the stronger the demand for tokens will be. The supply and demand of tokens will tilt in the market, and the price will rise. So the user is actually on the same side as the platform. That is to say, in the age of + Internet, after improving the efficiency of information circulation by using Internet technology, consumers cultivated taobao, a unicorn platform, but the benefits were mainly enjoyed by Jack Ma’s team, who created a richest man in China, and the majority of users of the platform did not get the benefits of the growth dividend of the platform. However, in the + blockchain era, all users are stakeholders of the platform and entrepreneurs. They will benefit as the platform grows, and the power of the dream will grow. In the current DAPP business ecosystem, many projects do not come with their own wallets or exchanges. I think dApps-only wallet functionality will be a basic feature. 1) When there is no TOKEN economy in the ecosystem, the platform is solid. Who is the user and who is the ultimate beneficiary of the benefit platform is statically solidified. This is the general + Internet model. A large number of users have created BATJ and other unicorns, but they are always contributors and do not share more benefits from them. 2) When there are tokens in the ecosystem and the interests are changed through the exchange, I think the ecosystem is liquid. The exchange of benefits in the ecosystem can be converted through exchanges. However, it cannot be decentralized or disintermediated, and there are problems of inconvenience and being charged. In this mode, the self-circulation ecology of token economy cannot be formed. At the same time, due to the security of the assets of the exchange, the attack, the impact on the real financial ecology and other reasons, is banned by many countries. 3) When the ecosystem is not only TOKEN but also wallet, I think the blockchain ecosystem will transition to gas. In the gas phase, the exchange of tokens and assets is ubiquitous and very convenient. It is recognized that the management side and the user side of this platform form a self-circulation system, which effectively promotes the circulation of assets within the ecosystem.

In Huige’s view, DAPP wallet will be a standard feature of blockchain projects.

2. Classification of wallets

2.1 Differences between Ethereum Wallet, Geth, DAPP and Ethereum Wallet

1) Apps like Ethereum Wallet

The Ethereum Wallet client is the counterpart of the Mist project. Most of this client is now called Ethereum Wallet, and there is also the Mist Client, just know that they both refer to the same client. This client is developed using JavaScript and supports Windows, Linux and OSX operating systems. It is a client with graphical operating interface. At this point, it’s probably clear that if you want to call ethereum’s interface through an API, this option won’t work. The Ethereum Wallet client is a graphical user interface that allows users to create accounts, transfer money, and check balances. Ethereum Wallet client features: 1] Create an account 2] Exchange Ethereum: Built in exchange for Bitcoin, other competing coins and Ethereum 3] Deploy smart contracts: Token contract, crowd funding contract, autonomous organization contract, etc. 4] Ethereum currency transfer operation 5] Backup wallet and other functions all the above functions are operated through the operation interface or menu after starting the client program. The smart contract part needs to write the corresponding code in advance and distribute it through the client. Other standalone wallet apps include imToken.

2) Introduction to Geth wallet

Geth is the client for the Go-Ethereum project and is currently the most widely used client. Supports Windows, Linux, and OSX operating systems. For this system, there are a lot of information on the web for reference, github wiki documentation instructions are more detailed, [click to jump to the document address]. Basically all ethereum-related operations can be performed through this client.

1] Geth client main functions:

  • JavaScript Console: Command operations through the background;
  • Management API: management-related API;
  • Json-rpc server: JSON-RPC related call API You can perform related operations through the API or console, for example:
  • Account management (creating accounts, locking accounts, unlocking accounts, etc.);
  • Query account information.
  • Query trading information;
  • Query gasPrice;
  • Trade;
  • Mining & stopping mining;
  • Deploying smart contracts
  • And other related functions.

The Geth client can be used either through the docking API, which is commonly used by trading platforms today, or directly from the command line. Compared to Ethereum Wallet, there is no visual interface and it’s basically all done by command. The Geth wallet is part of the technical implementation of the Ethereum ecosystem and is not intended as an application wallet for end user use.

3) Introduction of wallet in DAPP

DAPP wallet is a mobile App or web version wallet developed on the basis of Geth, such as the wallet with ColorBay token transfer function provided by the Caibei App account. The wallet is attached to the Caibei APP and cannot exist independently.

2.1 Differences between centralized wallet and decentralized wallet

According to the location of private key storage, it can be divided into two categories: 1) wallets with centralized private key storage, such as huobi wallets; 2) Decentralized wallet, private key stored in the client, such as IMtoken wallet, color shell wallet.

1) Decentralized wallets

Decentralized wallets are not the focus of this section, so here is a brief introduction. No matter the centralized wallet or the decentralized wallet, it is very lightweight at the App level. There is no BUILT-IN Geth node in the App, and the transaction query or sending is operated through the server. The difference is who keeps and is responsible for the private key of the transaction signature. Decentralized wallets have a key word: mnemonics. The following expression can be used to describe the use of mnemonic words:

Private key = mnemonic = keystore+ passwordCopy the code

From the above formula, we can see the important role of mnemonic words, which is also a bright spot of the de-centered wallet function. When an account is created in such a wallet, the wallet will generate a set of mnemonics (English or Chinese) based on the generated private key file. The mnemonics can be used to reverse calculate the keystore + password. The mnemonic is handwritten by the user and stored in a secure place. When a transaction is made, the mnemonic is entered to sign the transaction and send the transaction. When the mnemonic is lost, it means that the private key is lost, and wallets generally do not hold the user’s private key information, and the asset is permanently lost. The advantage of the decentralized wallet is that there is no need to worry about the platform interfering, and there is no need to worry about the platform being hacked and resulting in asset loss, but individuals are required to have certain private key storage ability.

2) Central wallet

The so-called centralized wallet is to store all the private key files in the server of the wallet service provider, and the service provider takes care of these private key files. That is to say, the assets belong to you, but the private key is not in your custody. The advantage of this is that the user does not need to remember the private key at all, only the account created on the platform, login password and payment password. Even if you forget your password, you can still retrieve it through the forgotten password provided by the platform, which, of course, does not have the advantages of a decentralized wallet. Color shell wallet belongs to the centralized wallet attached to color shell ecology, helping color shell community to complete the closed loop ecological construction of token economy.

3. Core functions of wallet

Wallet may have different functions for external presentation, such as recharge, withdrawal, transfer, etc., but in essence, there is only one function, that is transfer. A blockchain is essentially a ledger, a record of transactions, and a wallet can’t live without it. 1) Recharge is a transfer from the external account of the wallet to the address of the wallet; 2) Withdrawal is a transfer from the wallet’s account to an address other than the wallet; 3) The transfer function includes mutual transfer to the address inside the wallet and transfer to the address outside the wallet; In this process, it also corresponds to the increase and decrease of wallet account funds.

3.1 How do I Assign User Addresses

The user must have an address on the blockchain corresponding to the current account when using the wallet. How to generate this address? Many developers implement this by calling the Geth node’s personal_newAccount method to generate an address each time a user registers and storing the address in the default location of the Geth node. This can be done, but technically and securely it is not desirable. One of the performance bottlenecks is that calling a Geth node to generate an address is very time consuming, especially if the node is doing some synchronous or high-consumption work. The second performance bottleneck is that as the number of private keys under the Geth node increases, Geth starts to take a long time. Security problem: Geth nodes broadcast transactions and store sensitive private key information. ** Optimized after the approach is to generate the address in batches in advance, when the user registration only to assign the address to the user. ** The advantages of this method are as follows: The storage of the private key is isolated from the Geth node to ensure the isolation of the private key from the Internet, thus ensuring the security of the private key; The performance guarantee is that when the user registers, the data in the database is only established by an association, without having to perform time-consuming encryption algorithms to generate private keys and files. This method of generating Web3j provides the corresponding creation method, which can directly generate the private and private keys in accordance with the private key rules through the code without Geth node. Of course, if you have the ability to develop the Geth source code can also be extracted from the private key generation method out of a separate and network independent production of private key program.

3.2 Top-up transaction

In the bitcoin wallet, there is the concept of sub-accounts. Only N sub-accounts need to be created under a total account. The bitcoin that the user has charged to this sub-account will also be displayed on the wallet, and at the same time, it provides a method to query all transactions at an address. Unfortunately, Ether currency does not provide such an interface, so it can only judge whether there are top-up transactions of corresponding accounts by traversing block transactions. Related operations: 1) Query the block height and check whether it is a newly generated block (eth_blockNumber); 2) Check block content and transaction details, eth_gethBlockByNumber; Compare whether the toAddress of the transaction is the address of the wallet, if so, record the transaction to the database, and record the transaction status (pending, confirm times, etc.); 3) Ensure idempotency of warehousing and bookkeeping, because the same transaction will be queried many times. 4) The number of confirmations does not mean that the transaction has been successful when we query the transaction in the blockchain. Bitcoin is confirmed 12 times by default, after which the transaction will almost not be tampered with. Ethereum is confirmed 6 times by default, so how to calculate the number of confirmations?

Confirmations = current block height – exchange in block height + 1

Note here: Transactions can be isolated, and the formula needs to be executed to verify that the transaction in the block is still on that block and has been rolled back. Similarly, idempotent protection should be done.

3.3 Withdrawal transactions

Cash withdrawal deals with the same points mentioned above, but with additional considerations. Check the validity of withdrawal address, refer to the verification in the source code, this validity check can avoid many subsequent problems, such as the maintenance of the Nonce value. Transaction amount check, nonce value check, especially when the private key is separated from the Geth node to maintain the nonce value will be a big problem, for example, the previous transaction failed, the nonce value needs to be back, at this time, the next transaction has been sent, because the previous nonce has not been completed. The latter will not be traded. All these require special judgment and processing by the business. Query an address nonce, eth_getTransactionCount.

3.4 Withdrawal and transfer

Both withdrawals and transfers initiate a transaction, and it is mentioned in Ethereum’s JSON-RPC that transfers can be made directly through eth_sendTransaction and personal_sendTransaction, which are supported by the Geth node. Before transferring money, you can use unlock to unlock your account, as mentioned in the previous section. However, for the private key stored separately, the above method is not applicable, the transaction can be signed first and then broadcast mode:

  • Signed transactions (can be developed independently, using the node itself), eth_sign.
  • Broadcast transactions, which can be broadcast through eth_sendRawTransaction.
  • The internal transfer of wallet is just the from and to addresses are wallet addresses, and the business layer handles it appropriately. In this mode, the node interacts with the outside world, and the only function is to broadcast transactions. All operations before this can be carried out through the Intranet, which greatly ensures the security of private keys and transactions.

For more, see the Go-Ethereum GETH Wallet [RPC,API] link on the official website.

4. Realize WEB WALLET WALLET allocation and transfer function

4.1 Introduction to library modules

To create a DAPP wallet or A PC WEB wallet, you need to implement functions on the basis of Geth. This chapter introduces two library modules to reduce the difficulty of wallet implementation.

4.4.1 Hooked – web3 – Provider module

The Hooked web3-Provider module library provides a custom Provider that communicates with GETH using HTTP. This provider is unique in that it allows the sendTransation() call to the contract instance to be signed using the key, so there is no need to create the data part of the transaction. The custom provider actually overwrites the implementation of the web3.eth.sendTransaction() method, so basically it allows the sendTransaction() call to sign the contract instance as well as the web3.eth.sendtransation () call. The sendTransaction() method of the contract instance generates the transaction data internally and calls web3.eth.sendTransation() to broadcast the transaction.

4.1.2 LightWallet module

LightWallet is a HD wallet that implements BIP32,BIP39 and BIP44. LightWallet provides apis to create and sign transactions, or to encrypt and decrypt data using lightwallet-generated addresses and keys. The LightWallet API is split into four namespaces, namely keystore, Signing, Encryption, and Txutils. Signing, encrpytion, and Txutils are used to provide apis for signing transactions, asymmetric passwords, and creating transactions respectively, while the keystore namespace is used for creating keystores, generating seeds, and more. A keystore is an object that stores an encrypted seed and key. If Hooked- web3-provider is used, the keystore namespace implements the transaction signer method, which requires the we3.eth.sendTransation() call to be signed. Therefore, the keystore namespace can automatically create and sign transactions for addresses found in it. In fact, LightWallet’s main goal is to be a signature Provider for Hooked-Web3-Provider. Key store instances can be configured to create and sign transactions or to encrypt and decrypt data. Secp256k1 is used for signing transactions and curve25519 is used for encryption and decryption. LightWallet’s seed is a 12-word mnemonic that is easy to remember but hard to crack. It’s not just any 12 words, but a seed generated by LightWallet. The seeds generated by LightWallet have specific properties in terms of selecting words and other things.

4.2 Introduction to key codes

This environment code was successfully tested on the Ubuntu VIRTUAL machine of Whigo. If you do not know how to install an Ubuntu VM, please refer to the article “How to Build an Ethereum Development Environment on WINDOWS” to complete the configuration.

4.2.1 Code structure analysis

The WebWallet directory mainly contains the following files and directories. The function description of each directory is explained as follows: │ ├─ Node_modules-nodeb.js WebWallet │ package.json – App object │ ├─ Node_modules-nodeB.js │ ├─ public ├─ CSS │ ├─ HTML │ index.html – Front page │ ├─ ├─ CSS │ ├─ public ├─ CSS │ ├─ HTML │ ├─ javascript Bible-web3-provider.min.js -Format a readable file named “bible-web3-provider.min.js”. Module.module.js – From a major hooked web3-provider.min.js – From a major hooked web3-provider lightwallet Format readable “lightwallet.min.js” file lightwallet.min.js – implementation of lightwallet library file main.js – This case to achieve the main function web3.min.js -web3.js implementation file

4.2.2 Key code interpretation

The key implementation code is in the main.js file. 1, generate_seed function code

function generate_seed() {/ * have * 12 word mnemonic word/var new_seed = lightwallet keystore. GenerateRandomSeed (); document.getElementById("seed").value = new_seed; /* Generate wallet addresses */ generate_addresses(new_seed); }Copy the code

Generate_seed function function: call lightwallet function to generate seed mnemonic, generate wallet address.

2, generate_addresses function code

function generate_addresses(seed)
{
	if(seed == undefined) {/* Seed = document.getelementByid ("seed").value; } /* Determine if it is a valid mnemonic */if(! lightwallet.keystore.isSeedValid(seed)) { document.getElementById("info").innerHTML = "Please enter a valid seed";
		return; } /* How many addresses need to be generated */ totalAddresses = prompt("How many addresses do you want to generate"); /* Get the number of addresses */if(! Number.isInteger(parseInt(totalAddresses))) { document.getElementById("info").innerHTML = "Please enter valid number of addresses";
		return; } /* Generate a random password */ var password = math.random ().tostring (); / * create and display the address, the private key and account balances. * / lightwallet keystore. CreateVault ({password: password, seedPhrase: seed}.function(err, ks) {/* Generate a Uint8 array of symmetric keys for encrypting and decrypting keystore*/ ks.keyfromPassword (password,function (err, pwDerivedKey) {
	    	if(err)
	    	{
	    		document.getElementById("info").innerHTML = err;
	    	}
	    	else{/* Generate totalAddresses/private key pairs in the keystore with the seed mnemonic password. This address/private key pair returns */ ks.generatenewAddress (pwDerivedKey, totalAddresses) via the ks.getaddresses () function call; var addresses = ks.getAddresses(); / * 【 note 】 in order to be kept in other PC browser can access, IP here to change to the GETH surroundings of the UBUNTU IP * / / / var web3 = new web3 (new web3. Will. HttpProvider ("http://localhost:8545"));
	    		var web3 = new Web3(new Web3.providers.HttpProvider("http://192.168.0.106:8545"));

	    		var html = ""; /* Assembles the address/private key pair into HTML to display */for(var count = 0; count < addresses.length; count++) { var address = addresses[count]; /* Generate a private key based on the address and pwDerivedKey */ var private_key = ks.exportPrivateKey(address, pwDerivedKey); /* getBalance */ var balance = web3.eth."0x" + address);

					html = html + "<li>";
					html = html + "<p><b>Address: </b>0x" + address + "</p>";
					html = html + "<p><b>Private Key: </b>0x" + private_key + "</p>";
					html = html + "<p><b>Balance: </b>" + web3.fromWei(balance, "ether") + " ether</p>";
		    		html = html + "</li>";
	    		}

	    		document.getElementById("list").innerHTML = html; }}); }); }Copy the code

Generate_seed generates the account address according to the mnemonic and the number of addresses needed, and displays it. Lightwallet implements the same SEED to generate the same account address.

3. Send_ether function code

function send_ether()
{
	var	seed = document.getElementById("seed").value; /* Does seed work? * /if(! lightwallet.keystore.isSeedValid(seed)) { document.getElementById("info").innerHTML = "Please enter a valid seed";
		return;
	}

	var password = Math.random().toString();

	lightwallet.keystore.createVault({
		password: password,
	  	seedPhrase: seed
	}, function(err, ks) {/* Generate a Uint8 array of symmetric keys for encrypting and decrypting keystore*/ ks.keyfromPassword (password,function (err, pwDerivedKey) {
	    	if(err)
	    	{
	    		document.getElementById("info").innerHTML = err;
	    	}
	    	else
	    	{
	    		ks.generateNewAddress(pwDerivedKey, totalAddresses);

	    		ks.passwordProvider = function(callback) { callback(null, password); }; /* [note] In order to be accessible in other PC browsers, */ * Create HookedWeb3Provider. Reference https://www.npmjs.com/package/hooked-web3-provider * / / * * var provider = new HookedWeb3Provider ({host:"http://localhost:8545",
  					transaction_signer: ks*/
  				var provider = new HookedWeb3Provider({
  					host: "http://192.168.1.135:8545", transaction_signer: ks }); / * web3 HookedWeb3Provider as the object, is different from the pet store new web3. Will. HttpProvider ('http://localhost:8545'); */ var web3 = new Web3(provider); var from = document.getElementById("address1").value;
				var to = document.getElementById("address2").value;
			    var value = web3.toWei(document.getElementById("ether").value, "ether"); SendTransaction ({from: from, to: to, value: value, gas: 21000},function(error, result){
			    	if(error)
			    	{	
			    		document.getElementById("info").innerHTML = error;
			    	}
			    	else
			    	{
			    		document.getElementById("info").innerHTML = "Txn hash: "+ result; }}}})); }); }Copy the code

Function description of the send_ether function: This function transfers ETH. In order to run the code on your test machine, be sure to change the IP address to the IP address of the machine where the code resides.

5. Functional test of WEB WALLET

Because the screen of the Ubuntu VM configured on the local PC is relatively small, Xshell 4 is used to log in to the VM using SSH and the local Windows Chrome browser is used to demonstrate this method. You can also operate directly on Ubuntu to complete. The IP address of the Ubuntu machine is 192.168.1.135. The two IP addresses of main.js are also changed to 192.168.1.135, and updated to the Ubuntu working directory. After starting the Ubuntu remote connection, window input commands are used to run the GETH environment.

Geth –dev — RPC — rpccorsDomain “*” — rpcADDR “0.0.0.0” –rpcport “8545” –mine –unlock=0 –datadir testNet console 2>> test.log

For a brief explanation of the GETH command parameters, refer to the article “Lesson 5 GETH Command Usage of ethereum client – Detailed Explanation of the parameters”. –dev: start the development environment; 2) — RPC means http-RPC server enabled; 3) — rpcCorsDomain “*” is used to allow some specific domains to communicate with GETH. * Wildcard indicates that you can communicate with any domain name. 4) — rpcADDR “0.0.0.0” indicates which IP address the GETH server can reach. The default is 127.0.0.1. Change its value to 0.0.0.0, which means that the server can be reached using any IP address. 5) –rpcport “8545” means HTTP-RPC server listening port (default :8545) 6) –mine means open mining 1) –unlock=0 geth default created account 0 After the command is started, the system prompts Passphrase:. Press Enter and enter the empty password to unlock account 0. After the success of the operation, enter “eth. Accounts” can see the geth automatically create a default account address is “0 x5eaba24091f993917fb35188add523c501dc1354”.

5.2 Starting the APP Service

Open a new window link in XShell 4, go to the Whigo project directory ~/work/WebWallet, and then start this APP.

node app.js

The operation screenshot is as follows:

5.3 Basic Functions of the Web Wallet

1. Open the WEB wallet url

2. Click “Generate New Seed” to Generate a Seed

  1. SEED:obtain warm allow bicycle mushroom fiber shell tower twenty corn cherry close
  2. Address1: 0xe45d865ed260fdf2409f66d4a9499a664943079c
  3. Address2: 0x09da12a3c1e0675c29e14967a3be765b008205e4

3. Send ETH to the target address back to the GETH environment, and add 100 ETH from the system account[0] to the target account address.

eth.sendTransaction({from: ‘0x5eaba24091f993917fb35188add523c501dc1354’, to: ‘0xe45d865ed260fdf2409f66d4a9499a664943079c’, value: web3.toWei(100, “ether”)})

The operation screenshot is as follows:

4. View the target ADDRESS information

5. In-wallet account transfers

At this point, the DAPP application, why the need for wallet function, wallet function classification, a demonstration of the basic wallet to achieve the basic explain clearly. For more information, please refer to the interface documentation and instructions on the official website. We have opened a block chain entry column on Knowledge Planet, which is used to store the project source code and other contents. We have also established a special wechat group for technical exchange. Welcome to join us.

7. Reference materials

1, ethereumjs – tx www.npmjs.com/package/eth… Github code: github.com/ethereumjs/… 2, hooked – web3 – provider www.npmjs.com/package/hoo… Github code: github.com/consensys/h… 1) ETH Web: github.com/ConsenSys/e… 2). The android: github.com/walleth/wal… 3.) IOS: github.com/ethers-io/E… 4, web3.js complete documentation github.com/ethereum/wi… Github.com/ethereum/we WEB3. JS code… 5, Go-Ethereum GETH Wallet [RPC,API] github.com/ethereum/go… 6, the development of Ethernet fang purse blog.csdn.net/u011494083/… Blog.csdn.net/u011494083/… Github.com/ethereum/wi… 7, Lesson 08: Basic ideas and security for developing Ethereum Wallets [Good point on centralized and decentralized wallets] blog.csdn.net/su_bo_2010/… 8, the etheric fang client Ethereum Wallet with the Geth distinction introduction blog.csdn.net/wuxianbing2… 9 [the etheric fang source code analysis] v. blog.csdn.net/teaspring/a from the wallet to the client… Ethereum Wallet Parity Alliance chain from scratch ke.qq.com/course/2546… 11, based on the analysis of the etheric fang electronic wallet development mp.weixin.qq.com/s/YQNlYozCv… 12. Blockchain Project Development Guide – Narayan Prusty[India] 13, BIP32,BIP39 Protocol – About HD Wallet and Mnemonic seed specification github.com/bitcoin/bip… 14, formatting JS tools tool.oschina.net/codeformat/… 15, Lesson 03: Ethereum common JSON-RPC interface parsing blog.csdn.net/su_bo_2010/…