Flutter wallet錢包的隨機生成和sqflite數據庫存儲

前言:

    Flutter錢包具有管理密鑰、地址、轉賬交易等功能,是一種互聯網錢包或區塊鏈錢包通過助記詞可以拿到私鑰,而私鑰可以獲取地址信息 ,私鑰與地址一一對應,地址是用戶的唯一標識,用戶的所有錢都是存放在地址裏面。提到錢包,首先都會考慮如何安全的存放用戶的錢。在這裏,我使用的是sqflite數據庫來存儲錢包地址,用戶可以隨機創建錢包,查詢錢包和刪除錢包。

效果圖:

         

實現的步驟:

1.在pubspec.yaml添加sdk

dependencies:
  ...
  cupertino_icons: ^0.1.3
  bip39: ^1.0.3
  ed25519_hd_key: ^1.0.1
  web3dart: ^1.2.3
  hex: ^0.1.2
  sqflite: 1.3.1

2.隨機生成錢包地址

//導包
import 'package:bip39/bip39.dart' as bip39;
import 'package:ed25519_hd_key/ed25519_hd_key.dart';
import "package:hex/hex.dart";
import 'package:web3dart/web3dart.dart';


//隨機生成錢包地址的方法
Future _getWalletAddress(String password) async {
    //隨機生成助記詞
    String seed = bip39.mnemonicToSeedHex(password);
    KeyData master = ED25519_HD_KEY.getMasterKeyFromSeed(seed);
    //通過助記詞生成私鑰
    String privateKey = HEX.encode(master.key);

    //通過私鑰拿到地址信息
    final private = EthPrivateKey.fromHex(privateKey);
    final address = await private.extractAddress();
}

3.Sqflite數據庫存儲錢包的信息

 3.1創建數據庫

Database db;
String tableWallet = 'wallet';
String columnId = 'id';
String columnName = 'name';
String columnAddress = 'address';

//創建數據庫的方法
openSqlite() async {
    // 路徑
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'walletAddress.db');

    // 創建數據庫
    db = await openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
          await db.execute('''
          CREATE TABLE $tableWallet (
            $columnId INTEGER PRIMARY KEY autoincrement, 
            $columnName String, 
            $columnAddress String)
          ''');
        });
  }

3.2增加錢包地址信息

//增
Future insert(String name, String address) async {
    String sql =
        "INSERT INTO $tableWallet($columnName,$columnAddress) VALUES('$name','$address')";
    await db.rawInsert(sql);
}

3.3刪除錢包地址信息

//刪
Future<int> delete(String name) async {
    return await db.rawDelete('DELETE FROM $tableWallet WHERE $columnName = ?', ['$name']);
}

3.4修改錢包地址信息

//改
Future<void> update(String name,int id) async {
    await db.rawUpdate('UPDATE $tableWallet SET $columnName = ? WHERE $columnId = ?', ['$name', '$id']);

}

3.5查詢錢包地址信息

//查
Future<List<Map>> queryAll() async {
    String sqlQuery = 'SELECT * FROM $tableWallet';
    return await db.rawQuery(sqlQuery);
}

3.6關閉數據庫

//關閉
Future close() async {
    await db.close();
}

4.封裝Sqflite數據庫的完整代碼

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:async';

class SqliteWallet {
  Database db;
  String tableWallet = 'wallet';
  String columnId = 'id';
  String columnName = 'name';
  String columnAddress = 'address';

  openSqlite() async {
    // 路徑
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'walletAddress.db');

    // 創建數據庫
    db = await openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
          await db.execute('''
          CREATE TABLE $tableWallet (
            $columnId INTEGER PRIMARY KEY autoincrement, 
            $columnName String, 
            $columnAddress String)
          ''');
        });
  }

  // 增
  Future insert(String name, String address) async {
    String sql =
        "INSERT INTO $tableWallet($columnName,$columnAddress) VALUES('$name','$address')";
    await db.rawInsert(sql);
  }

  // 刪
  Future<int> delete(String name) async {
    return await db.rawDelete('DELETE FROM $tableWallet WHERE $columnName = ?', ['$name']);
  }

  //改
  Future<void> update(String name,int id) async {
    await db.rawUpdate('UPDATE $tableWallet SET $columnName = ? WHERE $columnId = ?', ['$name', '$id']);

  }

  // 查
  Future<List<Map>> queryAll() async {
    String sqlQuery = 'SELECT * FROM $tableWallet';
    return await db.rawQuery(sqlQuery);
  }

  //清空
  Future<int> clear() async {
    return await db.delete('$tableWallet');
  }

  // 關閉數據庫
  Future close() async {
    await db.close();
  }
}

5.在CreateWalletPage頁面調用創建錢包的方法

class CreateWalletPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new CreateWalletPageState();
}

class CreateWalletPageState extends State<CreateWalletPage> {
   SqliteWallet _sqliteWallet = new SqliteWallet();
   
   @override
   Widget build(BuildContext context) {
       return new Scaffold(
          ...
       );
   }
   
   //創建錢包的方法
   Future createWallet() async {
       _getWalletAddress(_password.text);//獲取錢包地址
       await _sqliteWallet.openSqlite();//打開數據庫
       await _sqliteWallet.insert(_name.text, _address);//插入數據
       await _sqliteWallet.close();//關閉數據庫
  }

}

6.在HomePage頁面調用查詢錢包的方法

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
   SqliteWallet _sqliteWallet = new SqliteWallet();
   var _walletList = [];

   @override
   Widget build(BuildContext context) {
       return Scaffold(
       ...
       );
   }

   //查詢錢包的方法
   Future _getQueryWalletAddressData() async {
       await _sqliteWallet.openSqlite();
       var queryWalletAddressList = await _sqliteWallet.queryAll();
       await _sqliteWallet.close();
       setState(() {
          _walletList = queryWalletAddressList;
       });
   }

}

7.在WalletMangerPage頁面調用刪除錢包的方法

class WalletMangerPage extends StatefulWidget {
  Wallets wallets;
  WalletMangerPage({@required this.wallets});

  @override
  State<StatefulWidget> createState() => new WalletMangerPageState();
}

class WalletMangerPageState extends State<WalletMangerPage> {
  SqliteWallet _sqliteWallet = new SqliteWallet();

  @override
  Widget build(BuildContext context) {
     return Scaffold(
     ...
     );
  }

  //刪除錢包的方法
  Future _deleteWallet() async {
    await _sqliteWallet.openSqlite();
    await _sqliteWallet.delete(widget.wallets.name);
    await _sqliteWallet.close();
    navigateToPage(context, "${Routes.home}");
  }

}

8.總結

在Flutter上已經實現錢包地址的隨機生成和sqflite數據庫存儲的功能,歡迎大家圍觀。源碼地址: https://github.com/wupeilinloveu/flutter_sqlite,如果有什麼疑問的話,歡迎留言聯繫我!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章