Flutter加密货币处理插件sumcoinlib的使用

发布于 1周前 作者 wuwangju 来自 Flutter

Flutter加密货币处理插件sumcoinlib的使用

Sumcoinlib

Sumcoinlib

Sumcoinlib 是一个简单且模块化的库,用于处理 Sumcoin 及其他类似加密货币,包括 Taproot 支持。该库允许构建和签名交易,并管理 BIP32 钱包。

安装和使用

如果您正在使用 Flutter,请参阅 sumcoinlib_flutter 插件。否则,您可以通过以下方式将 sumcoinlib 添加到项目中:

dart pub add sumcoinlib

如果您的库用于 Web 端,库已准备好使用。如果您的库在 Linux、macOS 或 Windows 上运行,则请参阅以下部分:

库可以通过以下方式导入:

import 'package:sumcoinlib/sumcoinlib.dart';

在使用任何库功能之前,必须异步加载库。这可以通过调用 await loadSumCoinlib() 函数来完成。

该库使用函数式面向对象编程风格。除了少数例外,对象是不可变的。方法返回新修改的对象。例如,对交易进行签名会返回一个新的已签名交易对象:

final signedTx = unsignedTx.sign(inputN: 0, key: privateKey);

示例可以在 example/ 目录中找到。

在 Linux 上构建

在 Linux 上构建库需要 Docker 或 Podman。

Linux 共享库可以通过在包的根目录下运行 dart run sumcoinlib:build_linux 来构建,这将在 build/libsecp256k1.so 中生成共享库。也可以在 sumcoinlib 的根目录下通过 dart run bin/build_linux.dart 运行此命令。

该库可以位于当前工作目录下的 build 目录中,作为系统库安装,或包含在 $LD_LIBRARY_PATH 中。

在 macOS 上构建

在 macOS 上构建库需要使用 Homebrew 安装 autotools:

brew install autoconf automake libtool

macOS 动态库必须在运行 Dart 代码时提供为 $PWD/build/libsecp256k1.dylib,或者作为名为 secp256k1.framework 的系统框架提供。

要构建动态库,运行 dart run sumcoinlib:build_macos,这将把库放置在 build 目录下。

在 Windows 上构建

原生 Windows 构建

请注意,在本节中描述的原生 Windows 构建有时会在构建过程中冻结。如果发生这种情况,请使用下面描述的 WSL 构建过程。

在 Windows 上构建需要 CMake 作为依赖项。

Windows 共享库可以通过在包的根目录下运行 dart run sumcoinlib:build_windows 来构建,这将在 build/libsecp256k1.dll 中生成共享库。也可以在 sumcoinlib 的根目录下通过 dart run bin/build_windows.dart 运行此命令。

Windows 构建使用 Visual Studio 17 2022 生成器。较早版本的 Visual Studio 工具链可能通过编辑 bin/build_windows.dart 而工作。

从 Linux 跨编译到 Windows

在 Ubuntu 20.04 主机上使用 dart run sumcoinlib:build_windows_crosscompile 跨编译 secp256k1 DLL 到 Windows。也可以在 sumcoinlib 的根目录下通过 dart run bin/build_windows_crosscompile.dart 运行此命令。

使用 WSL 跨编译到 Windows

可以在 Windows Subsystem for Linux (WSL2) 上完成 Windows 构建。首先,在 WSL(2) 主机上安装以下软件包:

apt-get update -y
apt-get install -y autoconf libtool build-essential git cmake mingw-w64

然后,在 Ubuntu 20.04 WSL2 实例上使用主机上的 dart run sumcoinlib:build_wsldart run bin/build_wsl.dartsumcoinlib 的根目录下跨编译 secp256k1 DLL 到 Windows。也可以在安装了 Docker 或 Podman 的 WSL 上完成上述步骤,或者在不安装 Flutter 的 WSL 上完成构建,具体参考 bitcoin-core/secp256k1 的 “Cross compiling” 指南

开发

本部分仅适用于库的开发者。

绑定和 WebAssembly

