我在使用 tonweb 库创建 Ton 钱包时遇到问题。 我尝试先生成私钥并从私钥获取公钥,然后从公钥获取地址钱包。 但地址钱包并不依赖于私钥!
const TonWeb = require("tonweb");
const nacl = require("tweetnacl");
(async () => {
const tonwebInstance = new TonWeb();
// Generate a random 32-byte private key
const privateKey = nacl.randomBytes(32);
const privateKeyHex = Buffer.from(privateKey).toString("hex");
// Create a key pair from the private key
const keyPair = nacl.sign.keyPair.fromSeed(privateKey);
// Extract the public key from the key pair
const publicKey = keyPair.publicKey;
const publicKeyHex = Buffer.from(publicKey).toString("hex");
// Create a wallet using the public key as Uint8Array
const wallet = tonwebInstance.wallet.create({
publicKey: publicKey,
});
// Get the wallet address
const walletAddress = (await wallet.getAddress()).toString(true, true, true);
console.log("Private key (hex):", privateKeyHex);
console.log("Public key (hex):", publicKeyHex);
console.log("Wallet address:", walletAddress);
})();
根据
tweetnacl
文档,不建议使用fromSeed
函数。我已更改您的代码以仅使用推荐的 nacl.sign.keyPair()
函数,并且它可以按预期工作:
const TonWeb = require("tonweb");
const nacl = require("tweetnacl");
(async () => {
const tonwebInstance = new TonWeb();
// Create a key pair
const keyPair = nacl.sign.keyPair();
// Extract the public key from the key pair
const publicKey = keyPair.publicKey;
const publicKeyHex = Buffer.from(publicKey).toString("hex");
// Extract the private key from the key pair
const privateKey = keyPair.secretKey;
const privateKeyHex = Buffer.from(privateKey).toString("hex");
// Create a wallet using the public key as Uint8Array
const wallet = tonwebInstance.wallet.create({publicKey});
// Get the wallet address
const walletAddress = (await wallet.getAddress()).toString(true, true, true);
console.log("Wallet address:", walletAddress);
console.log("Public key (hex):", publicKeyHex);
console.log("Private key (hex):", privateKeyHex);
})();
输出是 64 字节私钥,而不是之前的 32 字节私钥实现。
@Aaron Meese的答案是正确的👍.
但是我添加这个是因为您特别要求您需要
32-byte
或privateKey
。默认情况下,nacl.sign.keyPair()
生成组合私钥的
64-byte
。
组合私钥(64 字节)= 种子(32 字节)+ 公钥(32 字节)
如果您真的想坚持使用
32-byte
中的privateKey
,您必须从组合私钥中
slice
。
const combinedPrivateKey = keyPair.secretKey; // Seed + Public Key
// Sling first 32 bytes which is Seed that can be used as Private Key
const privateKey = combinedPrivateKey.slice(0, 32);
const privateKeyHex = Buffer.from(privateKey).toString("hex");
你也可以尝试用助记词生成
const createWallet = async () => {
const tonweb = new TonWeb();
const words = await generateMnemonic();
const seed = await mnemonicToSeed(words);
const keyPair = TonWeb.utils.nacl.sign.keyPair.fromSeed(seed);
console.log(TonWeb.utils.bytesToHex(keyPair.secretKey));
const WalletClass = tonweb.wallet.all.v3R2;
const wallet = new WalletClass(tonweb.provider, {
publicKey: keyPair.publicKey
});
const address = await wallet.getAddress();
console.log(address.toString(true, true, false)); // print address in format to display in UI
}