使用Nethereum.Signer离线签名交易并发送到Infura?

解读

国内区块链岗位面试时,面试官常把“离线签名 + 第三方节点广播”作为考察点,目的有三:

  1. 验证候选人是否真正理解“私钥不离网”的安全原则;
  2. 检查对Nethereum底层ABI编码、RLP序列化、链ID隔离(EIP-155)的掌握;
  3. 确认候选人能在国内网络环境下完成Infura TLS通信、异常重试、Nonce自增、Gas Price动态估算等工程闭环。
    回答时必须体现:私钥本地保存、交易对象构造、EIP-155签名、原始交易RLP编码、Hex发送、TxHash轮询回执六步,任何一步缺失都会被打断追问。

知识点

  1. Nethereum.Signer.TransactionSigner:负责用私钥对RLP编码做secp256k1签名,自动附加链ID防止重放。
  2. OfflineTransactionRequest:离线构造TransactionInput,不依赖节点,本地计算Nonce与GasPrice。
  3. EIP-155:把ChainId写入签名V值,国内主网面试必须回答“V = ChainId * 2 + 35 或 36”。
  4. Infura HTTPS JSON-RPC:国内需配置System.Net.Http.HttpClient的TLS 1.2、Keep-Alive、超时重试,避免“407 Proxy Authentication Required”或“502 Bad Gateway”。
  5. 发送流程:SignTransaction→RawHex→eth_sendRawTransaction→eth_getTransactionReceipt轮询,Receipt.Status == 0x1才确认成功。
  6. 异常分类:Nonce too low、Insufficient funds、Replacement transaction underpriced、Intrinsic gas too low,必须给出针对性处理代码。

答案

// 国内NuGet源:dotnet restore -s https://nuget.cdn.azure.cn/v3/index.json
using System;
using System.Numerics;
using System.Threading.Tasks;
using Nethereum.Signer;
using Nethereum.Web3;
using Nethereum.Web3.Accounts;
using Nethereum.RPC.Eth.DTOs;
using Nethereum.Hex.HexTypes;

public class InfuraOfflineSender
{
    private readonly string _infuraUrl;
    private readonly int _chainId;
    private readonly Web3 _web3;

    public InfuraOfflineSender(string infuraProjectId, int chainId = 1)
    {
        _chainId = chainId;
        // 国内推荐https,避免ws被防火墙掐断
        _infuraUrl = $"https://mainnet.infura.io/v3/{infuraProjectId}";
        _web3 = new Web3(_infuraUrl);
    }

    public async Task<string> SendOfflineAsync(string privateKey,
                                               string to,
                                               BigInteger valueWei,
                                               string? data = null,
                                               BigInteger? gasPrice = null,
                                               BigInteger? gasLimit = null)
    {
        // 1. 本地账户,仅用来取地址,不联网
        var account = new Account(privateKey, _chainId);
        var from = account.Address;

        // 2. 本地取Nonce,必须比节点高,面试常问“并发怎么办”——答:本地维护AtomicLong或Redis
        var nonce = await _web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(from, BlockParameter.CreatePending());
        BigInteger nonceValue = nonce.Value;

        // 3. 估算Gas,如果data为空,21000足够;带合约调用需estimate
        BigInteger gas = gasLimit ?? 21000;
        if (gasLimit == null && !string.IsNullOrEmpty(data))
        {
            var call = new CallInput { To = to, Data = data, Value = new HexBigInteger(valueWei), From = from };
            gas = (await _web3.Eth.Transactions.EstimateGas.SendRequestAsync(call)).Value;
        }

        // 4. GasPrice,国内面试必须答“用ETH Gas Station或Web3.GasPrice”,否则追问“拥堵时怎么加速”
        BigInteger price = gasPrice ?? (await _web3.Eth.GasPrice.SendRequestAsync()).Value;

        // 5. 离线签名
        var txSigner = new TransactionSigner();
        var rawHex = txSigner.SignTransaction(privateKey,
                                              to,
                                              valueWei,
                                              nonceValue,
                                              gas,
                                              price,
                                              data,
                                              _chainId);

        // 6. 发送到Infura
        var txHash = await _web3.Eth.TransactionManager.SendRawTransaction.SendRequestAsync("0x" + rawHex);

        // 7. 轮询回执,国内防火墙下建议最多120秒,每3秒一次
        TransactionReceipt? receipt = null;
        for (int i = 0; i < 40; i++)
        {
            receipt = await _web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(txHash);
            if (receipt != null) break;
            await Task.Delay(3000);
        }

        if (receipt == null)
            throw new TimeoutException("Infura未返回回执,可能网络拥堵或Tx被丢弃");
        if (receipt.Status.Value != 1)
            throw new Exception("链上执行失败,Status=0,可能Gas不足或合约Revert");

        return receipt.TransactionHash;
    }
}

// 使用示例
class Program
{
    static async Task Main()
    {
        var sender = new InfuraOfflineSender("你的InfuraProjectId", 1);
        var txHash = await sender.SendOfflineAsync(
            privateKey: "你的64位Hex私钥",
            to: "0x123...",
            valueWei: Web3.Convert.ToWei(0.01),
            data: null);
        Console.WriteLine("TxHash: " + txHash);
    }
}

关键点回顾:

  • 私钥只在SignTransaction时进入内存,面试可补充“用Azure Key Vault或国产HSM做密钥托管”。
  • 必须传_chainId,否则Infura返回“invalid sender”。
  • 发送失败时根据Error.Message做指数退避,国内云厂商SLA 99.9%,仍可能偶发502。

拓展思考

  1. 国内监管要求“区块链信息服务备案”,若DApp面向用户,需在网信办备案编号,面试可主动提及“代码已做敏感词过滤,交易data字段不含非法内容”。
  2. 大额资产离线下单后,如何防止“双花”?答:本地Nonce池持久化到MySQL,采用乐观锁;或接入国产BSN网关,利用其Nonce托管服务。
  3. 若Infura被墙,可无缝切换到国内节点服务商:Alchemy中国、ConsenSys中国、火币云、币安智能云,只需替换RPC URL,代码零改动。
  4. 性能压测:使用Channels + Batch.SendRawTransactionAsync,单进程可达800 TPS,面试可给出BenchmarkDotNet数据,展示内存零拷贝。
  5. 未来EIP-1559升级,BaseFee + PriorityFee替换GasPrice,需改用Transaction1559Signer,面试追问时答“已封装策略:如果链支持1559,自动切换签名算法,向下兼容Legacy”。