umi-top-community/umi-core-php

社区维护的 UMI 核心PHP库

1.0.8 2022-07-20 13:16 UTC

This package is not auto-updated.

Last update: 2024-09-26 22:32:48 UTC


README

UMI
UMI 核心 - PHP 库

travis

Scrutinizer 代码质量 覆盖率状态 PSR-12 GitHub Keybase PGP <br/> GitHub 发布 (最新 SemVer) Packagist 版本 PHP 版本支持 Packagist 下载

目录

简介

运行此库需要 PHP 64 位版本 >= 5.4 和标准的 hash 扩展。

安装

此库已在 Packagist 存储库中发布,并可以通过依赖管理器 Composer 安装。

Composer

composer require umi-top-community/umi-core-php

示例

助记词

UMI 对私钥的生成和存储方式没有任何限制。
为了兼容性,建议使用 bip39

从助记词生成种子

使用此库的示例 bitcoin-php

<?php declare(strict_types=1);

include __DIR__ . '/../vendor/autoload.php';

use BitWasp\Bitcoin\Mnemonic\Bip39\Bip39SeedGenerator;
use UmiTop\UmiCore\Key\SecretKey;
use UmiTop\UmiCore\Address\Address;

$mnemonic = 'mix tooth like stock powder emerge protect index magic';

$bip39 = new Bip39SeedGenerator();
$seed = $bip39->getSeed($mnemonic)->getBinary();

$address = Address::fromKey(SecretKey::fromSeed($seed));

echo $address->getBech32(), PHP_EOL;

密钥

UMI 使用 Ed25519 (RFC 8032) — 使用 EdDSA 方案的签名,该方案使用 SHA-512Curve25519

从种子生成密钥

种子可以是任意长度。最佳选择是 32 字节长度。

<?php declare(strict_types=1);

include __DIR__ . '/../vendor/autoload.php';

use UmiTop\UmiCore\Key\SecretKey;

$seed = random_bytes(32);
$secKey = SecretKey::fromSeed($seed);
$bytes = $secKey->getBytes();

签名消息

<?php declare(strict_types=1);

include __DIR__ . '/../vendor/autoload.php';

use UmiTop\UmiCore\Key\SecretKey;

$secKey = SecretKey::fromSeed(random_bytes(32));
$message = 'Hello World';
$signature = $secKey->sign($message);

echo base64_encode($signature), PHP_EOL;

验证签名

<?php declare(strict_types=1);
      
include __DIR__ . '/../vendor/autoload.php';

use UmiTop\UmiCore\Address\Address;

$address = 'umi18d4z00xwk6jz6c4r4rgz5mcdwdjny9thrh3y8f36cpy2rz6emg5s6rxnf6';
$message = 'Hello World';
$signature = base64_decode(
    'Jbi9YfwLcxiTMednl/wTvnSzsPP9mV9Bf2vvZytP87oyg1p1c9ZBkn4gNv15ZHwEFv3bVYlowgyIKmMwJLjJCw=='
);
$pubKey = Address::fromBech32($address)->getPublicKey();
$isValid = $pubKey->verifySignature($signature, $message);

var_dump($isValid);

地址

UMI 使用长度为 62 个字符的 Bech32 格式地址 (bip173)。前缀长度为 3 个字符。
Genesis-地址是一个特殊案例,它只存在于Genesis区块中,这些地址的长度为65个字符,并且总是以genesis前缀开头。

Bech32 格式地址

可以使用静态方法Address::fromBech32()从Bech32字符串创建地址,并使用Address->getBech32()导出。

<?php declare(strict_types=1);
      
include __DIR__ . '/../vendor/autoload.php';

use UmiTop\UmiCore\Address\Address;

$bech32 = 'umi18d4z00xwk6jz6c4r4rgz5mcdwdjny9thrh3y8f36cpy2rz6emg5s6rxnf6';
$address = Address::fromBech32($bech32);

echo $address->getBech32(), PHP_EOL;

从私钥或公钥生成地址

静态方法Address::fromKey()可以从私钥或公钥创建地址。

<?php declare(strict_types=1);
      
include __DIR__ . '/../vendor/autoload.php';

use UmiTop\UmiCore\Address\Address;
use UmiTop\UmiCore\Key\SecretKey;
use UmiTop\UmiCore\Key\PublicKey;

$secKey = SecretKey::fromSeed(random_bytes(32));
$address1 = Address::fromKey($secKey);

echo $address1->getBech32(), PHP_EOL;

$pubKey = new PublicKey(random_bytes(32));
$address2 = Address::fromKey($pubKey);

echo $address2->getBech32(), PHP_EOL;

前缀

默认情况下,地址具有umi前缀。可以使用方法Address->setPrefix()更改前缀。

<?php declare(strict_types=1);
      
include __DIR__ . '/../vendor/autoload.php';

use UmiTop\UmiCore\Address\Address;

