Web Golang

Code sample for verifying wallet signature and wallet address.


package main

import (
	"crypto/ed25519"
	"errors"
	"fmt"
	"github.com/btcsuite/btcd/btcutil/base58"
	"net/url"
	"strconv"
	"time"
)

var (
	// Copy for displaying on wallet signature page, allowing customization
	sprintfStr = "Welcome to %s!\\n\\nClick to sign in and accept the %s Terms of Service: %s\\n\\nThis request will not trigger a blockchain transaction or cost any gas fees.\\n\\nNonce:%d"
	// The project name used to display on the wallet signature page
	companyName = "Your Project Name"
	// Current website address for services provided
	serviceDomain = "https://www.youdomain.com"
	CheckTime     = false
)

// sign message str
func getSignMsg() string {
	return url.PathEscape(fmt.Sprintf(sprintfStr, companyName, companyName, serviceDomain, time.Now().Unix()))
}

// verify signature
func checkSign(signature, message, publicKey string) (string, error) {
	if signature == "" || message == "" || publicKey == "" {
		return "", errors.New("parameter error")
	}

	// verify expiration time
	if CheckTime {
		messageText := base58.Decode(message)
		if len(messageText) > 16 {
			clientTime := sprintfStr[len(messageText)-16:]
			clientTimeInt, _ := strconv.ParseInt(clientTime, 10, 64)
			if checkTime(clientTimeInt) {
				return "", errors.New("signature error")
			}
		} else {
			return "", errors.New("format error, please keep ending with the string \"Nonce%3A\" and a timestamp of length 10, like this \"Nonce%3A1689054559")
		}
	}

	verify := ed25519.Verify(base58.Decode(publicKey), base58.Decode(message), base58.Decode(signature))
	if verify {
		return publicKey, nil
	}
	return "", errors.New("signature error")
}

// CheckTime Check if the client time is within a certain range
func checkTime(clientTime int64) bool {
	sysTime := time.Now().Unix()
	time1 := sysTime + 120
	time2 := sysTime - 120
	return clientTime < time1 && clientTime > time2
}

// Example
func main() {
	fmt.Println(getSignMsg())

	publicKey, err := checkSign("21SNZbbXyhUkN9RXyfKBthzCq8fKA3asV5xcZ6RuQpDcsGRzr6aRreMfrV63jjE5Wc9yx1TzmSuf8h1nvtzSe9Rz",
		"3Qm87Hq6eP6pgoyMa5SraCsWJFB1HcwoTYWbmvhzhFVBTr7Sbm2NgX7JvZ5DEcEXXirwewpsPzDmLoV8Bz8HmQSv4ZJ1kJzbg2NKhk7HcshtczUssJSrfJosev87EcwpXb5GAjJGJunv96P63n36v9WHjaqkqSiRwRetx8GhGPZ3jVCFphEo96Ciz8oQaggqG9TnxP9P1JiyGKuewJkcWnEXyc581yjEF3iwqEVQcmL8BDoLS9kpa17oLPmiPLNXxUXhUXd8bGUrncQmfhG8yNjNQ44wpacbxMZXrtw4ACrBY6qUBRGPbU469RmmWEenF4R8R4rH9Wb22YmRWUmvBPCDVJCCauLvpjwA6Gapv9Lb5HSMtix3241pxd2JhoqhkWK",
		"7x9XDk1JZTukhN2KQSGqSL1SaoEbGwzdMR3tYLpiJeex")

	if err == nil {
		fmt.Println("Verification passed, wallet address is: " + publicKey)
	} else {
		fmt.Println(err)
	}
}

Last updated