WebAssembly (WASM) 模块已经预编译并准备就绪。FFI 绑定已经预生成。这些仅在底层 secp256k1 库更改时才需要更新。

对于本地库(不包括 WebAssembly)的绑定,是从 headers/secp256k1.h 文件使用 dart run ffigen 生成的。

WebAssembly 模块已经预编译到 lib/src/secp256k1/secp256k1.wasm.g.dart。可以使用 dart run bin/build_wasm.dartsumcoinlib 的根目录下重新构建。

完整示例代码

import "package:sumcoinlib/sumcoinlib.dart";

void main() async {

  // Always remember to load the library for web use
  // Flutter applications should use the sumcoinlib_flutter plugin with the
  // CoinlibLoader widget instead.
  await loadSumCoinlib();

  // Create a HD Key from a seed
  final seed = generateRandomBytes(16);
  final wallet = HDPrivateKey.fromSeed(seed);

  // Derive hardened key at 10'
  final hardened = wallet.deriveHardened(10);

  // Further derive key at 4
  final key1 = hardened.derive(4);

  // Keys can be derived from the path too
  final key2 = wallet.derivePath("m/10'/4");

  // Public keys can be compared
  if (key1.publicKey == key2.publicKey) {
    print("Derived keys match");
  }

  // Generate a P2PKH address with the mainnet prefix
  final address = P2PKHAddress.fromPublicKey(
    key1.publicKey,
    version: Network.mainnet.p2pkhPrefix,
  );
  print("Address: $address");

  // Sign message with key and verify with address

  final msg = "Hello World!";
  final msgSig = MessageSignature.sign(
    key: key1.privateKey,
    message: msg,
    prefix: Network.mainnet.messagePrefix,
  );

  if (
    msgSig.verifyAddress(
      address: address,
      message: msg,
      prefix: Network.mainnet.messagePrefix,
    )
  ) {
    print("Msg signature is valid: $msgSig");
  }

  // Create a transaction that spends a P2PKH input to the address generated
  // earlier. The version is set to 3 by default with a 0 locktime.

  print("\nP2PKH transaction");

  // hexToBytes is a convenience function.
  final prevHash = hexToBytes(
    "32d1f1cf811456c6da4ef9e1cb7f8bb80c4c5e9f2d2c3d743f2b68a9c6857823",
  );

  final tx = Transaction(
    inputs: [
      P2PKHInput(prevOut: OutPoint(prevHash, 1), publicKey: key1.publicKey),
    ],
    outputs: [
      Output.fromAddress(BigInt.from(2000000), address),
    ],
  );

  if (!tx.complete) {
    print("Unsigned transaction is incomplete");
  }

  // Sign the input with the private key. The signed transaction is returned as
  // a new object as most objects in the library are immutable.
  final signedTx = tx.sign(inputN: 0, key: key1.privateKey);

  if (signedTx.complete) {
    print("Signed transaction is complete");
  }

  print("Txid = ${signedTx.txid}");
  print("Tx hex = ${signedTx.toHex()}");

  print("\nTaproot");

  // Create a Taproot object with an internal key
  final taproot = Taproot(internalKey: key1.publicKey);

  // Print P2TR address
  final trAddr = P2TRAddress.fromTaproot(
    taproot, hrp: Network.mainnet.bech32Hrp,
  );
  print("Taproot address: $trAddr");

  // Sign a TR input using key-path. Send to an identical TR output

  final trOutput = Output.fromProgram(
    BigInt.from(123456),
    P2TR.fromTaproot(taproot),
  );

  final trTx = Transaction(
    inputs: [TaprootKeyInput(prevOut: OutPoint(prevHash, 1))],
    outputs: [trOutput],
  ).sign(
    inputN: 0,
    // Private keys must be tweaked by the Taproot object
    key: taproot.tweakPrivateKey(key1.privateKey),
    prevOuts: [trOutput],
  );

  print("TR Tx hex = ${trTx.toHex()}");

}