$bech32 = 'umi18d4z00xwk6jz6c4r4rgz5mcdwdjny9thrh3y8f36cpy2rz6emg5s6rxnf6';
$address = Address::fromBech32($bech32)->setPrefix('aaa');

echo $bech32, PHP_EOL;
echo $address->getBech32(), PHP_EOL;

交易

转币

senderrecipientvalue字段是必需的。
金额以UMI分表示,即1.23 UMI = 123。

<?php declare(strict_types=1);

include __DIR__ . '/../vendor/autoload.php';

use UmiTop\UmiCore\Address\Address;
use UmiTop\UmiCore\Key\SecretKey;
use UmiTop\UmiCore\Transaction\Transaction;

$secKey = SecretKey::fromSeed(random_bytes(32));
$sender = Address::fromKey($secKey)->setPrefix('umi');
$recipient = Address::fromKey($secKey)->setPrefix('aaa');
$value = 42;

$trx = new Transaction();
$trx->setVersion(Transaction::BASIC)
    ->setSender($sender)
    ->setRecipient($recipient)
    ->setValue($value)
    ->sign($secKey);

echo 'txid:   ', bin2hex($trx->getHash()), PHP_EOL;
echo 'base64: ', base64_encode($trx->getBytes()), PHP_EOL;

创建结构

senderprefixnameprofitPercentfeePercent字段是必需的。
前缀长度为3个字符。名称以UTF-8编码,长度可达35字节。百分比以百分之一为单位表示,即1.23% = 123。

<?php declare(strict_types=1);

include __DIR__ . '/../vendor/autoload.php';

use UmiTop\UmiCore\Address\Address;
use UmiTop\UmiCore\Key\SecretKey;
use UmiTop\UmiCore\Transaction\Transaction;

$secKey = SecretKey::fromSeed(random_bytes(32));
$sender = Address::fromKey($secKey)->setPrefix('umi');

$trx = new Transaction();
$trx->setVersion(Transaction::CREATE_STRUCTURE)
    ->setSender($sender)
    ->setPrefix('aaa')
    ->setName('🙂')
    ->setProfitPercent(500)
    ->setFeePercent(2000)
    ->sign($secKey);

echo 'txid:   ', bin2hex($trx->getHash()), PHP_EOL;
echo 'base64: ', base64_encode($trx->getBytes()), PHP_EOL;

更新结构设置

senderprefixnameprofitPercentfeePercent字段是必需的。
即使没有更改,也需要设置所有字段。

<?php declare(strict_types=1);

include __DIR__ . '/../vendor/autoload.php';

use UmiTop\UmiCore\Address\Address;
use UmiTop\UmiCore\Key\SecretKey;
use UmiTop\UmiCore\Transaction\Transaction;

$secKey = SecretKey::fromSeed(random_bytes(32));
$sender = Address::fromKey($secKey)->setPrefix('umi');

$trx = new Transaction();
$trx->setVersion(Transaction::UPDATE_STRUCTURE)
    ->setSender($sender)
    ->setPrefix('aaa')
    ->setName('🙂')
    ->setProfitPercent(500)
    ->setFeePercent(2000)
    ->sign($secKey);

echo 'txid:   ', bin2hex($trx->getHash()), PHP_EOL;
echo 'base64: ', base64_encode($trx->getBytes()), PHP_EOL;

设置收益地址

senderrecipient字段是必需的。
用于发放利润的地址必须属于结构。

<?php declare(strict_types=1);

include __DIR__ . '/../vendor/autoload.php';

use UmiTop\UmiCore\Address\Address;
use UmiTop\UmiCore\Key\SecretKey;
use UmiTop\UmiCore\Transaction\Transaction;

$secKey = SecretKey::fromSeed(random_bytes(32));
$sender = Address::fromKey($secKey)->setPrefix('umi');
$newPrf = Address::fromBech32('aaa18d4z00xwk6jz6c4r4rgz5mcdwdjny9thrh3y8f36cpy2rz6emg5svsuw66');

$trx = new Transaction();
$trx->setVersion(Transaction::UPDATE_PROFIT_ADDRESS)
    ->setSender($sender)
    ->setRecipient($newPrf)
    ->sign($secKey);

echo 'txid:   ', bin2hex($trx->getHash()), PHP_EOL;
echo 'base64: ', base64_encode($trx->getBytes()), PHP_EOL;

设置手续费转账地址

senderrecipient字段是必需的。
用于转账手续费的地址必须属于结构。

<?php declare(strict_types=1);

include __DIR__ . '/../vendor/autoload.php';

use UmiTop\UmiCore\Address\Address;
use UmiTop\UmiCore\Key\SecretKey;
use UmiTop\UmiCore\Transaction\Transaction;

$secKey = SecretKey::fromSeed(random_bytes(32));
$sender = Address::fromKey($secKey)->setPrefix('umi');
$newFee = Address::fromBech32('aaa18d4z00xwk6jz6c4r4rgz5mcdwdjny9thrh3y8f36cpy2rz6emg5svsuw66');

