The new version of the Ethereum library ethersV5.0 cooperates with the backend Golang1.18 to link the blockchain wallet (Metamask/Okc) and verify the signature in real time

The idea of ​​blockchain decentralization is ubiquitous. For example, the recent use of individual antigen self-testing to replace large-scale centralized nucleic acid testing is the implementation of the idea of ​​decentralization, which avoids cross-infection caused by large-scale gatherings and improves detection efficiency. , this time we use the latest ethersV5.0 or above version of Ethereum to link to the decentralized blockchain wallet, and verify the signature through the back-end Golang1.18 service.

In the previous article: The green hills are not hidden, after all, Dongliu, integrated Web3.0 identity wallet MetaMask Ethereum one-click login (Tornado6+Vue.js3) , we use ethersV4.0 version to link Metamask wallet, backend Using the Tornado6.0 framework based on Python3.10, in order to avoid homogenization, here is replaced by Okc wallet, client plug-in installation address: https://chrome.google.com/webstore/detail/okx-wallet/mcohilncbfahbmgdjkbpemcciiolgcge

Front-end link browser wallet

First uninstall the Vue2.0 project:

npm uninstall vue-cli -g

Here the node version must be above 8.9, and the npm version must be above 6;

Then install Vue3.0 or above:

npm install -g @vue/cli

Then install pnpm:

npm install -g pnpm

pnpm solves the node_modules dependency dilemma of traditional npm, mainly through the combination of soft links and hard links, and finally achieves the purpose of saving disk space, fast installation speed, strict and efficient, etc. Here, it is recommended to use pnpm for package management.

Next, install the ethers library in the current project:

pnpm install [email protected] --save

Note that this version requires v5.0 or above.

According to the official documentation of ethers5.4: https://docs.ethers.io/v5/getting-started/#getting-started–connecting-rpc

The ethers5.0 version supports asynchronous async operations, which improves efficiency. The async function is a function declared using the async keyword. It is an instance of the AsyncFunction constructor, and the await keyword is allowed in it. The async and await keywords allow us to write Promise-based asynchronous behavior in a more concise way without deliberately chaining promises.

Declare the asynchronous chaining method:

//链接逻辑  
    connect:async function(){  
  
  
},

Then request to link the current blockchain wallet and get the public key address asynchronously:

const provider = new ethers.providers.Web3Provider(window.ethereum);  
  
const accounts = await provider.send("eth_requestAccounts", []);

Print wallet address:

console.log(accounts);

as the picture shows:

The public key address of the okc wallet has been printed out here, and then the signature is generated:

const signer = provider.getSigner();  
  
  
var rightnow = (Date.now()/1000).toFixed(0)  
  
            console.log(rightnow);  
  
            signer.signMessage("Signing in at "+rightnow)  
              .then((signature) => {      
                        //打印签名和公钥  
                        console.log(accounts[0],signature);  
              });

Here, the signer object signer is obtained through the provider object, and then the signMessage method is called to perform the signing operation. The signing algorithm adopts the simplest form of string + timestamp.

The front end returns the signature and public key address:

0x5cae6c39a56d99d68e7a20c76da0ec387e34249b 
0x1093b6dc7c6ae1340b2ebcf819dac1a7160b69a2abbb14d86a0696bd96d6b36923d5f3f82588f30a9353b327014338f51d4e7a90baa8052791a8017f156b57511c

Backend Golang signature verification

The purpose of signature verification is easy to understand. If the client is monitored by other software that maliciously tampers with the public key address at the moment of linking the wallet, it is likely to cause irreparable economic losses to the client, so all data exposed on the front end will be lost. The backend needs to be verified. Previously, we used the Python3.10 version to verify the signature:

from web3.auto import w3  
from eth_account.messages import defunct_hash_message  
import time  
  
public_address = "0x5cae6c39a56d99d68e7a20c76da0ec387e34249b"  
signature = "0xc7b06789e6710652d8540487055e0e75918c9c4366ec47c9e7008760df1dedd6506a908f466e448481afed3fe009bbdbfdfa16c28585eff68be54d600083d4251b"  
  
  
#rightnow = int(time.time())  
  
rightnow = 1670142219  
  
print(rightnow)  
  
     
original_message = 'Signing in at {}'.format(rightnow)  
  
message_hash = defunct_hash_message(text=original_message)  
  
signer = w3.eth.account.recoverHash(message_hash, signature=signature)  
  
print(signer)

The program returns:

1670142219  
0x5cAE6c39A56d99d68e7A20c76da0ec387e34249b

Here, the public key address is reversely parsed through the signature, and it is consistent with the address obtained by the front end.

Next, we use Golang1.18 version to check the signature to see if there is any difference. First, install Golang1.18 . Platform (Sublime 4) Go lang development environment to build EP00

Then install the Golang-based Ethereum library:

go get github.com/storyicon/sigverify

According to the official document guidelines: https://github.com/storyicon/sigverify

Build the main.go file:

package main  
  
import (  
	"fmt"  
  
	ethcommon "github.com/ethereum/go-ethereum/common"  
	"github.com/storyicon/sigverify"  
)  
  
func main() {  
	valid, err := sigverify.VerifyEllipticCurveHexSignatureEx(  
		ethcommon.HexToAddress("0x5cae6c39a56d99d68e7a20c76da0ec387e34249b"),  
		[]byte("Signing in at 1670142219"),  
		"0xc7b06789e6710652d8540487055e0e75918c9c4366ec47c9e7008760df1dedd6506a908f466e448481afed3fe009bbdbfdfa16c28585eff68be54d600083d4251b",  
	)  
	fmt.Println(valid, err) // true <nil>  
}

Here the sigverify.VerifyEllipticCurveHexSignatureEx method has three parameters, which are the public key address, the signature character set, and the signature string returned by the front end, and the return value is valid:

➜  mydemo git:(master) ✗ go run "/Users/liuyue/wodfan/work/mydemo/src/mytest.go"  
true <nil>

If the signature is verified, it will return a Boolean value: true.

At this point, the back-end signature verification process is over.

epilogue

Overall, the front-end Ethers uses the new ES7 syntax async/await to achieve major improvements. It provides a way to asynchronously link wallet objects using synchronous code style without blocking the main thread, while the back-end Golang is used as a compiled language experience The signing process is simpler and more convenient than interpreted Python.

Guess you like

Origin blog.csdn.net/zcxey2911/article/details/128386219