更多关于Flutter加密货币处理插件sumcoinlib的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter加密货币处理插件sumcoinlib的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用sumcoinlib插件来处理加密货币(假设sumcoinlib是一个提供加密货币相关功能的虚构插件)的示例代码。由于sumcoinlib是一个虚构的插件,我将提供一个假设的API和功能实现,以便展示如何使用它。

前提条件

  1. 确保你的Flutter开发环境已经设置好。
  2. 确保你已经在pubspec.yaml文件中添加了sumcoinlib依赖(假设它存在于pub.dev上,但实际上你需要替换为真实的插件名称和版本)。
dependencies:
  flutter:
    sdk: flutter
  sumcoinlib: ^1.0.0  # 假设的版本号

步骤

  1. 安装依赖

    运行以下命令来安装依赖:

    flutter pub get
    
  2. 导入插件

    在你的Dart文件中导入sumcoinlib插件:

    import 'package:sumcoinlib/sumcoinlib.dart';
    
  3. 使用插件功能

    下面是一个示例,展示如何使用sumcoinlib插件进行加密货币地址的验证、余额查询和交易发送。

    import 'package:flutter/material.dart';
    import 'package:sumcoinlib/sumcoinlib.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Sumcoin Wallet',
          home: Scaffold(
            appBar: AppBar(
              title: Text('Sumcoin Wallet'),
            ),
            body: Center(
              child: SumcoinScreen(),
            ),
          ),
        );
      }
    }
    
    class SumcoinScreen extends StatefulWidget {
      @override
      _SumcoinScreenState createState() => _SumcoinScreenState();
    }
    
    class _SumcoinScreenState extends State<SumcoinScreen> {
      String address = '';
      String balance = '';
      String errorMessage = '';
    
      void validateAddress() async {
        try {
          bool isValid = await SumcoinLib.validateAddress(address);
          setState(() {
            errorMessage = isValid ? '' : 'Invalid Sumcoin address!';
          });
        } catch (e) {
          setState(() {
            errorMessage = 'Error validating address: $e';
          });
        }
      }
    
      void fetchBalance() async {
        try {
          String newBalance = await SumcoinLib.getBalance(address);
          setState(() {
            balance = newBalance;
            errorMessage = '';
          });
        } catch (e) {
          setState(() {
            errorMessage = 'Error fetching balance: $e';
          });
        }
      }
    
      void sendTransaction() async {
        try {
          String recipientAddress = 'recipient_address_here'; // Replace with actual recipient address
          double amount = 1.0; // Replace with actual amount
          String txId = await SumcoinLib.sendTransaction(address, recipientAddress, amount);
          setState(() {
            errorMessage = 'Transaction sent successfully! TX ID: $txId';
          });
        } catch (e) {
          setState(() {
            errorMessage = 'Error sending transaction: $e';
          });
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextField(
                decoration: InputDecoration(labelText: 'Sumcoin Address'),
                onChanged: (value) {
                  setState(() {
                    address = value;
                  });
                },
              ),
              SizedBox(height: 16),
              TextButton(
                onPressed: validateAddress,
                child: Text('Validate Address'),
              ),
              SizedBox(height: 16),
              Text('Balance: $balance'),
              SizedBox(height: 16),
              TextButton(
                onPressed: fetchBalance,
                child: Text('Fetch Balance'),
              ),
              SizedBox(height: 16),
              Text(errorMessage),
              SizedBox(height: 32),
              TextButton(
                onPressed: sendTransaction,
                child: Text('Send Transaction'),
              ),
            ],
          ),
        );
      }
    }
    

注意事项

  1. 插件API:上述代码假设SumcoinLib类提供了validateAddressgetBalancesendTransaction方法。你需要根据实际的插件API文档进行调整。
  2. 错误处理:在实际应用中,你应该添加更多的错误处理和用户反馈。
  3. 安全性:处理加密货币时,确保你的应用安全,包括使用安全的存储和传输方法。

由于sumcoinlib是虚构的,你需要将上述代码中的API调用替换为实际插件提供的API。如果你有一个具体的插件,请参考其官方文档来获取正确的API调用方式和参数。

回到顶部