$trx = new Transaction();
$trx->setVersion(Transaction::UPDATE_FEE_ADDRESS)
    ->setSender($sender)
    ->setRecipient($newFee)
    ->sign($secKey);

echo 'txid:   ', bin2hex($trx->getHash()), PHP_EOL;
echo 'base64: ', base64_encode($trx->getBytes()), PHP_EOL;

激活中继地址

senderrecipient字段是必需的。
地址必须属于结构。

<?php declare(strict_types=1);

include __DIR__ . '/../vendor/autoload.php';

use UmiTop\UmiCore\Address\Address;
use UmiTop\UmiCore\Key\SecretKey;
use UmiTop\UmiCore\Transaction\Transaction;

$secKey = SecretKey::fromSeed(random_bytes(32));
$sender = Address::fromKey($secKey)->setPrefix('umi');
$transit = Address::fromBech32('aaa18d4z00xwk6jz6c4r4rgz5mcdwdjny9thrh3y8f36cpy2rz6emg5svsuw66');

$trx = new Transaction();
$trx->setVersion(Transaction::CREATE_TRANSIT_ADDRESS)
    ->setSender($sender)
    ->setRecipient($transit)
    ->sign($secKey);

echo 'txid:   ', bin2hex($trx->getHash()), PHP_EOL;
echo 'base64: ', base64_encode($trx->getBytes()), PHP_EOL;

禁用中继地址

senderrecipient字段是必需的。
地址必须属于结构。

<?php declare(strict_types=1);

include __DIR__ . '/../vendor/autoload.php';

use UmiTop\UmiCore\Address\Address;
use UmiTop\UmiCore\Key\SecretKey;
use UmiTop\UmiCore\Transaction\Transaction;

$secKey = SecretKey::fromSeed(random_bytes(32));
$sender = Address::fromKey($secKey)->setPrefix('umi');
$transit = Address::fromBech32('aaa18d4z00xwk6jz6c4r4rgz5mcdwdjny9thrh3y8f36cpy2rz6emg5svsuw66');

$trx = new Transaction();
$trx->setVersion(Transaction::DELETE_TRANSIT_ADDRESS)
    ->setSender($sender)
    ->setRecipient($transit)
    ->sign($secKey);

echo 'txid:   ', bin2hex($trx->getHash()), PHP_EOL;
echo 'base64: ', base64_encode($trx->getBytes()), PHP_EOL;

将交易发送到网络

使用cURLJSON的示例

<?php declare(strict_types=1);

include __DIR__ . '/../vendor/autoload.php';

use UmiTop\UmiCore\Transaction\Transaction;

$trx = new Transaction();

$payload = json_encode(
    [
        'jsonrpc' => '2.0',
        'id' => '',
        'method' => 'sendTransaction',
        'params' => [
            'base64' => base64_encode($trx->getBytes())
        ]
    ]
);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://testnet.umi.top/json-rpc");
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);

$response = curl_exec($ch);

curl_close($ch);

echo $response, PHP_EOL;

许可证

Лицензия MIT

Copyright © 2020 UMI

Данная лицензия разрешает лицам, получившим копию данного программного
обеспечения и сопутствующей документации (в дальнейшем именуемыми
«Программное обеспечение»), безвозмездно использовать Программное обеспечение
без ограничений, включая неограниченное право на использование, копирование,
изменение, слияние, публикацию, распространение, сублицензирование и/или
продажу копий Программного обеспечения, а также лицам, которым предоставляется
данное Программное обеспечение, при соблюдении следующих условий:

Указанное выше уведомление об авторском праве и данные условия должны быть
включены во все копии или значимые части данного Программного обеспечения.

ДАННОЕ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ «КАК ЕСТЬ», БЕЗ КАКИХ-ЛИБО
ГАРАНТИЙ, ЯВНО ВЫРАЖЕННЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ, ВКЛЮЧАЯ ГАРАНТИИ ТОВАРНОЙ
ПРИГОДНОСТИ, СООТВЕТСТВИЯ ПО ЕГО КОНКРЕТНОМУ НАЗНАЧЕНИЮ И ОТСУТСТВИЯ НАРУШЕНИЙ,
НО НЕ ОГРАНИЧИВАЯСЬ ИМИ. НИ В КАКОМ СЛУЧАЕ АВТОРЫ ИЛИ ПРАВООБЛАДАТЕЛИ НЕ НЕСУТ
ОТВЕТСТВЕННОСТИ ПО КАКИМ-ЛИБО ИСКАМ, ЗА УЩЕРБ ИЛИ ПО ИНЫМ ТРЕБОВАНИЯМ, В ТОМ
ЧИСЛЕ, ПРИ ДЕЙСТВИИ КОНТРАКТА, ДЕЛИКТЕ ИЛИ ИНОЙ СИТУАЦИИ, ВОЗНИКШИМ ИЗ-ЗА
ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ ИЛИ ИНЫХ ДЕЙСТВИЙ С ПРОГРАММНЫМ
ОБЕСПЕЧЕНИЕМ.