repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/test/Encryption/AbstractEncryptionTest.php
test/Encryption/AbstractEncryptionTest.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\PdfTest\Encryption; use Bacon\Pdf\Encryption\AbstractEncryption; use Bacon\Pdf\Encryption\Pdf11Encryption; use Bacon\Pdf\Encryption\Pdf14Encryption; use Bacon\Pdf\Encryption\Pdf16Encryption; use Bacon\Pdf\Encryption\Permissions; use Bacon\Pdf\Exception\UnexpectedValueException; use Bacon\Pdf\Exception\UnsupportedPasswordException; use Bacon\Pdf\Options\EncryptionOptions; use PHPUnit_Framework_TestCase as TestCase; /** * @covers \Bacon\Pdf\Encryption\AbstractEncryption */ class AbstractEncryptionTest extends TestCase { public function testForPdfVersion() { $this->assertInstanceOf( Pdf11Encryption::class, AbstractEncryption::forPdfVersion('1.3', '', new EncryptionOptions('')) ); $this->assertInstanceOf( Pdf14Encryption::class, AbstractEncryption::forPdfVersion('1.4', '', new EncryptionOptions('')) ); $this->assertInstanceOf( Pdf14Encryption::class, AbstractEncryption::forPdfVersion('1.5', '', new EncryptionOptions('')) ); $this->assertInstanceOf( Pdf16Encryption::class, AbstractEncryption::forPdfVersion('1.6', '', new EncryptionOptions('')) ); $this->assertInstanceOf( Pdf16Encryption::class, AbstractEncryption::forPdfVersion('1.7', '', new EncryptionOptions('')) ); } public function testTooLongishUserPassword() { $this->setExpectedException(UnsupportedPasswordException::class, 'Password is longer than 32 characters'); $this->getAbstractEncryption()->__construct('', str_repeat('a', 33), '', Permissions::allowNothing()); } public function testTooLongishOwnerPassword() { $this->setExpectedException(UnsupportedPasswordException::class, 'Password is longer than 32 characters'); $this->getAbstractEncryption()->__construct('', '', str_repeat('a', 33), Permissions::allowNothing()); } public function testUserPasswordWithInvalidCharacters() { $this->setExpectedException(UnsupportedPasswordException::class, 'Password contains non-latin-1 characters'); $this->getAbstractEncryption()->__construct('', 'Ŧ', '', Permissions::allowNothing()); } public function testOwnerPasswordWithInvalidCharacters() { $this->setExpectedException(UnsupportedPasswordException::class, 'Password contains non-latin-1 characters'); $this->getAbstractEncryption()->__construct('', '', 'Ŧ', Permissions::allowNothing()); } public function testAbstractReturnsInvalidKeyLength() { $this->setExpectedException(UnexpectedValueException::class, 'Key length must be either 40 or 128'); $this->getAbstractEncryption(100)->__construct('', '', '', Permissions::allowNothing()); } /** * @return AbstractEncryption */ private function getAbstractEncryption($keyLength = 128) { $encryption = $this->getMockForAbstractClass(AbstractEncryption::class, [], '', false); $encryption->expects($this->any())->method('getKeyLength')->willReturn($keyLength); $encryption->expects($this->any())->method('getRevision')->willReturn(2); $encryption->expects($this->any())->method('getAlgorithm')->willReturn(1); return $encryption; } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/test/Encryption/Pdf16EncryptionTest.php
test/Encryption/Pdf16EncryptionTest.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\PdfTest\Encryption; use Bacon\Pdf\Encryption\Pdf16Encryption; use Bacon\Pdf\Encryption\Permissions; /** * @covers \Bacon\Pdf\Encryption\AbstractEncryption * @covers \Bacon\Pdf\Encryption\Pdf16Encryption */ class Pdf16EncryptionTest extends AbstractEncryptionTestCase { /** * {@inheritdoc} */ public function encryptionTestData() { return [ 'same-numbers' => ['test', 'foo', null, 1, 1], 'changed-generation-number' => ['test', 'foo', null, 1, 2], 'changed-object-number' => ['test', 'foo', null, 2, 1], 'both-numbers-changed' => ['test', 'foo', null, 2, 2], 'changed-user-password' => ['test', 'bar', null, 1, 1], 'added-owner-password' => ['test', 'bar', 'baz', 1, 1], ]; } /** * {@inheritdoc} */ protected function createEncryption( $userPassword, $ownerPassword = null, Permissions $userPermissions = null ) { return new Pdf16Encryption( md5('test', true), $userPassword, $ownerPassword ?: $userPassword, $userPermissions ?: Permissions::allowNothing() ); } /** * {@inheritdoc} */ protected function decrypt($encryptedText, $key) { return openssl_decrypt( substr($encryptedText, 16), 'aes-128-cbc', $key, OPENSSL_RAW_DATA, substr($encryptedText, 0, 16) ); } /** * {@inheritdoc} */ protected function getExpectedEntry() { return file_get_contents(__DIR__ . '/_files/pdf16-encrypt-entry.txt'); } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/test/Encryption/NullEncryptionTest.php
test/Encryption/NullEncryptionTest.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\PdfTest\Encryption; use Bacon\Pdf\Encryption\NullEncryption; use Bacon\PdfTest\TestHelper\MemoryObjectWriter; use PHPUnit_Framework_TestCase as TestCase; /** * @covers \Bacon\Pdf\Encryption\NullEncryption */ class NullEncryptionTest extends TestCase { public function testEncryptReturnsPlaintext() { $encryption = new NullEncryption(); $this->assertSame('foo', $encryption->encrypt('foo', 1, 1)); } public function testWriteEncryptEntryWritesNothing() { $encryption = new NullEncryption(); $objectWriter = new MemoryObjectWriter(); $encryption->writeEncryptEntry($objectWriter); $this->assertSame('', $objectWriter->getData()); } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/test/TestHelper/MemoryObjectWriter.php
test/TestHelper/MemoryObjectWriter.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\PdfTest\TestHelper; use Bacon\Pdf\Exception\InvalidArgumentException; use Bacon\Pdf\Writer\ObjectWriter; use SplFileObject; /** * This is a memory object writer which will ignore formatting for predictable test data. */ class MemoryObjectWriter extends ObjectWriter { /** * @var SplFileObject */ private $fileObject; /** * {@inheritdoc} */ public function __construct() { $this->fileObject = new SplFileObject('php://memory', 'w+b'); } /** * {@inheritdoc} */ public function writeRawLine($data) { $this->fileObject->fwrite($data. "\n"); } /** * {@inheritdoc} */ public function currentOffset() { return $this->fileObject->ftell(); } /** * {@inheritdoc} */ public function startDictionary() { $this->fileObject->fwrite("<<\n"); } /** * {@inheritdoc} */ public function endDictionary() { $this->fileObject->fwrite(">>\n"); } /** * {@inheritdoc} */ public function startArray() { $this->fileObject->fwrite("]\n"); } /** * {@inheritdoc} */ public function endArray() { $this->fileObject->fwrite("[\n"); } /** * {@inheritdoc} */ public function writeNull() { $this->fileObject->fwrite("null\n"); } /** * {@inheritdoc} */ public function writeBoolean($boolean) { $this->fileObject->fwrite(($boolean ? 'true' : 'false') . "\n"); } /** * {@inheritdoc} */ public function writeNumber($number) { if (is_int($number)) { $value = (string) $number; } elseif (is_float($number)) { $value = sprintf('%F', $number); } else { throw new InvalidArgumentException(sprintf( 'Expected int or float, got %s', gettype($number) )); } $this->fileObject->fwrite($value . "\n"); } /** * {@inheritdoc} */ public function writeName($name) { $this->fileObject->fwrite('/' . $name . "\n"); } /** * {@inheritdoc} */ public function writeLiteralString($string) { $this->fileObject->fwrite('(' . strtr($string, ['(' => '\\(', ')' => '\\)', '\\' => '\\\\']) . ")\n"); } /** * {@inheritdoc} */ public function writeHexadecimalString($string) { $this->fileObject->fwrite('<' . bin2hex($string) . ">\n"); } /** * @return string */ public function getData() { $currentPos = $this->fileObject->ftell(); if ($currentPos === 0) { return ''; } $this->fileObject->fseek(0); $data = $this->fileObject->fread($currentPos); $this->fileObject->fseek($currentPos); return $data; } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/test/Writer/ObjectWriterTest.php
test/Writer/ObjectWriterTest.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace Bacon\PdfTest\Writer; use Bacon\Pdf\Writer\ObjectWriter; use PHPUnit_Framework_TestCase as TestCase; use SplFileObject; /** * @covers \Bacon\Pdf\Writer\ObjectWriter */ class ObjectWriterTest extends TestCase { /** * @var SplFileObject */ private $fileObject; /** * @var ObjectWriter */ private $objectWriter; /** * {@inheritdoc} */ public function setUp() { $this->fileObject = new SplFileObject('php://memory', 'w+b'); $this->objectWriter = new ObjectWriter($this->fileObject); } public function testGetCurrentOffset() { $this->assertSame(0, $this->objectWriter->getCurrentOffset()); $this->fileObject->fwrite('foo'); $this->assertSame(3, $this->objectWriter->getCurrentOffset()); } public function testObjectNumberAllocation() { $this->assertSame(1, $this->objectWriter->allocateObjectId()); $this->assertSame(2, $this->objectWriter->allocateObjectId()); $this->assertSame(3, $this->objectWriter->allocateObjectId()); } public function testGetObjectOffsets() { $this->objectWriter->startObject(); $this->objectWriter->startObject(); $this->objectWriter->startObject(); $this->assertSame([1 => 0, 2 => 8, 3 => 16], $this->objectWriter->getObjectOffsets()); } public function testStartObjectWithoutObjectId() { $this->objectWriter->startObject(); $this->objectWriter->startObject(); $this->assertSame("1 0 obj\n2 0 obj\n", $this->getFileObjectData()); } public function testStartObjectWithObjectId() { $this->objectWriter->startObject(10); $this->assertSame("10 0 obj\n", $this->getFileObjectData()); } public function testWriteIndirectReference() { $this->objectWriter->writeIndirectReference(1); $this->assertSame('1 0 R', $this->getFileObjectData()); } public function testEndObject() { $this->objectWriter->endObject(); $this->assertSame("\nendobj\n", $this->getFileObjectData()); } public function testWriteRawLine() { $this->objectWriter->writeRawLine('foo'); $this->assertSame("foo\n", $this->getFileObjectData()); } public function testStartDictionary() { $this->objectWriter->startDictionary(); $this->assertSame('<<', $this->getFileObjectData()); } public function testEndDictionary() { $this->objectWriter->endDictionary(); $this->assertSame('>>', $this->getFileObjectData()); } public function testStartArray() { $this->objectWriter->startArray(); $this->assertSame('[', $this->getFileObjectData()); } public function testEndArray() { $this->objectWriter->endArray(); $this->assertSame(']', $this->getFileObjectData()); } public function testWriteNull() { $this->objectWriter->writeNull(); $this->assertSame('null', $this->getFileObjectData()); } public function testWriteBooleanTrue() { $this->objectWriter->writeBoolean(true); $this->assertSame('true', $this->getFileObjectData()); } public function testWriteBooleanFalse() { $this->objectWriter->writeBoolean(false); $this->assertSame('false', $this->getFileObjectData()); } public function testWriteIntegerNumber() { $this->objectWriter->writeNumber(0); $this->assertSame('0', $this->getFileObjectData()); $this->objectWriter->writeNumber(12); $this->assertSame('0 12', $this->getFileObjectData()); $this->objectWriter->writeNumber(0); $this->assertSame('0 12 0', $this->getFileObjectData()); } public function testWriteFloatNumber() { $this->objectWriter->writeNumber(12.3456789123); $this->assertSame('12.345679', $this->getFileObjectData()); $this->objectWriter->writeNumber(12.); $this->assertSame('12.345679 12', $this->getFileObjectData()); } public function testWriteName() { $this->objectWriter->writeName('foo'); $this->assertSame('/foo', $this->getFileObjectData()); } public function testWriteLiteralString() { $this->objectWriter->writeLiteralString('foo(bar\\baz)bat'); $this->assertSame('(foo\\(bar\\\\baz\\)bat)', $this->getFileObjectData()); } public function testWriteHexadecimalString() { $this->objectWriter->writeHexadecimalString('foo'); $this->assertSame('<666f6f>', $this->getFileObjectData()); } /** * @dataProvider whitespaceTestData */ public function testWhitespaceHandling(array $methodCalls, $expectedData) { foreach ($methodCalls as $methodCall) { if (!array_key_exists(1, $methodCall)) { $methodCall[1] = []; } call_user_func_array([$this->objectWriter, $methodCall[0]], $methodCall[1]); } $this->assertSame($expectedData, $this->getFileObjectData()); } /** * @return array */ public function whitespaceTestData() { return [ [[ ['writeIndirectReference', [1]], ['writeIndirectReference', [2]], ], '1 0 R 2 0 R'], [[ ['startDictionary'], ['endDictionary'], ], '<<>>'], [[ ['startArray'], ['endArray'], ], '[]'], [[ ['startDictionary'], ['writeNull'], ['endDictionary'], ], '<<null>>'], [[ ['startArray'], ['writeNull'], ['endArray'], ], '[null]'], [[ ['writeNull'], ['writeNull'], ], 'null null'], [[ ['writeBoolean', [true]], ['writeBoolean', [false]], ], 'true false'], [[ ['writeNumber', [1]], ['writeNumber', [1.1]], ], '1 1.1'], [[ ['writeNumber', [0]], ['writeNumber', [0.0]], ], '0 0'], [[ ['writeLiteralString', ['foo']], ['writeLiteralString', ['bar']], ], '(foo)(bar)'], [[ ['writeHexadecimalString', ['foo']], ['writeHexadecimalString', ['bar']], ], '<666f6f><626172>'], [[ ['writeNull'], ['writeRawLine', ['foo']], ], "nullfoo\n"], ]; } /** * @return string */ private function getFileObjectData() { $offset = $this->fileObject->ftell(); $this->fileObject->fseek(0); $data = $this->fileObject->fread($offset); $this->fileObject->fseek($offset); return $data; } }
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
Bacon/BaconPdf
https://github.com/Bacon/BaconPdf/blob/5f2e6b4eea079d5311111b80a53f6e5d3d3d4630/example/empty-page.php
example/empty-page.php
<?php /** * BaconPdf * * @link http://github.com/Bacon/BaconPdf For the canonical source repository * @copyright 2015 Ben Scholzen (DASPRiD) * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ use Bacon\Pdf\PdfWriter; require_once __DIR__ . '/../vendor/autoload.php'; $writer = PdfWriter::toFile(__DIR__ . '/empty-page.pdf'); $writer->getDocumentInformation()->set('Title', 'Empty Page Example'); $writer->addPage(595, 842); $writer->endDocument();
php
BSD-2-Clause
5f2e6b4eea079d5311111b80a53f6e5d3d3d4630
2026-01-05T04:48:03.848172Z
false
shvetsgroup/laravel-email-database-log
https://github.com/shvetsgroup/laravel-email-database-log/blob/8ba15db6ab9c0e3824548db74f1f3f290f840cfc/src/ShvetsGroup/LaravelEmailDatabaseLog/LaravelEmailDatabaseLogServiceProvider.php
src/ShvetsGroup/LaravelEmailDatabaseLog/LaravelEmailDatabaseLogServiceProvider.php
<?php namespace ShvetsGroup\LaravelEmailDatabaseLog; use Illuminate\Support\ServiceProvider; class LaravelEmailDatabaseLogServiceProvider extends ServiceProvider { /** * Register any other events for your application. * * @return void */ public function boot() { // } /** * Register any application services. * * @return void */ public function register() { $this->app->register(LaravelEmailDatabaseLogEventServiceProvider::class); if ($this->app->runningInConsole()) { $this->publishes([ __DIR__ . '/../../database/migrations' => database_path('migrations'), ], 'laravel-email-database-log-migration'); } } }
php
MIT
8ba15db6ab9c0e3824548db74f1f3f290f840cfc
2026-01-05T04:48:11.321673Z
false
shvetsgroup/laravel-email-database-log
https://github.com/shvetsgroup/laravel-email-database-log/blob/8ba15db6ab9c0e3824548db74f1f3f290f840cfc/src/ShvetsGroup/LaravelEmailDatabaseLog/EmailLogger.php
src/ShvetsGroup/LaravelEmailDatabaseLog/EmailLogger.php
<?php namespace ShvetsGroup\LaravelEmailDatabaseLog; use Carbon\Carbon; use Symfony\Component\Mime\Email; use Illuminate\Support\Facades\DB; use Symfony\Component\Mime\Part\DataPart; use Illuminate\Mail\Events\MessageSending; class EmailLogger { /** * Handle the actual logging. * * @param MessageSending $event * @return void */ public function handle(MessageSending $event): void { $message = $event->message; DB::table('email_log')->insert([ 'date' => Carbon::now()->format('Y-m-d H:i:s'), 'from' => $this->formatAddressField($message, 'From'), 'to' => $this->formatAddressField($message, 'To'), 'cc' => $this->formatAddressField($message, 'Cc'), 'bcc' => $this->formatAddressField($message, 'Bcc'), 'subject' => $message->getSubject(), 'body' => $message->getBody()->bodyToString(), 'headers' => $message->getHeaders()->toString(), 'attachments' => $this->saveAttachments($message), ]); } /** * Format address strings for sender, to, cc, bcc. * * @param Email $message * @param string $field * @return null|string */ function formatAddressField(Email $message, string $field): ?string { $headers = $message->getHeaders(); return $headers->get($field)?->getBodyAsString(); } /** * Collect all attachments and format them as strings. * * @param Email $message * @return string|null */ protected function saveAttachments(Email $message): ?string { if (empty($message->getAttachments())) { return null; } return collect($message->getAttachments()) ->map(fn(DataPart $part) => $part->toString()) ->implode("\n\n"); } }
php
MIT
8ba15db6ab9c0e3824548db74f1f3f290f840cfc
2026-01-05T04:48:11.321673Z
false
shvetsgroup/laravel-email-database-log
https://github.com/shvetsgroup/laravel-email-database-log/blob/8ba15db6ab9c0e3824548db74f1f3f290f840cfc/src/ShvetsGroup/LaravelEmailDatabaseLog/LaravelEmailDatabaseLogEventServiceProvider.php
src/ShvetsGroup/LaravelEmailDatabaseLog/LaravelEmailDatabaseLogEventServiceProvider.php
<?php namespace ShvetsGroup\LaravelEmailDatabaseLog; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; use Illuminate\Mail\Events\MessageSending; class LaravelEmailDatabaseLogEventServiceProvider extends ServiceProvider { /** * The event listener mappings for the application. * * @var array */ protected $listen = [ MessageSending::class => [ EmailLogger::class, ], ]; }
php
MIT
8ba15db6ab9c0e3824548db74f1f3f290f840cfc
2026-01-05T04:48:11.321673Z
false
shvetsgroup/laravel-email-database-log
https://github.com/shvetsgroup/laravel-email-database-log/blob/8ba15db6ab9c0e3824548db74f1f3f290f840cfc/src/database/migrations/2017_11_10_001638_add_more_mail_columns_email_log.php
src/database/migrations/2017_11_10_001638_add_more_mail_columns_email_log.php
<?php use Illuminate\Database\Migrations\Migration; class AddMoreMailColumnsEmailLog extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('email_log', function ($table) { if (!Schema::hasColumn('email_log', 'id')) { $table->increments('id')->first(); $table->string('from')->after('date')->nullable(); $table->string('cc')->after('to')->nullable(); $table->text('headers')->after('body')->nullable(); $table->text('attachments')->after('headers')->nullable(); } }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('email_log', function ($table) { $table->dropColumn(['id', 'from', 'cc', 'headers', 'attachments']); }); } }
php
MIT
8ba15db6ab9c0e3824548db74f1f3f290f840cfc
2026-01-05T04:48:11.321673Z
false
shvetsgroup/laravel-email-database-log
https://github.com/shvetsgroup/laravel-email-database-log/blob/8ba15db6ab9c0e3824548db74f1f3f290f840cfc/src/database/migrations/2018_05_11_115355_use_longtext_for_attachments.php
src/database/migrations/2018_05_11_115355_use_longtext_for_attachments.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class UseLongtextForAttachments extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('email_log', function (Blueprint $table) { $table->longText('attachments')->nullable()->change(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('email_log', function (Blueprint $table) { $table->text('attachments')->nullable()->change(); }); } }
php
MIT
8ba15db6ab9c0e3824548db74f1f3f290f840cfc
2026-01-05T04:48:11.321673Z
false
shvetsgroup/laravel-email-database-log
https://github.com/shvetsgroup/laravel-email-database-log/blob/8ba15db6ab9c0e3824548db74f1f3f290f840cfc/src/database/migrations/2016_09_21_001638_add_bcc_column_email_log.php
src/database/migrations/2016_09_21_001638_add_bcc_column_email_log.php
<?php use Illuminate\Database\Migrations\Migration; class AddBccColumnEmailLog extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('email_log', function ($table) { if (!Schema::hasColumn('email_log', 'bcc')) { $table->string('to')->nullable()->change(); $table->string('bcc')->after('to')->nullable(); } }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('email_log', function ($table) { $table->string('to')->change(); $table->dropColumn('bcc'); }); } }
php
MIT
8ba15db6ab9c0e3824548db74f1f3f290f840cfc
2026-01-05T04:48:11.321673Z
false
shvetsgroup/laravel-email-database-log
https://github.com/shvetsgroup/laravel-email-database-log/blob/8ba15db6ab9c0e3824548db74f1f3f290f840cfc/src/database/migrations/2015_07_31_1_email_log.php
src/database/migrations/2015_07_31_1_email_log.php
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class EmailLog extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('email_log', function (Blueprint $table) { $table->increments('id'); $table->dateTime('date'); $table->string('from')->nullable(); $table->string('to')->nullable(); $table->string('cc')->nullable(); $table->string('bcc')->nullable(); $table->string('subject'); $table->text('body'); $table->text('headers')->nullable(); $table->text('attachments')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('email_log'); } }
php
MIT
8ba15db6ab9c0e3824548db74f1f3f290f840cfc
2026-01-05T04:48:11.321673Z
false
shvetsgroup/laravel-email-database-log
https://github.com/shvetsgroup/laravel-email-database-log/blob/8ba15db6ab9c0e3824548db74f1f3f290f840cfc/tests/TestCase.php
tests/TestCase.php
<?php namespace ShvetsGroup\LaravelEmailDatabaseLog\Tests; use ShvetsGroup\LaravelEmailDatabaseLog\LaravelEmailDatabaseLogServiceProvider; class TestCase extends \Orchestra\Testbench\TestCase { public function getEnvironmentSetUp($app) { // import the migrations include_once __DIR__ . '/../src/database/migrations/2015_07_31_1_email_log.php'; include_once __DIR__ . '/../src/database/migrations/2016_09_21_001638_add_bcc_column_email_log.php'; include_once __DIR__ . '/../src/database/migrations/2017_11_10_001638_add_more_mail_columns_email_log.php'; include_once __DIR__ . '/../src/database/migrations/2018_05_11_115355_use_longtext_for_attachments.php'; // run the up() method of those migration classes (new \EmailLog)->up(); (new \AddBccColumnEmailLog)->up(); (new \AddMoreMailColumnsEmailLog)->up(); (new \UseLongtextForAttachments)->up(); } protected function getPackageProviders($app) { return [ LaravelEmailDatabaseLogServiceProvider::class, ]; } }
php
MIT
8ba15db6ab9c0e3824548db74f1f3f290f840cfc
2026-01-05T04:48:11.321673Z
false
shvetsgroup/laravel-email-database-log
https://github.com/shvetsgroup/laravel-email-database-log/blob/8ba15db6ab9c0e3824548db74f1f3f290f840cfc/tests/Mail/TestMailWithAttachment.php
tests/Mail/TestMailWithAttachment.php
<?php namespace ShvetsGroup\LaravelEmailDatabaseLog\Tests\Mail; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; class TestMailWithAttachment extends Mailable { use Queueable, SerializesModels; /** * Create a new message instance. * * @return void */ public function __construct() { // } /** * Build the message. * * @return $this */ public function build() { return $this ->subject('The e-mail subject') ->attach(__DIR__ . '/../stubs/demo.txt') ->html('<p>Some random string.</p>'); } }
php
MIT
8ba15db6ab9c0e3824548db74f1f3f290f840cfc
2026-01-05T04:48:11.321673Z
false
shvetsgroup/laravel-email-database-log
https://github.com/shvetsgroup/laravel-email-database-log/blob/8ba15db6ab9c0e3824548db74f1f3f290f840cfc/tests/Mail/TestMail.php
tests/Mail/TestMail.php
<?php namespace ShvetsGroup\LaravelEmailDatabaseLog\Tests\Mail; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; class TestMail extends Mailable { use Queueable, SerializesModels; /** * Create a new message instance. * * @return void */ public function __construct() { // } /** * Build the message. * * @return $this */ public function build() { return $this ->subject('The e-mail subject') ->html('<p>Some random string.</p>'); } }
php
MIT
8ba15db6ab9c0e3824548db74f1f3f290f840cfc
2026-01-05T04:48:11.321673Z
false
shvetsgroup/laravel-email-database-log
https://github.com/shvetsgroup/laravel-email-database-log/blob/8ba15db6ab9c0e3824548db74f1f3f290f840cfc/tests/Feature/LaravelEmailDatabaseTest.php
tests/Feature/LaravelEmailDatabaseTest.php
<?php namespace ShvetsGroup\LaravelEmailDatabaseLog\Tests\Feature; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Mail; use Symfony\Component\Mime\Encoder\Base64Encoder; use Illuminate\Foundation\Testing\RefreshDatabase; use ShvetsGroup\LaravelEmailDatabaseLog\Tests\TestCase; use ShvetsGroup\LaravelEmailDatabaseLog\Tests\Mail\TestMail; use ShvetsGroup\LaravelEmailDatabaseLog\Tests\Mail\TestMailWithAttachment; class LaravelEmailDatabaseTest extends TestCase { use RefreshDatabase; /** @test */ public function the_email_is_logged_to_the_database() { Mail::to('email@example.com') ->send(new TestMail()); $this->assertDatabaseHas('email_log', [ 'date' => now()->format('Y-m-d H:i:s'), 'from' => 'Example <hello@example.com>', 'to' => 'email@example.com', 'cc' => null, 'bcc' => null, 'subject' => 'The e-mail subject', 'body' => '<p>Some random string.</p>', 'attachments' => null, ]); } /** @test */ public function multiple_recipients_are_comma_separated() { Mail::to(['email@example.com', 'email2@example.com']) ->send(new TestMail()); $this->assertDatabaseHas('email_log', [ 'date' => now()->format('Y-m-d H:i:s'), 'to' => 'email@example.com, email2@example.com', 'cc' => null, 'bcc' => null, ]); } /** @test */ public function recipient_with_name_is_correctly_formatted() { Mail::to((object)['email' => 'email@example.com', 'name' => 'John Do']) ->send(new TestMail()); $this->assertDatabaseHas('email_log', [ 'date' => now()->format('Y-m-d H:i:s'), 'to' => 'John Do <email@example.com>', 'cc' => null, 'bcc' => null, ]); } /** @test */ public function cc_recipient_with_name_is_correctly_formatted() { Mail::cc((object)['email' => 'email@example.com', 'name' => 'John Do']) ->send(new TestMail()); $this->assertDatabaseHas('email_log', [ 'date' => now()->format('Y-m-d H:i:s'), 'to' => null, 'cc' => 'John Do <email@example.com>', 'bcc' => null, ]); } /** @test */ public function bcc_recipient_with_name_is_correctly_formatted() { Mail::bcc((object)['email' => 'email@example.com', 'name' => 'John Do']) ->send(new TestMail()); $this->assertDatabaseHas('email_log', [ 'date' => now()->format('Y-m-d H:i:s'), 'to' => null, 'cc' => null, 'bcc' => 'John Do <email@example.com>', ]); } /** @test */ public function attachement_is_saved() { Mail::to('email@example.com')->send(new TestMailWithAttachment()); $log = DB::table('email_log')->first(); // TODO: Is there a beter way to tests this ? $encoded = (new Base64Encoder)->encodeString(file_get_contents(__DIR__ . '/../stubs/demo.txt')); $this->assertStringContainsString('Content-Type: text/plain; name=demo.txt', $log->attachments); $this->assertStringContainsString('Content-Transfer-Encoding: base64', $log->attachments); $this->assertStringContainsString('Content-Disposition: attachment; name=demo.txt; filename=demo.txt', $log->attachments); $this->assertStringContainsString($encoded, $log->attachments); } }
php
MIT
8ba15db6ab9c0e3824548db74f1f3f290f840cfc
2026-01-05T04:48:11.321673Z
false
aldemeery/sieve
https://github.com/aldemeery/sieve/blob/8c13c8b3638b3ffa4fc56d7288e7e0b3389cb78f/src/SieveServiceProvider.php
src/SieveServiceProvider.php
<?php declare(strict_types=1); namespace Aldemeery\Sieve; use Aldemeery\Sieve\Commands\FilterMakeCommand; use Illuminate\Support\ServiceProvider; class SieveServiceProvider extends ServiceProvider { public function boot(): void { if ($this->app->runningInConsole()) { $this->commands([ FilterMakeCommand::class, ]); } } }
php
MIT
8c13c8b3638b3ffa4fc56d7288e7e0b3389cb78f
2026-01-05T04:48:20.018527Z
false
aldemeery/sieve
https://github.com/aldemeery/sieve/blob/8c13c8b3638b3ffa4fc56d7288e7e0b3389cb78f/src/Contracts/Filter.php
src/Contracts/Filter.php
<?php declare(strict_types=1); namespace Aldemeery\Sieve\Contracts; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; /** @template Filterable of Model */ interface Filter { public function map(mixed $value): mixed; /** @param Builder<Filterable> $query */ public function apply(Builder $query, mixed $value): void; }
php
MIT
8c13c8b3638b3ffa4fc56d7288e7e0b3389cb78f
2026-01-05T04:48:20.018527Z
false
aldemeery/sieve
https://github.com/aldemeery/sieve/blob/8c13c8b3638b3ffa4fc56d7288e7e0b3389cb78f/src/Concerns/Filterable.php
src/Concerns/Filterable.php
<?php declare(strict_types=1); namespace Aldemeery\Sieve\Concerns; use Aldemeery\Onion; use Aldemeery\Sieve\Contracts\Filter; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\App; use RuntimeException; trait Filterable { /** * @param Builder<Model> $query * @param array<string, mixed> $params * @param array<string, mixed> $additional */ protected function scopeFilter(Builder $query, array $params = [], array $additional = []): void { Onion\onion([ fn (array $filters): array => array_merge($filters, $additional), fn (array $filters): array => array_intersect_key($filters, $params), fn (array $filters): array => array_map( function (string $filter): Filter { $filter = App::make($filter); if (!$filter instanceof Filter) { throw new RuntimeException(sprintf( 'Filters must implement %s, but %s does not.', Filter::class, is_object($filter) ? get_class($filter) : gettype($filter), )); } return $filter; }, $filters, ), fn (array $filters): true => array_walk( $filters, fn (Filter $filter, string $key) => $filter->apply($query, $filter->map($params[$key])), ), ])->withoutExceptionHandling()->peel($this->filters()); } /** @return array<string, string> */ private function filters(): array { return [ // "filter-name" => \FilterCalss::class ]; } }
php
MIT
8c13c8b3638b3ffa4fc56d7288e7e0b3389cb78f
2026-01-05T04:48:20.018527Z
false
aldemeery/sieve
https://github.com/aldemeery/sieve/blob/8c13c8b3638b3ffa4fc56d7288e7e0b3389cb78f/src/Commands/FilterMakeCommand.php
src/Commands/FilterMakeCommand.php
<?php declare(strict_types=1); namespace Aldemeery\Sieve\Commands; use Illuminate\Console\GeneratorCommand; class FilterMakeCommand extends GeneratorCommand { /** * The console command name. * * @var string */ protected $name = 'make:filter'; /** * The console command description. * * @var string */ protected $description = 'Create a new filter class'; /** * Get the stub file for the generator. * * @return string */ protected function getStub() { return __DIR__ . '/../../stubs/filter.stub'; } /** * Get the default namespace for the class. * * @param string $rootNamespace * * @return string */ protected function getDefaultNamespace($rootNamespace) { return $rootNamespace . '\Filters'; } }
php
MIT
8c13c8b3638b3ffa4fc56d7288e7e0b3389cb78f
2026-01-05T04:48:20.018527Z
false
aldemeery/sieve
https://github.com/aldemeery/sieve/blob/8c13c8b3638b3ffa4fc56d7288e7e0b3389cb78f/tests/ModelWithoutFilters.php
tests/ModelWithoutFilters.php
<?php declare(strict_types=1); namespace Tests\Aldemeery\Sieve; use Aldemeery\Sieve\Concerns\Filterable; use Illuminate\Database\Eloquent\Model; /** @method \Illuminate\Database\Eloquent\Builder filter(array $params = [], array $additional = []) */ class ModelWithoutFilters extends Model { use Filterable; protected $table = 'tests'; }
php
MIT
8c13c8b3638b3ffa4fc56d7288e7e0b3389cb78f
2026-01-05T04:48:20.018527Z
false
aldemeery/sieve
https://github.com/aldemeery/sieve/blob/8c13c8b3638b3ffa4fc56d7288e7e0b3389cb78f/tests/BadFilter.php
tests/BadFilter.php
<?php declare(strict_types=1); namespace Tests\Aldemeery\Sieve; use Illuminate\Database\Eloquent\Builder; class BadFilter { public function map(mixed $value): mixed { return match ($value) { default => $value, }; } /** @param Builder<ModelWithoutFilters> $query */ public function apply(Builder $query, mixed $value): void { $query->where('test', $value); } }
php
MIT
8c13c8b3638b3ffa4fc56d7288e7e0b3389cb78f
2026-01-05T04:48:20.018527Z
false
aldemeery/sieve
https://github.com/aldemeery/sieve/blob/8c13c8b3638b3ffa4fc56d7288e7e0b3389cb78f/tests/ModelWithFilters.php
tests/ModelWithFilters.php
<?php declare(strict_types=1); namespace Tests\Aldemeery\Sieve; use Aldemeery\Sieve\Concerns\Filterable; use Illuminate\Database\Eloquent\Model; /** @method \Illuminate\Database\Eloquent\Builder filter(array $params = [], array $additional = []) */ class ModelWithFilters extends Model { use Filterable; protected $table = 'tests'; /** @return array<string, string> */ private function filters(): array { return [ 'test-1' => TestFilter::class, 'test-2' => TestFilter::class, ]; } }
php
MIT
8c13c8b3638b3ffa4fc56d7288e7e0b3389cb78f
2026-01-05T04:48:20.018527Z
false
aldemeery/sieve
https://github.com/aldemeery/sieve/blob/8c13c8b3638b3ffa4fc56d7288e7e0b3389cb78f/tests/TestFilter.php
tests/TestFilter.php
<?php declare(strict_types=1); namespace Tests\Aldemeery\Sieve; use Aldemeery\Sieve\Contracts\Filter; use Illuminate\Database\Eloquent\Builder; /** @implements Filter<ModelWithFilters> */ class TestFilter implements Filter { public function map(mixed $value): mixed { return match ($value) { default => $value, }; } public function apply(Builder $query, mixed $value): void { $query->where('test', $value); } }
php
MIT
8c13c8b3638b3ffa4fc56d7288e7e0b3389cb78f
2026-01-05T04:48:20.018527Z
false
aldemeery/sieve
https://github.com/aldemeery/sieve/blob/8c13c8b3638b3ffa4fc56d7288e7e0b3389cb78f/tests/Concerns/FilterableTest.php
tests/Concerns/FilterableTest.php
<?php declare(strict_types=1); namespace Tests\Aldemeery\Sieve\Concerns; use Illuminate\Database\Connection; use Illuminate\Database\ConnectionResolver; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\App; use PDO; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; use RuntimeException; use Tests\Aldemeery\Sieve\BadFilter; use Tests\Aldemeery\Sieve\ModelWithFilters; use Tests\Aldemeery\Sieve\ModelWithoutFilters; use Tests\Aldemeery\Sieve\TestFilter; #[CoversClass(ModelWithFilters::class)] #[CoversClass(ModelWithoutFilters::class)] class FilterableTest extends TestCase { protected function setUp(): void { parent::setUp(); Model::setConnectionResolver(new class () extends ConnectionResolver { public function __construct() { parent::__construct([ null => new class () extends Connection { public function __construct() { parent::__construct(new PDO('sqlite::memory:')); } }, ]); } }); } public function test_has_no_filters_by_default(): void { App::shouldReceive('make')->with(TestFilter::class)->andReturn(new TestFilter()); $filterable = new ModelWithoutFilters(); $query = $filterable->filter(['test-1' => 'one', 'test-2' => 'two', 'test-3' => 'three']); static::assertSame('select * from "tests"', $query->toSql()); static::assertSame([], $query->getBindings()); } public function test_filters_are_applied(): void { App::shouldReceive('make')->with(TestFilter::class)->andReturn(new TestFilter()); $filterable = new ModelWithFilters(); $query = $filterable->filter(['test-1' => 'one', 'test-3' => 'three']); static::assertSame('select * from "tests" where "test" = ?', $query->toSql()); static::assertSame(['one'], $query->getBindings()); } public function test_additional_filters_are_applied(): void { App::shouldReceive('make')->with(TestFilter::class)->andReturn(new TestFilter()); $filterable = new ModelWithFilters(); $query = $filterable->filter(['test-1' => 'one', 'test-3' => 'three'], ['test-3' => TestFilter::class]); static::assertSame('select * from "tests" where "test" = ? and "test" = ?', $query->toSql()); static::assertSame(['one', 'three'], $query->getBindings()); } public function test_filters_not_implementing_the_filter_interface_throw_an_exception(): void { App::shouldReceive('make')->with(BadFilter::class)->andReturn(new BadFilter()); $filterable = new ModelWithoutFilters(); static::expectException(RuntimeException::class); static::expectExceptionMessage('Filters must implement Aldemeery\Sieve\Contracts\Filter, but Tests\Aldemeery\Sieve\BadFilter does not.'); $filterable->filter(['test-1' => 'one'], ['test-1' => BadFilter::class]); } }
php
MIT
8c13c8b3638b3ffa4fc56d7288e7e0b3389cb78f
2026-01-05T04:48:20.018527Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/src/Approach.php
src/Approach.php
<?php namespace Laravel\Roster; use Laravel\Roster\Enums\Approaches; class Approach { public function __construct(protected Approaches $approach) {} public function name(): string { return $this->approach->name; } public function approach(): Approaches { return $this->approach; } }
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/src/PackageCollection.php
src/PackageCollection.php
<?php namespace Laravel\Roster; use Illuminate\Support\Collection; /** * @extends Collection<int, Package> */ class PackageCollection extends Collection { public function dev(): static { return $this->filter(fn (Package $package) => $package->isDev()); } public function production(): static { return $this->filter(fn (Package $package) => ! $package->isDev()); } }
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/src/Roster.php
src/Roster.php
<?php namespace Laravel\Roster; use Illuminate\Support\Collection; use Laravel\Roster\Enums\Approaches; use Laravel\Roster\Enums\NodePackageManager; use Laravel\Roster\Enums\Packages; use Laravel\Roster\Scanners\Composer; use Laravel\Roster\Scanners\DirectoryStructure; use Laravel\Roster\Scanners\PackageLock; /** * Package and approach detection service for Laravel projects. * * Scans composer.lock, package-lock.json, and directory structure to identify * packages and development approaches in use. */ class Roster { /** * @var Collection<int, \Laravel\Roster\Approach> */ protected Collection $approaches; protected PackageCollection $packages; protected ?NodePackageManager $nodePackageManager = null; public function __construct() { $this->approaches = collect(); $this->packages = new PackageCollection; } /** * @throws \InvalidArgumentException */ public function add(Package|Approach $item): self { return match (get_class($item)) { Package::class => $this->addPackage($item), Approach::class => $this->addApproach($item), default => throw new \InvalidArgumentException('Unexpected match value'), }; } public function uses(Packages|Approaches $item): bool { return $this->findItem($item) !== null; } /** * @throws \InvalidArgumentException */ public function usesVersion(Packages $package, string $version, string $operator = '='): bool { if (! preg_match('/[0-9]{1,}\.[0-9]{1,}\.[0-9]{1,}/', $version)) { throw new \InvalidArgumentException('SEMVER required'); } $validOperators = ['<', '<=', '>', '>=', '==', '=', '!=', '<>']; if (! in_array($operator, $validOperators)) { throw new \InvalidArgumentException('Invalid operator'); } $package = $this->findItem($package); if (is_null($package)) { return false; } /** @var \Laravel\Roster\Package $package */ return version_compare($package->version(), $version, $operator); } protected function findItem(Packages|Approaches $item): Package|Approach|null { return match (get_class($item)) { Packages::class => $this->package($item), Approaches::class => $this->approach($item), default => null, }; } protected function addPackage(Package $package): self { $this->packages->push($package); return $this; } protected function addApproach(Approach $approach): self { $this->approaches->push($approach); return $this; } /** * @return Collection<int, \Laravel\Roster\Approach> */ public function approaches(): Collection { return $this->approaches; } public function packages(): PackageCollection { return $this->packages; } public function package(Packages $package): ?Package { return $this->packages->first(fn (Package $item) => $item->package()->value === $package->value); } public function approach(Approaches $approach): ?Approach { return $this->approaches->first(fn (Approach $item) => $item->approach()->value === $approach->value); } public function nodePackageManager(): ?NodePackageManager { return $this->nodePackageManager; } public function json(): string { return json_encode([ 'approaches' => $this->approaches->map(fn (Approach $approach) => [ 'name' => $approach->name(), ])->toArray(), 'packages' => $this->packages->map(fn (Package $package) => [ 'name' => $package->name(), 'version' => $package->version(), ])->toArray(), 'nodePackageManager' => $this->nodePackageManager?->value, ], JSON_PRETTY_PRINT) ?: '{}'; } public static function scan(?string $basePath = null): self { $roster = new self; $basePath = ($basePath ?? base_path()).DIRECTORY_SEPARATOR; (new Composer($basePath.'composer.lock')) ->scan() ->each(fn ($item) => $roster->add($item)); $packageLock = new PackageLock($basePath); $packageLock->scan() ->each(fn ($item) => $roster->add($item)); (new DirectoryStructure($basePath)) ->scan() ->each(fn ($item) => $roster->add($item)); $roster->nodePackageManager = $packageLock->detect(); return $roster; } }
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/src/RosterServiceProvider.php
src/RosterServiceProvider.php
<?php namespace Laravel\Roster; use Illuminate\Support\ServiceProvider; class RosterServiceProvider extends ServiceProvider { /** * Bootstrap any package services. */ public function boot(): void { $this->registerCommands(); } /** * Register the package's commands. */ protected function registerCommands(): void { if ($this->app->runningInConsole()) { $this->commands([ Console\ScanCommand::class, ]); } } }
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/src/Package.php
src/Package.php
<?php namespace Laravel\Roster; use Laravel\Roster\Enums\Packages; class Package { protected bool $direct = false; protected string $constraint = ''; public function __construct(protected Packages $package, protected string $packageName, protected string $version, protected bool $dev = false) {} public function setDev(bool $dev = true): self { $this->dev = $dev; return $this; } public function setDirect(bool $direct = true): self { $this->direct = $direct; return $this; } public function setConstraint(string $constraint = ''): self { $this->constraint = $constraint; return $this; } public function name(): string { return $this->package->name; } public function package(): Packages { return $this->package; } public function version(): string { return $this->version; } public function direct(): bool { return $this->direct; } public function indirect(): bool { return ! $this->direct; } public function constraint(): string { return $this->constraint; } public function majorVersion(): string { return explode('.', $this->version)[0]; } public function isDev(): bool { return $this->dev; } public function rawName(): string { return $this->packageName; } }
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/src/Console/ScanCommand.php
src/Console/ScanCommand.php
<?php namespace Laravel\Roster\Console; use Illuminate\Console\Command; use Laravel\Roster\Roster; class ScanCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'roster:scan {directory}'; protected $description = 'Detect packages & approaches in use and output as JSON'; public function handle(): int { $directory = $this->argument('directory'); if (! is_string($directory)) { $this->error('Pass a directory'); return self::FAILURE; } if (! is_dir($directory) || ! is_readable($directory)) { $this->error("Directory '{$directory}' isn't a directory"); return self::FAILURE; } $roster = Roster::scan($directory); $this->line($roster->json()); return self::SUCCESS; } }
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/src/Enums/Approaches.php
src/Enums/Approaches.php
<?php namespace Laravel\Roster\Enums; enum Approaches: string { case ACTION = 'action'; case DDD = 'ddd'; }
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/src/Enums/Ides.php
src/Enums/Ides.php
<?php namespace Laravel\Roster\Enums; enum Ides: string { case PHPSTORM = 'phpstorm'; case CURSOR = 'cursor'; case WINDSURF = 'windsurf'; case VSCODE = 'vscode'; case CLAUDE_CODE = 'claudecode'; case CODEX = 'codex'; case OPENCODE = 'opencode'; }
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/src/Enums/NodePackageManager.php
src/Enums/NodePackageManager.php
<?php namespace Laravel\Roster\Enums; use Laravel\Roster\Scanners\BunPackageLock; use Laravel\Roster\Scanners\NpmPackageLock; use Laravel\Roster\Scanners\PnpmPackageLock; use Laravel\Roster\Scanners\YarnPackageLock; enum NodePackageManager: string { case NPM = 'npm'; case PNPM = 'pnpm'; case YARN = 'yarn'; case BUN = 'bun'; public function scanner(string $path): NpmPackageLock|PnpmPackageLock|YarnPackageLock|BunPackageLock { return match ($this) { self::NPM => new NpmPackageLock($path), self::PNPM => new PnpmPackageLock($path), self::YARN => new YarnPackageLock($path), self::BUN => new BunPackageLock($path), }; } }
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/src/Enums/Packages.php
src/Enums/Packages.php
<?php namespace Laravel\Roster\Enums; enum Packages: string { // Compound case INERTIA = 'inertia'; case WAYFINDER = 'wayfinder'; // BACKEND case BREEZE = 'breeze'; case CASHIER = 'cashier'; case DUSK = 'dusk'; case ENVOY = 'envoy'; case FILAMENT = 'filament'; case FOLIO = 'folio'; case FORTIFY = 'fortify'; case FLUXUI_FREE = 'flux_free'; case FLUXUI_PRO = 'flux_pro'; case HORIZON = 'horizon'; case INERTIA_LARAVEL = 'inertia-laravel'; case LARASTAN = 'larastan'; case LARAVEL = 'laravel'; case LIVEWIRE = 'livewire'; case MCP = 'mcp'; case NIGHTWATCH = 'nightwatch'; case NOVA = 'nova'; case OCTANE = 'octane'; case PASSPORT = 'passport'; case PENNANT = 'pennant'; case PEST = 'pest'; case PHPUNIT = 'phpunit'; case PINT = 'pint'; case PROMPTS = 'prompts'; case PULSE = 'pulse'; case RECTOR = 'rector'; case REVERB = 'reverb'; case SAIL = 'sail'; case SANCTUM = 'sanctum'; case SCOUT = 'scout'; case SOCIALITE = 'socialite'; case STATAMIC = 'statamic'; case TELESCOPE = 'telescope'; case VOLT = 'volt'; case WAYFINDER_LARAVEL = 'wayfinder_laravel'; case ZIGGY = 'ziggy'; // NPM case ALPINEJS = 'alpinejs'; case ECHO = 'laravel-echo'; case ESLINT = 'eslint'; case INERTIA_REACT = 'inertia-react'; case INERTIA_SVELTE = 'inertia-svelte'; case INERTIA_VUE = 'inertia-vue'; case PRETTIER = 'prettier'; case REACT = 'react'; case TAILWINDCSS = 'tailwindcss'; case VUE = 'vue'; case WAYFINDER_VITE = 'wayfinder_vite'; }
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/src/Scanners/BunPackageLock.php
src/Scanners/BunPackageLock.php
<?php namespace Laravel\Roster\Scanners; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; class BunPackageLock extends BasePackageScanner { /** * @return \Illuminate\Support\Collection<int, \Laravel\Roster\Package|\Laravel\Roster\Approach> */ public function scan(): Collection { $mappedItems = collect(); $lockFilePath = $this->path.'bun.lock'; $contents = $this->validateFile($lockFilePath); if ($contents === null) { return $mappedItems; } // Remove trailing commas before decoding /** @var string $contents */ $contents = preg_replace('/,\s*([]}])/m', '$1', $contents); $json = json_decode($contents, true); if (json_last_error() !== JSON_ERROR_NONE || ! is_array($json)) { Log::warning('Failed to decode Package: '.$lockFilePath.'. '.json_last_error_msg()); return $mappedItems; } /** @var array<string, array<string, mixed>> $json */ if (! isset($json['workspaces']['']) || ! isset($json['packages'])) { Log::warning('Malformed bun.lock'); return $mappedItems; } /** @var array<string, mixed> $workspace */ $workspace = $json['workspaces']['']; /** @var array<string, string> $dependencies */ $dependencies = $workspace['dependencies'] ?? []; /** @var array<string, string> $devDependencies */ $devDependencies = $workspace['devDependencies'] ?? []; $this->processDependencies($dependencies, $mappedItems, false); $this->processDependencies($devDependencies, $mappedItems, true); return $mappedItems; } /** * Check if the scanner can handle the given path */ public function canScan(): bool { return file_exists($this->path.'bun.lock'); } }
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/src/Scanners/PnpmPackageLock.php
src/Scanners/PnpmPackageLock.php
<?php namespace Laravel\Roster\Scanners; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; use Symfony\Component\Yaml\Yaml; class PnpmPackageLock extends BasePackageScanner { /** * @return \Illuminate\Support\Collection<int, \Laravel\Roster\Package|\Laravel\Roster\Approach> */ public function scan(): Collection { $mappedItems = collect(); $lockFilePath = $this->path.'pnpm-lock.yaml'; $contents = $this->validateFile($lockFilePath, 'PNPM lock'); if ($contents === null) { return $mappedItems; } try { /** @var array<string, mixed> $parsed */ $parsed = Yaml::parse($contents); } catch (\Exception $e) { Log::error('Failed to parse YAML: '.$e->getMessage()); return $mappedItems; } /** @var array<string, string> $dependencies */ $dependencies = []; /** @var array<string, string> $devDependencies */ $devDependencies = []; /** @var array<string, array<string, mixed>> $importers */ $importers = $parsed['importers'] ?? []; $root = $importers['.'] ?? []; /** @var array<string, array<string, mixed>> $rootDependencies */ $rootDependencies = $root['dependencies'] ?? []; /** @var array<string, array<string, mixed>> $rootDevDependencies */ $rootDevDependencies = $root['devDependencies'] ?? []; foreach ($rootDependencies as $name => $data) { if (isset($data['version'])) { $dependencies[$name] = $data['version']; } } foreach ($rootDevDependencies as $name => $data) { if (isset($data['version'])) { $devDependencies[$name] = $data['version']; } } /** @var array<string, string> $dependencies */ /** @var array<string, string> $devDependencies */ $this->processDependencies($dependencies, $mappedItems, false); $this->processDependencies($devDependencies, $mappedItems, true); return $mappedItems; } /** * Check if the scanner can handle the given path */ public function canScan(): bool { return file_exists($this->path.'pnpm-lock.yaml'); } }
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/src/Scanners/YarnPackageLock.php
src/Scanners/YarnPackageLock.php
<?php namespace Laravel\Roster\Scanners; use Illuminate\Support\Collection; class YarnPackageLock extends BasePackageScanner { /** * @return \Illuminate\Support\Collection<int, \Laravel\Roster\Package|\Laravel\Roster\Approach> */ public function scan(): Collection { $mappedItems = collect([]); $lockFilePath = $this->path.'yarn.lock'; $contents = $this->validateFile($lockFilePath, 'Yarn lock'); if ($contents === null) { return $mappedItems; } $dependencies = []; $lines = explode("\n", $contents); $currentPackage = null; foreach ($lines as $line) { $line = trim($line); // Skip comments and empty lines if ($line === '' || str_starts_with($line, '#')) { continue; } // Package header line (e.g. tailwindcss@^3.4.3:) if (preg_match('/^("?)([^@"]+)(@[^:]+)?:\1$/', $line, $matches)) { $currentPackage = $matches[2]; } // Version line elseif ($currentPackage && preg_match('/^version\s+"?([^"]+)"?$/', $line, $matches)) { $version = $matches[1]; $dependencies[$currentPackage] = $version; $currentPackage = null; // Reset until next package block } } // Yarn lock does not distinguish devDependencies :/ $this->processDependencies($dependencies, $mappedItems, false); return $mappedItems; } /** * Check if the scanner can handle the given path */ public function canScan(): bool { return file_exists($this->path.'yarn.lock'); } }
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/src/Scanners/PackageLock.php
src/Scanners/PackageLock.php
<?php namespace Laravel\Roster\Scanners; use Illuminate\Support\Collection; use Laravel\Roster\Enums\NodePackageManager; class PackageLock { /** * @param string $path - Base path to scan for lock files (package-lock.json, pnpm-lock.yaml, yarn.lock, ...) */ public function __construct(protected string $path) {} /** * @return \Illuminate\Support\Collection<int, \Laravel\Roster\Package|\Laravel\Roster\Approach> */ public function scan(): Collection { foreach (NodePackageManager::cases() as $case) { $scanner = $case->scanner($this->path); if ($scanner->canScan()) { return $scanner->scan(); } } return collect(); } public function detect(): NodePackageManager { foreach (NodePackageManager::cases() as $case) { $scanner = $case->scanner($this->path); if ($scanner->canScan()) { return $case; } } return NodePackageManager::NPM; } }
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/src/Scanners/Composer.php
src/Scanners/Composer.php
<?php namespace Laravel\Roster\Scanners; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; use Laravel\Roster\Approach; use Laravel\Roster\Enums\Approaches; use Laravel\Roster\Enums\Packages; use Laravel\Roster\Package; class Composer { /** * Map of composer package names to enums * * @var array<string, Packages|Approaches|array<int, Packages|Approaches>|null> */ protected array $map = [ 'filament/filament' => Packages::FILAMENT, 'inertiajs/inertia-laravel' => [Packages::INERTIA, Packages::INERTIA_LARAVEL], 'larastan/larastan' => Packages::LARASTAN, 'laravel/breeze' => Packages::BREEZE, 'laravel/cashier' => Packages::CASHIER, 'laravel/dusk' => Packages::DUSK, 'laravel/envoy' => Packages::ENVOY, 'laravel/folio' => Packages::FOLIO, 'laravel/fortify' => Packages::FORTIFY, 'laravel/framework' => Packages::LARAVEL, 'laravel/horizon' => Packages::HORIZON, 'laravel/mcp' => Packages::MCP, 'laravel/nightwatch' => Packages::NIGHTWATCH, 'laravel/nova' => Packages::NOVA, 'laravel/octane' => Packages::OCTANE, 'laravel/passport' => Packages::PASSPORT, 'laravel/pennant' => Packages::PENNANT, 'laravel/pint' => Packages::PINT, 'laravel/prompts' => Packages::PROMPTS, 'laravel/pulse' => Packages::PULSE, 'laravel/reverb' => Packages::REVERB, 'laravel/sail' => Packages::SAIL, 'laravel/sanctum' => Packages::SANCTUM, 'laravel/scout' => Packages::SCOUT, 'laravel/socialite' => Packages::SOCIALITE, 'laravel/telescope' => Packages::TELESCOPE, 'laravel/wayfinder' => [Packages::WAYFINDER, Packages::WAYFINDER_LARAVEL], 'livewire/flux' => Packages::FLUXUI_FREE, 'livewire/flux-pro' => Packages::FLUXUI_PRO, 'livewire/livewire' => Packages::LIVEWIRE, 'livewire/volt' => Packages::VOLT, 'pestphp/pest' => Packages::PEST, 'phpunit/phpunit' => Packages::PHPUNIT, 'rector/rector' => Packages::RECTOR, 'statamic/cms' => Packages::STATAMIC, 'tightenco/ziggy' => Packages::ZIGGY, ]; /** @var array<string, array{constraint: string, isDev: bool}> */ protected array $directPackages = []; /** * @param string $path - composer.lock */ public function __construct(protected string $path) {} /** * @return \Illuminate\Support\Collection<int, \Laravel\Roster\Package|\Laravel\Roster\Approach> */ public function scan(): Collection { $mappedItems = collect([]); if (! file_exists($this->path)) { Log::warning('Failed to scan Composer: '.$this->path); return $mappedItems; } if (! is_readable($this->path)) { Log::warning('File not readable: '.$this->path); return $mappedItems; } $contents = file_get_contents($this->path); if ($contents === false) { Log::warning('Failed to read Composer: '.$this->path); return $mappedItems; } $json = json_decode($contents, true); if (json_last_error() !== JSON_ERROR_NONE || ! is_array($json)) { Log::warning('Failed to decode Composer: '.$this->path.'. '.json_last_error_msg()); return $mappedItems; } if (! array_key_exists('packages', $json)) { Log::warning('Malformed composer.lock'); return $mappedItems; } $this->directPackages = $this->direct(); $packages = $json['packages'] ?? []; $devPackages = $json['packages-dev'] ?? []; $this->processPackages($packages, $mappedItems, false); $this->processPackages($devPackages, $mappedItems, true); return $mappedItems; } /** * Returns direct dependencies as defined in composer.json * * @return array<string, array{constraint: string, isDev: bool}> * */ protected function direct(): array { $packages = []; $filename = realpath(dirname($this->path)).DIRECTORY_SEPARATOR.'composer.json'; if (file_exists($filename) === false || is_readable($filename) === false) { return $packages; } $json = file_get_contents($filename); if ($json === false) { return $packages; } $json = json_decode($json, true); if (json_last_error() !== JSON_ERROR_NONE || ! is_array($json)) { return $packages; } foreach (($json['require'] ?? []) as $name => $constraint) { $packages[$name] = [ 'constraint' => $constraint, 'isDev' => false, ]; } foreach (($json['require-dev'] ?? []) as $name => $constraint) { $packages[$name] = [ 'constraint' => $constraint, 'isDev' => true, ]; } return $packages; } /** * Process packages and add them to the mapped items collection * * @param array<int, array<string, string>> $packages * @param Collection<int, Package|Approach> $mappedItems * @return Collection<int, Package|Approach> */ private function processPackages(array $packages, Collection $mappedItems, bool $isDev): Collection { foreach ($packages as $package) { $packageName = $package['name'] ?? ''; $version = $package['version'] ?? ''; $mappedPackage = $this->map[$packageName] ?? null; $direct = false; $constraint = $version; if (is_null($mappedPackage)) { continue; } if (! is_array($mappedPackage)) { $mappedPackage = [$mappedPackage]; } if (array_key_exists($packageName, $this->directPackages) === true) { $direct = true; $constraint = $this->directPackages[$packageName]['constraint']; } foreach ($mappedPackage as $mapped) { $niceVersion = preg_replace('/[^0-9.]/', '', $version) ?? ''; $mappedItems->push(match (get_class($mapped)) { Packages::class => (new Package($mapped, $packageName, $niceVersion, $isDev))->setDirect($direct)->setConstraint($constraint), Approaches::class => new Approach($mapped), default => throw new \InvalidArgumentException('Unsupported mapping') }); } } return $mappedItems; } }
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/src/Scanners/BasePackageScanner.php
src/Scanners/BasePackageScanner.php
<?php namespace Laravel\Roster\Scanners; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; use Laravel\Roster\Approach; use Laravel\Roster\Enums\Approaches; use Laravel\Roster\Enums\Packages; use Laravel\Roster\Package; abstract class BasePackageScanner { /** * Map of package names to enums * * @var array<string, Packages|Approaches|array<int, Packages|Approaches>> */ protected array $map = [ 'alpinejs' => Packages::ALPINEJS, 'eslint' => Packages::ESLINT, '@inertiajs/react' => [Packages::INERTIA, Packages::INERTIA_REACT], '@inertiajs/svelte' => [Packages::INERTIA, Packages::INERTIA_SVELTE], '@inertiajs/vue3' => [Packages::INERTIA, Packages::INERTIA_VUE], 'laravel-echo' => Packages::ECHO, '@laravel/vite-plugin-wayfinder' => [Packages::WAYFINDER, Packages::WAYFINDER_VITE], 'prettier' => Packages::PRETTIER, 'react' => Packages::REACT, 'tailwindcss' => [Packages::TAILWINDCSS], 'vue' => Packages::VUE, ]; public function __construct(protected string $path) {} /** * @return \Illuminate\Support\Collection<int, \Laravel\Roster\Package|\Laravel\Roster\Approach> */ abstract public function scan(): Collection; /** * Check if the scanner can handle the given path */ abstract public function canScan(): bool; /** * Process dependencies and add them to the mapped items collection * * @param array<string, string> $dependencies * @param Collection<int, Package|Approach> $mappedItems * @param ?callable $versionCb - callback to override version */ protected function processDependencies(array $dependencies, Collection $mappedItems, bool $isDev, ?callable $versionCb = null): void { foreach ($dependencies as $packageName => $version) { $mappedPackage = $this->map[$packageName] ?? null; if (is_null($mappedPackage)) { continue; } if (! is_array($mappedPackage)) { $mappedPackage = [$mappedPackage]; } if (! is_null($versionCb)) { $version = $versionCb($packageName, $version); } foreach ($mappedPackage as $mapped) { $niceVersion = preg_replace('/[^0-9.]/', '', $version) ?? ''; $mappedItems->push(match (get_class($mapped)) { Packages::class => new Package($mapped, $packageName, $niceVersion, $isDev), Approaches::class => new Approach($mapped), default => throw new \InvalidArgumentException('Unsupported mapping') }); } } } /** * Common file validation logic */ protected function validateFile(string $path, string $type = 'Package'): ?string { if (! file_exists($path)) { Log::warning("Failed to scan $type: $path"); return null; } if (! is_readable($path)) { Log::warning("File not readable: $path"); return null; } $contents = file_get_contents($path); if ($contents === false) { Log::warning("Failed to read $type: $path"); return null; } return $contents; } }
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/src/Scanners/DirectoryStructure.php
src/Scanners/DirectoryStructure.php
<?php namespace Laravel\Roster\Scanners; use Illuminate\Support\Collection; use Laravel\Roster\Approach; use Laravel\Roster\Enums\Approaches; class DirectoryStructure { public function __construct(protected string $path) {} /** * @return \Illuminate\Support\Collection<int, \Laravel\Roster\Package|\Laravel\Roster\Approach> */ public function scan(): Collection { $items = collect(); $actions = $this->path.DIRECTORY_SEPARATOR.'/app/'.DIRECTORY_SEPARATOR.'Actions'; if (is_dir($actions)) { $items->push(new Approach(Approaches::ACTION)); } $domains = $this->path.DIRECTORY_SEPARATOR.'/app/'.DIRECTORY_SEPARATOR.'Domains'; if (is_dir($domains)) { $items->push(new Approach(Approaches::DDD)); } return $items; } }
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/src/Scanners/NpmPackageLock.php
src/Scanners/NpmPackageLock.php
<?php namespace Laravel\Roster\Scanners; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; class NpmPackageLock extends BasePackageScanner { /** * @return \Illuminate\Support\Collection<int, \Laravel\Roster\Package|\Laravel\Roster\Approach> */ public function scan(): Collection { $mappedItems = collect(); $lockFilePath = $this->path.'package-lock.json'; $contents = $this->validateFile($lockFilePath); if ($contents === null) { return $mappedItems; } $json = json_decode($contents, true); if (json_last_error() !== JSON_ERROR_NONE || ! is_array($json)) { Log::warning('Failed to decode Package: '.$lockFilePath.'. '.json_last_error_msg()); return $mappedItems; } if (! array_key_exists('packages', $json)) { Log::warning('Malformed package-lock'); return $mappedItems; } $dependencies = $json['packages']['']['dependencies'] ?? []; $devDependencies = $json['packages']['']['devDependencies'] ?? []; $packages = array_filter($json['packages'], fn ($key) => $key !== '', ARRAY_FILTER_USE_KEY); $versionCb = function (string $packageName, string $version) use ($packages): string { $key = "node_modules/{$packageName}"; if (array_key_exists($key, $packages)) { return $packages[$key]['version']; } return $version; }; $this->processDependencies($dependencies, $mappedItems, false, $versionCb); $this->processDependencies($devDependencies, $mappedItems, true, $versionCb); return $mappedItems; } /** * Check if the scanner can handle the given path */ public function canScan(): bool { return file_exists($this->path.'package-lock.json'); } }
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/tests/Pest.php
tests/Pest.php
<?php /* |-------------------------------------------------------------------------- | Test Case |-------------------------------------------------------------------------- | | The closure you provide to your test functions is always bound to a specific PHPUnit test | case class. By default, that class is "PHPUnit\Framework\TestCase". Of course, you may | need to change it using the "uses()" function to bind a different classes or traits. | */ /* |-------------------------------------------------------------------------- | Expectations |-------------------------------------------------------------------------- | | When you're writing tests, you often need to check that values meet certain conditions. The | "expect()" function gives you access to a set of "expectations" methods that you can use | to assert different things. Of course, you may extend the Expectation API at any time. | */ expect()->extend('toBeOne', function () { return $this->toBe(1); });
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/tests/TestCase.php
tests/TestCase.php
<?php namespace Tests; use Laravel\Roster\RosterServiceProvider; use Orchestra\Testbench\TestCase as OrchestraTestCase; abstract class TestCase extends OrchestraTestCase { protected function defineEnvironment($app) {} protected function setUp(): void { parent::setUp(); } protected function tearDown(): void { parent::tearDown(); } protected function getPackageProviders($app) { return [RosterServiceProvider::class]; } }
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/tests/fixtures/fog/installed.php
tests/fixtures/fog/installed.php
<?php return [ [ 'versions' => [ 'laravel/framework' => [ 'pretty_version' => '11.44.2', 'dev_requirement' => false, ], 'pestphp/pest' => [ 'pretty_version' => '3.8.1', 'dev_requirement' => true, ], 'laravel/pint' => [ 'pretty_version' => '1.21.2', 'dev_requirement' => false, ], ], ], ];
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/tests/Unit/CreateApproachesAndPackagesTest.php
tests/Unit/CreateApproachesAndPackagesTest.php
<?php use Laravel\Roster\Approach; it('can create instances of approaches', function () { $approach = new \Laravel\Roster\Approach(\Laravel\Roster\Enums\Approaches::DDD); expect($approach)->toBeInstanceOf(Approach::class); }); it('can create instances of packages', function () { $approach = new \Laravel\Roster\Package(\Laravel\Roster\Enums\Packages::PEST, 'pestphp/pest', '1.0.1'); expect($approach)->toBeInstanceOf(\Laravel\Roster\Package::class); });
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/tests/Unit/RosterTest.php
tests/Unit/RosterTest.php
<?php use Laravel\Roster\Approach; use Laravel\Roster\Enums\Approaches; use Laravel\Roster\Enums\NodePackageManager; use Laravel\Roster\Enums\Packages; use Laravel\Roster\Package; use Laravel\Roster\Roster; it('can add packages and approaches to roster', function () { $package = new Package(Packages::PEST, 'pestphp/pest', '1.0.1'); $approach = new Approach(Approaches::DDD); $roster = new Roster; $roster->add($package); $roster->add($approach); expect($roster)->packages()->toArray()->toBe([$package]); expect($roster)->approaches()->toArray()->toBe([$approach]); }); it('knows if a package is in use', function () { $package = new Package(Packages::PEST, 'pestphp/pest', '1.0.1'); $roster = (new Roster)->add($package); expect($roster->uses(Packages::PEST))->toBeTrue(); expect($roster->uses(Packages::INERTIA))->toBeFalse(); }); it('knows if a specific version of a package is in use', function () { $usedPackage = new Package(Packages::PEST, 'pestphp/pest', '1.0.1'); $roster = (new Roster)->add($usedPackage); expect($roster->uses(Packages::PEST))->toBeTrue(); expect($roster->usesVersion(Packages::INERTIA, '1.0.1'))->toBeFalse(); expect($roster->usesVersion(Packages::PEST, '1.0.1'))->toBeTrue(); expect($roster->usesVersion(Packages::PEST, '1.0.1', '='))->toBeTrue(); expect($roster->usesVersion(Packages::PEST, '1.0.1', '=='))->toBeTrue(); expect($roster->usesVersion(Packages::PEST, '1.0.1', '>='))->toBeTrue(); expect($roster->usesVersion(Packages::PEST, '1.0.1', '<='))->toBeTrue(); expect($roster->usesVersion(Packages::PEST, '1.0.2', '<='))->toBeTrue(); expect($roster->usesVersion(Packages::PEST, '1.0.2', '!='))->toBeTrue(); expect($roster->usesVersion(Packages::PEST, '1.0.2', '<>'))->toBeTrue(); expect($roster->usesVersion(Packages::PEST, '1.0.2', '>='))->toBeFalse(); expect($roster->usesVersion(Packages::PEST, '1.0.0', '<='))->toBeFalse(); }); it('throws an exception with an invalid version when checking version usage', function () { (new Roster)->usesVersion(Packages::PEST, '1.0.x', '##INVALID##'); })->throws(InvalidArgumentException::class); it('throws an exception with an invalid operator when checking version usage', function () { (new Roster)->usesVersion(Packages::PEST, '1.0.0', '##INVALID##'); })->throws(InvalidArgumentException::class); it('knows if an approach is in use', function () { $approach = new Approach(Approaches::DDD); $roster = (new Roster)->add($approach); expect($roster->uses(Approaches::DDD))->toBeTrue(); expect($roster->uses(Approaches::ACTION))->toBeFalse(); }); it('can return dev packages', function () { $devPackage = new Package(Packages::PEST, 'pestphp/pest', '1.0.1', true); $package = new Package(Packages::INERTIA, 'inertiajs/inertia-laravel', '2.0.0'); $roster = (new Roster)->add($devPackage)->add($package); expect($roster->uses(Packages::INERTIA))->toBeTrue(); expect($roster->uses(Packages::PEST))->toBeTrue(); expect($roster->packages()->dev()->toArray())->toBe([$devPackage]); }); it('can return a specific package', function () { $package = new Package(Packages::PEST, 'pestphp/pest', '1.0.1'); $roster = (new Roster)->add($package); expect($roster->package(Packages::PEST))->toBe($package); expect($roster->package(Packages::INERTIA))->toBeNull(); }); it('can return raw package name', function () { $package = new Package(Packages::PEST, 'pestphp/pest', '1.0.1'); expect($package->rawName())->toBe('pestphp/pest'); expect($package->name())->toBe('PEST'); }); describe('node package manager detection', function () { beforeEach(function () { $this->path = __DIR__.'/../fixtures/fog/'; $this->lockFiles = [ 'package-lock.json' => $this->path.'package-lock.json', 'pnpm-lock.yaml' => $this->path.'pnpm-lock.yaml', 'yarn.lock' => $this->path.'yarn.lock', 'bun.lock' => $this->path.'bun.lock', ]; }); afterEach(function () { foreach ($this->lockFiles as $file) { $tempPath = $file.'.bac'; if (file_exists($tempPath)) { rename($tempPath, $file); } } }); it('can detect :manager as node package manager', function (string $requiredFile, NodePackageManager $expected) { foreach ($this->lockFiles as $fileName => $filePath) { if ($fileName !== $requiredFile && file_exists($filePath)) { rename($filePath, $filePath.'.bac'); } } $roster = Roster::scan($this->path); expect($roster->nodePackageManager())->toBe($expected); })->with([ 'npm' => ['package-lock.json', NodePackageManager::NPM], 'pnpm' => ['pnpm-lock.yaml', NodePackageManager::PNPM], 'yarn' => ['yarn.lock', NodePackageManager::YARN], 'bun' => ['bun.lock', NodePackageManager::BUN], ]); it('defaults to npm when no lock files exist', function () { $path = __DIR__.'/../fixtures/phpunit/'; $roster = Roster::scan($path); expect($roster->nodePackageManager())->toBe(NodePackageManager::NPM); }); });
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/tests/Unit/CheckTest.php
tests/Unit/CheckTest.php
<?php use Laravel\Roster\Enums\Packages; use Laravel\Roster\Roster; it('adds found composer packages to roster class', function () { $path = __DIR__.'/../fixtures/fog'; $roster = Roster::scan($path); // Overall - 12 packages from composer (dusk, socialite, folio, volt, fluxui_free, laravel, pest, pint, filament, livewire, flux, phpunit) and 2 from package lock (tailwind, alpine) expect($roster->packages())->toHaveCount(15); // From composer expect($roster->uses(Packages::PEST))->toBeTrue(); expect($roster->uses(Packages::FOLIO))->toBeTrue(); expect($roster->uses(Packages::VOLT))->toBeTrue(); expect($roster->uses(Packages::FLUXUI_FREE))->toBeTrue(); expect($roster->uses(Packages::PINT))->toBeTrue(); expect($roster->uses(Packages::LARAVEL))->toBeTrue(); expect($roster->uses(Packages::INERTIA))->toBeFalse(); expect($roster->usesVersion(Packages::PEST, '3.8.1'))->toBeTrue(); expect($roster->usesVersion(Packages::PINT, '1.21.2'))->toBeTrue(); // From packagelock expect($roster->usesVersion(Packages::TAILWINDCSS, '3.4.16'))->toBeTrue(); expect($roster->usesVersion(Packages::ALPINEJS, '3.14.7'))->toBeTrue(); });
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/tests/Unit/ScanCommandTest.php
tests/Unit/ScanCommandTest.php
<?php use Illuminate\Support\Facades\Artisan; use Tests\TestCase; uses(TestCase::class); it('outputs JSON for directory with packages', function () { $path = __DIR__.'/../fixtures/fog'; Artisan::call('roster:scan', ['directory' => $path]); $output = Artisan::output(); $decoded = json_decode($output, true); expect($decoded)->toBeArray(); expect($decoded)->toHaveKey('packages'); expect($decoded['packages'])->toBeArray(); expect(count($decoded['packages']))->toBeGreaterThan(0); }); it('outputs empty JSON for empty directory', function () { $emptyDir = sys_get_temp_dir().'/roster_test_empty_'.uniqid(); mkdir($emptyDir); Artisan::call('roster:scan', ['directory' => $emptyDir]); $output = Artisan::output(); $decoded = json_decode($output, true); expect($decoded)->toBeArray(); expect($decoded)->toHaveKey('packages'); expect($decoded['packages'])->toBeEmpty(); rmdir($emptyDir); }); it('returns failure for non-existent directory', function () { $nonExistentDir = '/non/existent/directory'; $exitCode = Artisan::call('roster:scan', ['directory' => $nonExistentDir]); expect($exitCode)->toBe(1); }); it('returns failure for unreadable directory', function () { $invalidArg = 123; $exitCode = Artisan::call('roster:scan', ['directory' => $invalidArg]); expect($exitCode)->toBe(1); });
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/tests/Unit/Scanners/PackageLockTest.php
tests/Unit/Scanners/PackageLockTest.php
<?php use Laravel\Roster\Enums\Packages; use Laravel\Roster\Package; use Laravel\Roster\Scanners\PackageLock; $packageLockPath = __DIR__.'/../../fixtures/fog/package-lock.json'; $pnpmLockPath = __DIR__.'/../../fixtures/fog/pnpm-lock.yaml'; $yarnLockPath = __DIR__.'/../../fixtures/fog/yarn.lock'; $tempPackagePath = $packageLockPath.'.bac'; $tempPnpmPath = $pnpmLockPath.'.bac'; $tempYarnPath = $yarnLockPath.'.bac'; afterEach(function () use ($packageLockPath, $pnpmLockPath, $yarnLockPath, $tempPackagePath, $tempPnpmPath, $tempYarnPath) { // Restore original files after each test if (file_exists($tempPackagePath)) { rename($tempPackagePath, $packageLockPath); } if (file_exists($tempPnpmPath)) { rename($tempPnpmPath, $pnpmLockPath); } if (file_exists($tempYarnPath)) { rename($tempYarnPath, $yarnLockPath); } }); it('scans valid package-lock.json', function () { $path = __DIR__.'/../../fixtures/fog/'; $packageLock = new PackageLock($path); $items = $packageLock->scan(); $tailwind = $items->first(fn (Package $package) => $package->package() === Packages::TAILWINDCSS); $inertiaReact = $items->first(fn (Package $package) => $package->package() === Packages::INERTIA_REACT); expect($tailwind->version())->toEqual('3.4.16'); // Installed version, not dependency constraint expect($inertiaReact)->toBeNull(); }); it('scans valid pnpm-lock.yaml', function () use ($packageLockPath, $tempPackagePath) { // Remove package-lock.json temporarily to test pnpm priority if (file_exists($packageLockPath)) { rename($packageLockPath, $tempPackagePath); } $path = __DIR__.'/../../fixtures/fog/'; $packageLock = new PackageLock($path); $items = $packageLock->scan(); $tailwind = $items->first(fn (Package $package) => $package->package() === Packages::TAILWINDCSS); $alpine = $items->first(fn (Package $package) => $package->package() === Packages::ALPINEJS); expect($tailwind->version())->toEqual('3.4.3'); expect($alpine->version())->toEqual('3.4.2'); // Restore package-lock.json if (file_exists($tempPackagePath)) { rename($tempPackagePath, $packageLockPath); } }); it('scans valid yarn.lock', function () use ($packageLockPath, $pnpmLockPath, $tempPackagePath, $tempPnpmPath) { // Remove package-lock.json and pnpm-lock.yaml temporarily to test yarn priority if (file_exists($packageLockPath)) { rename($packageLockPath, $tempPackagePath); } if (file_exists($pnpmLockPath)) { rename($pnpmLockPath, $tempPnpmPath); } $path = __DIR__.'/../../fixtures/fog/'; $packageLock = new PackageLock($path); $items = $packageLock->scan(); /** @var Package $tailwind */ $tailwind = $items->first( fn ($item) => $item instanceof Package && $item->package() === Packages::TAILWINDCSS ); /** @var Package $alpine */ $alpine = $items->first( fn ($item) => $item instanceof Package && $item->package() === Packages::ALPINEJS ); expect($tailwind->version())->toEqual('3.4.16') ->and($alpine->version())->toEqual('3.4.4'); // Restore files if (file_exists($tempPackagePath)) { rename($tempPackagePath, $packageLockPath); } if (file_exists($tempPnpmPath)) { rename($tempPnpmPath, $pnpmLockPath); } }); it('handles missing lock files gracefully', function () { $path = __DIR__.'/../../fixtures/empty/'; // Create empty directory if it doesn't exist if (! is_dir($path)) { mkdir($path, 0755, true); } $packageLock = new PackageLock($path); $items = $packageLock->scan(); expect($items)->toBeEmpty(); }); it('scans valid bun.lock', function () use ($packageLockPath, $pnpmLockPath, $yarnLockPath, $tempPackagePath, $tempPnpmPath, $tempYarnPath) { // Remove other lock files temporarily to test bun priority if (file_exists($packageLockPath)) { rename($packageLockPath, $tempPackagePath); } if (file_exists($pnpmLockPath)) { rename($pnpmLockPath, $tempPnpmPath); } if (file_exists($yarnLockPath)) { rename($yarnLockPath, $tempYarnPath); } $path = __DIR__.'/../../fixtures/fog/'; $packageLock = new PackageLock($path); $items = $packageLock->scan(); /** @var Package $tailwind */ $tailwind = $items->first( fn ($item) => $item instanceof Package && $item->package() === Packages::TAILWINDCSS ); /** @var Package $alpine */ $alpine = $items->first( fn ($item) => $item instanceof Package && $item->package() === Packages::ALPINEJS ); expect($tailwind->version())->toEqual('3.4.3') ->and($alpine->version())->toEqual('3.4.2') ->and($alpine->isDev())->toBeTrue() ->and($tailwind->isDev())->toBeFalse(); // Restore files if (file_exists($tempPackagePath)) { rename($tempPackagePath, $packageLockPath); } if (file_exists($tempPnpmPath)) { rename($tempPnpmPath, $pnpmLockPath); } if (file_exists($tempYarnPath)) { rename($tempYarnPath, $yarnLockPath); } });
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
laravel/roster
https://github.com/laravel/roster/blob/b1bcac84218466f9d258315fb89f36261e79d385/tests/Unit/Scanners/ComposerTest.php
tests/Unit/Scanners/ComposerTest.php
<?php use Laravel\Roster\Enums\Packages; use Laravel\Roster\Scanners\Composer; it('can parse installed packages', function () { $path = __DIR__.'/../../fixtures/fog/composer.lock'; $uses = (new Composer($path))->scan(); $laravel = $uses->first(fn ($item) => $item->package() === Packages::LARAVEL); expect($laravel->version())->toEqual('11.44.2'); expect($laravel->isDev())->toBeFalse(); expect($laravel->direct())->toBeTrue(); expect($laravel->constraint())->toEqual('^11.0'); $pest = $uses->first(fn ($item) => $item->package() === Packages::PEST); expect($pest->version())->toEqual('3.8.1'); expect($pest->isDev())->toBeTrue(); $pint = $uses->first(fn ($item) => $item->package() === Packages::PINT); expect($pint->version())->toEqual('1.21.2'); expect($pint->isDev())->toBeFalse(); $inertia = $uses->first(fn ($item) => $item->package() === Packages::INERTIA); expect($inertia)->toBeNull(); }); it('adds 2 entries for inertia', function () { $composerLockContent = '{ "packages": [ { "name": "inertiajs/inertia-laravel", "version": "v123.456.789" } ], "packages-dev": [] }'; $tempFile = tempnam(sys_get_temp_dir(), 'composer_lock_test'); file_put_contents($tempFile, $composerLockContent); $uses = (new Composer($tempFile))->scan(); unlink($tempFile); $laravel = $uses->first(fn ($item) => $item->package() === Packages::LARAVEL); expect($laravel)->toBeNull(); // INERTIA is the general package - is it using inertia at all? $inertia = $uses->first(fn ($item) => $item->package() === Packages::INERTIA); expect($inertia->version())->toEqual('123.456.789'); expect($inertia->isDev())->toBeFalse(); // The specific package of Inertia $inertia = $uses->first(fn ($item) => $item->package() === Packages::INERTIA_LARAVEL); expect($inertia->version())->toEqual('123.456.789'); expect($inertia->isDev())->toBeFalse(); }); it('detects PHPUnit from fixture', function () { $path = __DIR__.'/../../fixtures/phpunit/composer.lock'; $uses = (new Composer($path))->scan(); $phpunit = $uses->first(fn ($item) => $item->package() === Packages::PHPUNIT); expect($phpunit)->not()->toBeNull(); expect($phpunit->version())->toEqual('11.4.3'); expect($phpunit->isDev())->toBeTrue(); });
php
MIT
b1bcac84218466f9d258315fb89f36261e79d385
2026-01-05T04:48:34.931826Z
false
danmed/TasmoBackupV1
https://github.com/danmed/TasmoBackupV1/blob/ff65d7aeade785f40b50f91351f7786592ea5d2d/export.php
export.php
<?PHP require_once(__DIR__.'/lib/functions.inc.php'); global $db_handle; if ($_POST["export"]!="") { header('Content-Type: text/csv'); header('Content-Disposition: attachment;filename=tasmobackup_devices.csv'); //SQL Query for Data $sql = "SELECT * FROM devices;"; //Prepare Query, Bind Parameters, Excute Query $STH = $db_handle->prepare($sql); $STH->execute(); //Export to .CSV $fp = fopen('php://output', 'w'); // first set $first_row = $STH->fetch(PDO::FETCH_ASSOC); $headers = array_keys($first_row); fputcsv($fp, $headers); // put the headers fputcsv($fp, array_values($first_row)); // put the first row while ($row = $STH->fetch(PDO::FETCH_NUM)) { fputcsv($fp, $row); // push the rest } fclose($fp); } //header("Location: settings.php"); ?>
php
MIT
ff65d7aeade785f40b50f91351f7786592ea5d2d
2026-01-05T04:48:49.060847Z
false
danmed/TasmoBackupV1
https://github.com/danmed/TasmoBackupV1/blob/ff65d7aeade785f40b50f91351f7786592ea5d2d/listbackups.php
listbackups.php
<?php require_once(__DIR__.'/lib/functions.inc.php'); global $db_handle; global $settings; if (isset($_POST["name"])) { $name = $_POST["name"]; } if (isset($_POST["id"])) { $id = intval($_POST["id"]); } if (isset($_POST["task"])) { switch(strtolower($_POST["task"])) { case 'delbackup': dbBackupDel(intval($_POST["backupid"])); dbDeviceBackups($id); break; case 'restorebackup': $device=dbDeviceId($id); $backup=dbBackupId(intval($_POST["backupid"])); restoreTasmotaBackup($device['ip'],'admin',$device['password'],$backup['filename']); break; } } TBHeader('List Backups',true,' $(document).ready(function() { $(\'#status\').DataTable({ "order": [[0, "desc" ]], "pageLength": '. (isset($settings['amount'])?$settings['amount']:25) .', "columnDefs": [ { "type": "version", "targets": [2] } ], "statesave": true, "autoWidth": false } ); } ); ',true); ?> <body> <div class="container-fluid"> <center><h4><a href="index.php">TasmoBackup</a> - Listing for <?php echo $name; ?></h4></center> <table class="table table-striped table-bordered" id="status"> <thead> <tr><th><b>DATE</b></th><th><center><b>NAME</b></center></th><th><center><b>VERSION</b></center></th><th><center><b>FILE</b></center></th><th><center><b>DELETE</b><center></th><th><center><b>RESTORE</b></center></th></tr> </thead> <tbody> <?php $device = dbDeviceId($id); $type=0; if(isset($device['type'])) $type=intval($device['type']); $backups = dbBackupList($id); foreach ($backups as $db_field) { $backupid = $db_field['id']; $name = $db_field['name']; $version = $db_field['version']; $date = $db_field['date']; $filename = $db_field['filename']; if(($pos=strpos($version,'('))>0) { $ver=substr($version,0,$pos); $tag=substr($version,$pos); $version=$ver.' <small>'.$tag.'</small>'; } ?> <tr valign='middle'> <td><?php echo $date; ?></td> <td><center><?php echo $name; ?></center></td> <td><center><?php echo $version; ?></center></td> <td><center> <form action='index.php' method='POST'> <input type='hidden' name='task' value='download'> <input type='hidden' name='backupid' value='<?php echo $backupid; ?>'> <input type='hidden' name='id' value='<?php echo $id; ?>'> <button type='submit' class='btn btn-sm btn-success'>Download</button> </form> </center></td> <td><center> <form action='listbackups.php' method='POST'> <input type='hidden' name='task' value='delbackup'> <input type='hidden' name='backupid' value='<?php echo $backupid; ?>'> <input type='hidden' name='id' value='<?php echo $id; ?>'> <input type='hidden' name='name' value='<?php echo $name; ?>'> <button type='submit' onclick='return window.confirm("Are you sure you want to delete <?php echo $filename; ?>");' class='btn-sm btn-danger'>Delete</button> </form> </center></td> <?php if(intval($type)===0) { ?> <td><center> <form action='listbackups.php' method='POST'> <input type='hidden' name='task' value='restorebackup'> <input type='hidden' name='backupid' value='<?php echo $backupid; ?>'> <input type='hidden' name='id' value='<?php echo $id; ?>'> <input type='hidden' name='name' value='<?php echo $name; ?>'> <button type='submit' onclick='return window.confirm("Are you sure you want to restore <?php echo $filename; ?> to this device");' class='btn btn-sm btn-danger'>Restore</button> </form> </center></td> <?php } else { echo '<td>&nbsp;</td>'; } echo "\r\n</tr>\r\n"; } ?> </tbody> </table> </div> <?php TBFooter(); ?> </body> </html>
php
MIT
ff65d7aeade785f40b50f91351f7786592ea5d2d
2026-01-05T04:48:49.060847Z
false
danmed/TasmoBackupV1
https://github.com/danmed/TasmoBackupV1/blob/ff65d7aeade785f40b50f91351f7786592ea5d2d/backupall.php
backupall.php
<?PHP require_once(__DIR__.'/lib/functions.inc.php'); $errorcount=backupAll(isset($_REQUEST['docker'])); TBHeader(false,false,false,false); ?> <body> <div class="container-fluid"> <?php if(is_array($errorcount)) { if($errorcount[0]==0 && $errorcount[1]==0) { $output = "All backups are uptodate"; } if($errorcount[0]==0 && $errorcount[1]>0) { $output = "All ".$errorcount[1]." backups completed successfully!"; } if($errorcount[0]>0 && $errorcount[1]>0) { $output = $errorcount[0]." backups failed out of ".$errorcount[1]." backups attempted."; } } else { if ($errorcount < 1) { $output = "All backups completed successfully!"; } else { $output = "<font color='red'><b>Not all backups completed successfully!</b></font>"; } } ?> </div> <?php TBFooter(); ?> </body> </html>
php
MIT
ff65d7aeade785f40b50f91351f7786592ea5d2d
2026-01-05T04:48:49.060847Z
false
danmed/TasmoBackupV1
https://github.com/danmed/TasmoBackupV1/blob/ff65d7aeade785f40b50f91351f7786592ea5d2d/scan.php
scan.php
<?php require_once(__DIR__.'/lib/functions.inc.php'); require_once(__DIR__.'/lib/mqtt.inc.php'); global $settings; TBHeader('Scan',true,' $(document).ready(function() { $(\'#status\').DataTable({ "order": [[1, "asc" ]], "pageLength": '. (isset($settings['amount'])?$settings['amount']:100) .', "statesave": true, "autoWidth": false } ); } ); ',true,((isset($settings['autoadd_scan']) && $settings['autoadd_scan']=='Y')?1:false)); ?> <body> <script language="Javascript"> function toggle(source) { checkboxes = document.getElementsByName('ip[]'); for(var i=0, n=checkboxes.length;i<n;i++) { checkboxes[i].checked = source.checked; } } </script> <div class="container-fluid"> <center><h4><a href="index.php">TasmoBackup</a> - Scan Results</h4></center> <form action="index.php" method="POST"> <input type="hidden" name="task" value="discoverall"> <?php if(isset($_POST['user'])) { echo '<input type="hidden" name="user" value="'.$_POST['user'].'">'; } ?> <?php if(isset($_POST['password'])) { echo '<input type="hidden" name="password" value="'.$_POST['password'].'">'; } ?> <table class="table table-striped table-bordered" id="status"> <thead> <tr><th><b>ADD</b></th><th><b>NAME</b></th><th><b>IP</b></th></tr> </thead> <tbody> <?php $password=''; $user='admin'; if(isset($settings['tasmota_username'])) $user=$settings['tasmota_username']; if (isset($_POST['user'])) { $user=$_POST['user']; } if (isset($_POST['password'])) { $password=$_POST['password']; } if (isset($_POST['mqtt_topic'])) { $mqtt_topic=$_POST['mqtt_topic']; } if ($_POST["task"]=="scan") { set_time_limit(0); print(str_repeat(" ", 300) . "\n"); $range = $_POST['range']; $range = explode('.', $range); foreach ($range as $index=>$octet) { $range[$index] = array_map('intval', explode('-', $octet)); } $iprange=array(); // 4 for loops to generate the ip address 4 octets for ($octet1=$range[0][0]; $octet1<=(isset($range[0][1])? $range[0][1]:$range[0][0]); $octet1++) { for ($octet2=$range[1][0]; $octet2<=(isset($range[1][1])? $range[1][1]:$range[1][0]); $octet2++) { for ($octet3=$range[2][0]; $octet3<=(isset($range[2][1])? $range[2][1]:$range[2][0]); $octet3++) { for ($octet4=$range[3][0]; $octet4<=(isset($range[3][1])? $range[3][1]:$range[3][0]); $octet4++) { // assemble the IP address array_push($iprange,$octet1.".".$octet2.".".$octet3.".".$octet4); } } } } // initialise the URL if ($ipresult=getTasmotaScanRange($iprange, $user, $password)) { for($i=0;$i<count($ipresult);$i++) { list($ip,$type)=$ipresult[$i]; if ($status=getTasmotaStatus($ip, $user, $password, $type)) { if ($type===0) { // Tasmota if ($status['Status']['Topic']) $name=$status['Status']['Topic']; if(!isset($settings['use_topic_as_name']) || $settings['use_topic_as_name']=='N') { if ($status['Status']['DeviceName'] && strlen(preg_replace('/\s+/', '',$status['Status']['DeviceName']))>0) $name=$status['Status']['DeviceName']; else if ($status['Status']['FriendlyName'][0]) $name=$status['Status']['FriendlyName'][0]; } } else if ($type===1) { // WLED if(isset($status['info']['name'])) $name=trim($status['info']['name']); } echo "<tr valign='middle'><td><center><input type='checkbox' name='ip[]' value='" . $ip . "'></center></td>". "<td>" . $name . "</td>". "<td><center><a href='http://" . $ip . "'>" . $ip . "</a></center></td></tr>"; } } } } if ($_POST["task"]=="mqtt") { if(isset($settings['mqtt_host']) && isset($settings['mqtt_port']) && strlen($settings['mqtt_host'])>1) { $mqtt=setupMQTT($settings['mqtt_host'], $settings['mqtt_port'], $settings['mqtt_user'], $settings['mqtt_password']); if(!isset($mqtt_topic)) $mqtt_topic=$settings['mqtt_topic']; $results=getTasmotaMQTTScan($mqtt,$mqtt_topic,$user,$password,false); if(count($results)>0) { foreach($results as $found) { $ip=$found['ip']; $name='Unknown'; if(isset($found['name'])) $name=$found['name']; echo "<tr valign='middle'><td><center><input type='checkbox' name='ip[]' value='" . $ip . "'></center></td>". "<td>" . $name . "</td>". "<td><center><a href='http://" . $ip . "'>" . $ip . "</a></center></td></tr>"; } } } } ?> </tbody> <tr><td colspan="3">&nbsp;</td></tr> <tr><td><center><input type='checkbox' name="select-all" id="select-all" onClick="toggle(this)"></center></td><td>Select All</td><td>&nbsp;</td></tr> <tr><td colspan="3"><center><button type=submit class='btn btn-sm btn-success'>Add Devices</button></center></td></tr> </table> </form> </div> <?php TBFooter(); ?> </body> </html>
php
MIT
ff65d7aeade785f40b50f91351f7786592ea5d2d
2026-01-05T04:48:49.060847Z
false
danmed/TasmoBackupV1
https://github.com/danmed/TasmoBackupV1/blob/ff65d7aeade785f40b50f91351f7786592ea5d2d/upgrade.php
upgrade.php
<?php global $settings; global $db_upgrade; $db_upgrade = true; require_once(__DIR__.'/lib/functions.inc.php'); TBHeader('Upgrade',true,false,true,10); ?> <body> <div class="container-fluid"> Upgrade Complete </div> <?php TBFooter(); ?> </body> </html>
php
MIT
ff65d7aeade785f40b50f91351f7786592ea5d2d
2026-01-05T04:48:49.060847Z
false
danmed/TasmoBackupV1
https://github.com/danmed/TasmoBackupV1/blob/ff65d7aeade785f40b50f91351f7786592ea5d2d/edit.php
edit.php
<?php require_once(__DIR__.'/lib/functions.inc.php'); if (isset($_POST['ip'])) { $ip = $_POST['ip']; } TBHeader('Edit Device',true,' $(document).ready(function() { $(\'#status\').DataTable({ "order": [[0, "asc" ]], "pageLength": '. (isset($settings['amount'])?$settings['amount']:100) .', "statesave": true, "autoWidth": false } ); } ); ',true); ?> <body> <div class="container-fluid"> <center><h4><a href="index.php">TasmoBackup</a> - Edit</h4></center> <table class="table table-striped table-bordered" id="status"> <thead> <tr><th><b>NAME</th><th>IP</th><th>AUTH</th><th>SUBMIT</th></tr> </thead> <tbody> <?php $relcount = 1; $devices = dbDeviceIp($ip); foreach ($devices as $db_field) { $id = $relcount; $name = $db_field['name']; $ip = $db_field['ip']; $password = $db_field['password']; ?> <tr valign='middle'> <form method='POST' action='index.php'> <input type='hidden' name='task' value='edit'> <input type='hidden' name='oldip' value='<?php echo $ip; ?>'> <td><center><input type='text' name='name' value='<?php echo $name; ?>'></center></td> <td><center><input type='text' name='ip' value='<?php echo $ip; ?>'></center></td> <td><center><input type='password' name='password' value='<?php echo $password; ?>'></center></td> <td><center><button type='submit' class='btn btn-sm btn-success'>Submit</button></center></td> </form> </tr> <?php $relcount ++; } ?> </tbody> </table> </div> <?php TBFooter();
php
MIT
ff65d7aeade785f40b50f91351f7786592ea5d2d
2026-01-05T04:48:49.060847Z
false
danmed/TasmoBackupV1
https://github.com/danmed/TasmoBackupV1/blob/ff65d7aeade785f40b50f91351f7786592ea5d2d/index.php
index.php
<?php require_once(__DIR__.'/lib/functions.inc.php'); global $db_handle; global $settings; $task=''; $password=''; $user='admin'; if(isset($settings['tasmota_username'])) $user=$settings['tasmota_username']; if (isset($_POST["task"])) { $task = $_POST["task"]; } if (isset($_POST["user"])) { $user = $_POST["user"]; } if (isset($_POST["password"])) { $password = $_POST["password"]; } if (isset($_POST["ip"])) { $device = $ip = $_POST["ip"]; } if (isset($_POST["name"])) { $name = $_POST["name"]; } switch(strtolower($task)) { case 'discover': $show_modal = true; $output = '<center>'.addTasmotaDevice($ip, $user, $password).'<br></center>'; break; case 'discoverall': $show_modal = true; $output = '<center>'; if (!is_array($ip)) { $output .= "You didn't select any devices.<br>"; } else { foreach($ip as $i) { $output .= addTasmotaDevice($i, $user, $password).'<br>'; } } $output .= '</center>'; break; case 'edit': if (isset($_POST['oldip'])) { $old_ip = $_POST['oldip']; } if (isset($_POST['oldname'])) { $old_name = $_POST['oldname']; } if (isset($old_ip) && isset($ip)) { if (dbDeviceRename($old_ip, $name, $ip, $password)) { $show_modal = true; $output = "<center><b>" . $name . " updated up successfully</b><br></center>"; } else { $show_modal = true; echo "<center><b>Error updating record for ".$old_ip." ".$name." <br>"; } } break; case 'download': $device=dbDeviceId(intval($_POST["id"])); $backup=dbBackupId(intval($_POST["backupid"])); downloadTasmotaBackup($backup); break; case 'singlebackup': $show_modal = true; $output = "<center><b>Device not found: ".$ip."</b></center>"; $devices = dbDeviceIp($ip); if ($devices!==false) { foreach ($devices as $db_field) { if (backupSingle($db_field['id'], $db_field['name'], $db_field['ip'], 'admin', $db_field['password'], $db_field['type'])) { $show_modal = true; $output = "<center><b>Backup failed</b></center>"; } else { $show_model = true; $output = "Backup completed successfully!"; } } } break; case 'backupall': $errorcount = backupAll(); $show_modal = true; if(is_array($errorcount)) { if($errorcount[0]==0 && $errorcount[1]==0) { $output = "All backups are uptodate"; } if($errorcount[0]==0 && $errorcount[1]>0) { $output = "All ".$errorcount[1]." backups completed successfully!"; } if($errorcount[0]>0 && $errorcount[1]>0) { $output = $errorcount[0]." backups failed out of ".$errorcount[1]." backups attempted."; } } else { if ($errorcount < 1) { $output = "All backups completed successfully!"; } else { $output = "<font color='red'><b>Not all backups completed successfully!</b></font>"; } } break; case 'delete': $show_modal = true; try { if (dbDeviceDel($ip)) { $output = $name . " deleted successfully from the database."; } else { $output = "Error deleting " . $ip; } } catch (PDOException $e) { $output = "Error deleting " . $ip . " : " . $e->getMessage(); } break; case 'noofbackups': $findname = preg_replace('/\s+/', '_', $name); $findname = preg_replace('/[^A-Za-z0-9\-]/', '', $findname); $directory = $settings['backup_folder'] . $findname; $scanned_directory = array_diff(scandir($directory), array('..','.')); $out = array(); foreach ($scanned_directory as $value) { $link = strtolower(implode("-", explode(" ", $value))); $out[] = '<a href="' . $settings['backup_folder'] . $findname . '/' . $link . '">' . $link . '</a>'; } $output = implode("<br>", $out); $show_modal = true; break; default: break; } TBHeader(false,true,' $(document).ready(function() { $(\'#status\').DataTable({ "order": ['. (isset($settings['sort'])?(($settings['sort']<2 || (isset($settings['hide_mac_column']) && $settings['hide_mac_column']=='Y'))?$settings['sort']:$settings['sort']+1):0) .', "asc" ], "pageLength": '. (isset($settings['amount'])?$settings['amount']:100) .', "columnDefs": [ { "type": "ip-address", "targets": [1] }, { "type": "version", "targets": ['. ((isset($settings['hide_mac_column']) && $settings['hide_mac_column']=='Y')?'3':'4') .'] } ], "statesave": true, "autoWidth": false } ); } ); ',true); ?> <body style="scrollbar-gutter: stable;overflow-y:scroll;"> <div class="container-fluid"> <center><h4>TasmoBackup <a href="settings.php"><?php if(isset($settings['theme']) && $settings['theme']=='dark') { // Enforce Dark mode echo '<img src="images/settings-dark.png">'; } else if(isset($settings['theme']) && $settings['theme']=='light') { // Enforce Light mode echo '<img src="images/settings.png">'; } else { // auto mode echo '<picture><source srcset="images/settings-dark.png" media="(prefers-color-scheme: dark">'; echo '<source srcset="images/settings.png" media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)">'; echo '<img src="images/settings.png"></picture>'; } ?></a></h4></center> <table class="table table-striped table-bordered" id="status"> <thead> <tr><th><b>NAME</th><th><center>IP</center></th><?php if(isset($settings['hide_mac_column']) && $settings['hide_mac_column']=='Y') { echo ''; } else { echo '<th><center>MAC</center></th>'; } ?><th><center>AUTH</center></th><th><center><b>VERSION</b></center></th><th><center>LAST BACKUP</center></th><th><center><b>FILES</b></center></th><th><center><b>BACKUP</b></center></th><th><center>EDIT</center></th><th><center><b>DELETE</b></center></th></tr> </thead> <tbody> <?php $github_tasmota_release_data = getGithubTasmotaReleaseData(); $list_model=''; $now=time(); $lastbackup_green=0; $lastbackup_red=0; $lastbackup_yellow=0; if(isset($settings['backup_minhours']) && $settings['backup_minhours']>0) { $lastbackup_green=$now-(intval($settings['backup_minhours'])*3600*2.2); $lastbackup_red=$now-(intval($settings['backup_minhours'])*3600*8); } $devices = dbDevicesSort(); foreach ($devices as $db_field) { $id = $db_field['id']; $name = $db_field['name']; $ip = $db_field['ip']; if(isset($db_field['mac'])) { $mac = $db_field['mac']; $mac_display = $mac; } else { $mac = ''; $mac_display = '&nbsp;'; } $logo='images/tasmota.png'; $type='Tasmota'; if(isset($db_field['type']) && intval($db_field['type'])===1) { $logo='images/wled.png'; $type='WLED'; } $version = $db_field['version']; $lastbackup = $db_field['lastbackup']; $numberofbackups = $db_field['noofbackups']; $password = $db_field['password']; $color=''; if($lastbackup_green>0 && isset($lastbackup) && strlen($lastbackup)>10) { $ts=strtotime($lastbackup); if($ts<$lastbackup_red && $ts>0) $color='bg-danger text-white'; if($ts>$lastbackup_red) $color='bg-warning text-dark'; if($ts>$lastbackup_green) $color=''; // $color='bg-success'; } $mac_display='<td><center>'.$mac_display.'</center></td>'; if(isset($settings['hide_mac_column']) && $settings['hide_mac_column']=='Y') $mac_display=''; //echo "<tr valign='middle'><td onclick=\"deviceModal('#myModaldevice".$id."');\"><img src=\"" . $logo ."\" width=\"32\" height=\"32\" style=\"align:left\">&nbsp;" . $name . "</td><td><center><a href='http://" . $ip . "' target='_blank'>" . $ip . "</a>&nbsp&nbsp<img src='images/cli.png' alt='Open inline console' style='cursor: pointer;width:16px;margin-right:8px;' class='openConsole' data-ip='".$ip."' data-row='".$id."'><a href='http://".$ip."/cs' target='_blank'><img src='images/newtab.png' style='width:16px;' alt='Open console in new tab'></a></td>" . $mac_display . "<td><center>"; echo "<tr valign='middle'><td onclick=\"deviceModal('#myModaldevice".$id."');\"><img src=\"" . $logo ."\" width=\"32\" height=\"32\" style=\"align:left\">&nbsp;" . $name . "</td><td><center><a href='http://" . $ip . "' target='_blank'>" . $ip . "</a>&nbsp&nbsp<a href='http://".$ip."/cs' target='_blank'><img src='images/newtab.png' style='width:16px;' alt='Open console in new tab'></a></td>" . $mac_display . "<td><center>"; if(isset($settings['theme']) && $settings['theme']=='dark') { // Enforce Dark mode echo "<img src='" . (strlen($password) > 0 ? 'images/lock-dark.png' : 'images/lock-open-variant-dark.png') . "'>"; } else if(isset($settings['theme']) && $settings['theme']=='light') { // Enforce Light mode echo "<img src='" . (strlen($password) > 0 ? 'images/lock.png' : 'images/lock-open-variant.png') . "'>"; } else { // auto mode if(strlen($password) >0) { echo '<picture><source srcset="images/lock-dark.png" media="(prefers-color-scheme: dark">'; echo '<source srcset="images/lock.png" media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)">'; echo '<img src="images/lock.png"></picture>'; } else { echo '<picture><source srcset="images/lock-open-variant-dark.png" media="(prefers-color-scheme: dark">'; echo '<source srcset="images/lock-open-variant.png" media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)">'; echo '<img src="images/lock-open-variant.png"></picture>'; } } $ver=$version; $tag=''; $release_html = ''; if(($pos=strpos($version,'('))>0) { $ver=substr($version,0,$pos); $tag=substr($version,$pos); $version=$ver.' <small>'.$tag.'</small>'; if ( in_array($tag,array('(tasmota)','(lite)','(sensors)','(display)','(ir)','(knx)','(zbbridge)','(webcam)','(bluetooth)','(core2)')) ) { $github_tag_name = 'v' . $ver; foreach ( $github_tasmota_release_data as $release => $values ) { $url = $values['html_url']; if ( $values['tag_name'] == $github_tag_name ) { break; } } } else { // default to the Tasmota documentation if a custom "version" is in use $url = "https://tasmota.github.io/docs/"; } if(isset($url) && strlen($url)>5) $version='<a href="'.$url.'">'.$version.'</a>'; } $upgrade = '&nbsp;&nbsp;<a href="http://'.$ip.'/u1" target="_blank"><img src="images/upgrade.png" style="width:16px;" alt="Open upgrade in new tab"></a>'; echo "</center></td><td><center>" . $version . $upgrade . "</center></td><td class='$color'><center>" . $lastbackup . "</center></td>"; echo "<td data-sort='" . $numberofbackups . "'><center><form method='POST' action='listbackups.php'><input type='hidden' value='" . $name . "' name='name'><input type='hidden' value='" . $id . "' name='id'><button type='submit' class='btn btn-sm btn-info'>" . $numberofbackups . "</button></form></center></td>"; echo "<td><center><form method='POST' action='index.php'><input type='hidden' value='" . $ip . "' name='ip'><input type='hidden' value='singlebackup' name='task'><button type='submit' class='btn btn-sm btn-success'>Backup</button></form></center></td>"; echo "<td><center><form method='POST' action='edit.php'><input type='hidden' value='" . $ip . "' name='ip'><input type='hidden' value='" . $name . "' name='name'><input type='hidden' value='edit' name='task'><button type='submit' class='btn btn-sm btn-warning'>Edit</button></form></center></td>"; echo "<td><center><form method='POST' id='deleteform' action='index.php'><input type='hidden' value='" . $ip . "' name='ip'><input type='hidden' value='" . $name . "' name='name'><input type='hidden' value='delete' name='task'><button type='submit' onclick='return window.confirm(\"Are you sure you want to delete " . $name . "\");' class='btn btn-sm btn-danger'>Delete</button></form></center></td></tr>\r\n"; // echo "<tr style='display:none'><td colspan='". ((isset($settings['hide_mac_column']) && $settings['hide_mac_column']=='Y')?'10':'11') ."'><iframe id='iframe".$id."' style='width:95vw;height:20vh' src=''></iframe></td></tr>"; // http://".$ip."/cs $list_model.='<div id="myModaldevice'.$id.'" class="modal fade" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h4 class="modal-title">'.$name.'</h4><button type="button" class="btn btn-sm close" data-bs-dismiss="modal">&times;</button></div><div class="modal-body"><p><pre>'."\r\n"; $list_model.=sprintf("%14s: %s\r\n%14s: %s\r\n%14s: %s\r\n%14s: %s\r\n%14s: %s","Name",$name,"IP",$ip,"MAC",$mac,"Type",$type,"Version",$ver); if(isset($tag)) $list_model.=sprintf("\r\n%14s: %s","BuildTag",$tag); $list_model.=sprintf("\r\n%14s: %s\r\n","Last Backup",$lastbackup); $list_model.='</pre></p></div><div class="modal-footer"><button type="button" class="btn btn-default" data-bs-dismiss="modal">Close</button></div></div></div></div>'."\r\n"; } ?> </tbody> </table> <center><form method='POST' action='index.php'><input type='hidden' value='backupall' name='task'><button type='submit' class='btn btn-sm btn-success'>Backup All</button></form><br> <form method="POST" action="scan.php"><input type=text name=range placeholder="192.168.1.1-255"><input type="password" name="password" placeholder="password" <?php if(isset($settings['tasmota_password'])) { echo 'value="'.$settings['tasmota_password'].'" '; } ?>><input type=hidden name=task value=scan><button style="min-width:200px" type=submit class='btn btn-sm btn-danger'>Discover</button></form> <?php if(isset($settings['mqtt_host']) && isset($settings['mqtt_port']) && strlen($settings['mqtt_host'])>1) { ?> <form method="POST" action="scan.php"><input type=text name=mqtt_topic value='<?php echo isset($settings['mqtt_topic'])?$settings['mqtt_topic']:'tasmotas'; ?>'><input type="password" name="password" placeholder="password" <?php if(isset($settings['tasmota_password'])) { echo 'value="'.$settings['tasmota_password'].'" '; } ?>><input type=hidden name=task value=mqtt><button style="min-width:200px" type=submit class='btn btn-sm btn-danger'>MQTT Discover</button></form> <?php } TBFooter(); echo '</div>'; if(isset($list_model)) { echo $list_model; ?> <script> $(document).ready(function() { $('.openConsole').on('click', function(){ let buttonClicked = $(this); buttonClicked.closest('tr').next('tr').toggle(); let row = buttonClicked.data('row'); let ip = buttonClicked.data('ip') $('#iframe'+row).attr('src', 'http://' + ip + '/cs'); }); }); function deviceModal(modalId) { $(modalId).modal('show'); } </script> <?php } if (isset($show_modal) && $show_modal): ?> <script> $(document).ready(function(){ $('#myModal').modal('show'); }); </script> <?php endif; ?> <!-- Modal --> <div id="myModal" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">TasmoBackup</h4> <button type="button" class="btn btn-sm close" data-bs-dismiss="modal">&times;</button> </div> <div class="modal-body"> <p style="align:center"> <?php if (isset($output)) { echo $output; } ?> <br> <?php if (isset($output2)) { echo $output2; } ?> </p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div>
php
MIT
ff65d7aeade785f40b50f91351f7786592ea5d2d
2026-01-05T04:48:49.060847Z
false
danmed/TasmoBackupV1
https://github.com/danmed/TasmoBackupV1/blob/ff65d7aeade785f40b50f91351f7786592ea5d2d/settings.php
settings.php
<?php require_once(__DIR__.'/lib/functions.inc.php'); global $db_handle; global $settings; if (isset($_POST["sortoption"])) { dbSettingsUpdate('sort',intval($_POST["sortoption"])); } if (isset($_POST["amountoption"])) { dbSettingsUpdate('amount',intval($_POST["amountoption"])); } if (isset($_POST['mqtt_host'])) { dbSettingsUpdate('mqtt_host',$_POST['mqtt_host']); } if (isset($_POST['mqtt_port'])) { dbSettingsUpdate('mqtt_port',intval($_POST['mqtt_port'])); } if (isset($_POST['mqtt_user'])) { dbSettingsUpdate('mqtt_user',$_POST['mqtt_user']); } if (isset($_POST['mqtt_password'])) { dbSettingsUpdate('mqtt_password',$_POST['mqtt_password']); } if (isset($_POST['mqtt_topic'])) { dbSettingsUpdate('mqtt_topic',trim($_POST['mqtt_topic']," \t\n\r\0\v/")); } if (isset($_POST['mqtt_topic_format'])) { dbSettingsUpdate('mqtt_topic_format',trim($_POST['mqtt_topic_format']," \t\n\r\0\v/")); } if (isset($_POST['backup_minhours'])) { dbSettingsUpdate('backup_minhours',intval($_POST['backup_minhours'])); } if (isset($_POST['backup_maxdays'])) { dbSettingsUpdate('backup_maxdays',intval($_POST['backup_maxdays'])); } if (isset($_POST['backup_maxcount'])) { dbSettingsUpdate('backup_maxcount',intval($_POST['backup_maxcount'])); } if (isset($_POST['backup_folder'])) { dbSettingsUpdate('backup_folder',$_POST['backup_folder']); } if (isset($_POST['tasmota_password'])) { dbSettingsUpdate('tasmota_password',$_POST['tasmota_password']); } if (isset($_POST['autoupdate_name'])) { if (in_array(strtolower($_POST['autoupdate_name']),array('y','yes','true','t'))) dbSettingsUpdate('autoupdate_name','Y'); else dbSettingsUpdate('autoupdate_name','N'); } if (isset($_POST['autoadd_scan'])) { if (in_array(strtolower($_POST['autoadd_scan']),array('y','yes','true','t'))) dbSettingsUpdate('autoadd_scan','Y'); else dbSettingsUpdate('autoadd_scan','N'); } if (isset($_POST['theme'])) { if (in_array(strtolower($_POST['theme']),array('light','dark','auto'))) dbSettingsUpdate('theme',strtolower($_POST['theme'])); } if (isset($_POST['use_topic_as_name'])) { if (in_array(strtolower($_POST['use_topic_as_name']),array('y','yes','true','t'))) dbSettingsUpdate('use_topic_as_name','Y'); else if (in_array(strtolower($_POST['use_topic_as_name']),array('f','full'))) dbSettingsUpdate('use_topic_as_name','F'); else dbSettingsUpdate('use_topic_as_name','N'); } if (isset($_POST['hide_mac_column'])) { if (in_array(strtolower($_POST['hide_mac_column']),array('y','yes','true','t'))) dbSettingsUpdate('hide_mac_column','Y'); else dbSettingsUpdate('hide_mac_column','N'); } TBHeader('Settings',true,' $(document).ready(function() { $(\'#status\').DataTable({ "order": [], "pageLength": '. (isset($settings['amount'])?$settings['amount']:25) .', "statesave": true, "autoWidth": false } ); } ); ',true); ?> <body> <div class="container-fluid"> <center><h4><a href="index.php">TasmoBackup</a> - Settings</h4></center> <form method='POST' action='settings.php'> <table class="table table-striped table-bordered" id="status" > <thead> <tr><th>Setting</th><th>Value</th></tr> </thead> <tbody> <tr valign='middle'><td align="right">Sort Column</td><td><select name ="sortoption"><option value="0" <?php if(isset($settings['sort']) && $settings['sort']==0) { echo 'selected="selected"'; } ?>>Name</option><option value="1" <?php if(isset($settings['sort']) && $settings['sort']==1) { echo 'selected="selected"'; } ?>>IP</option><option value="2" <?php if(isset($settings['sort']) && $settings['sort']==2) { echo 'selected="selected"'; } ?>>Auth</option><option value="3" <?php if(isset($settings['sort']) && $settings['sort']==3) { echo 'selected="selected"'; } ?>>Version</option><option value="4" <?php if(isset($settings['sort']) && $settings['sort']==4) { echo 'selected="selected"'; } ?>>Last Backup</option></select></td></tr> <tr valign='middle'><td align="right">Amount of Rows</td><td><input type='text' name='amountoption' value='<?php echo isset($settings['amount'])?$settings['amount']:100; ?>'></td></tr> <tr valign='middle'><td align="right">Theme (light or dark or auto)</td><td><input type="text" name='theme' value='<?php echo isset($settings['theme'])?$settings['theme']:'auto'; ?>'></td></tr> <tr valign='middle'><td align="right">Tasmota Default Password for web login on devices</td><td><input type="password" name='tasmota_password' value='<?php if(isset($settings['tasmota_password'])) echo $settings['tasmota_password']; ?>'></td></tr> <tr valign='middle'><td align="right">Update Device Name when doing Backups (Y or N)</td><td><input type="text" name='autoupdate_name' value='<?php echo isset($settings['autoupdate_name'])?$settings['autoupdate_name']:'Y'; ?>'></td></tr> <tr valign='middle'><td align="right">Automatically Add New Devices (Y or N)</td><td><input type="text" name='autoadd_scan' value='<?php echo isset($settings['autoadd_scan'])?$settings['autoadd_scan']:'N'; ?>'></td></tr> <tr valign='middle'><td align="right">Use MQTT Topic as Device Name (Y or N or F (Full))</td><td><input type="text" name='use_topic_as_name' value='<?php echo isset($settings['use_topic_as_name'])?$settings['use_topic_as_name']:'N'; ?>'></td></tr> <tr valign='middle'><td align="right">Hide MAC Address column on index page (Y or N)</td><td><input type="text" name='hide_mac_column' value='<?php echo isset($settings['hide_mac_column'])?$settings['hide_mac_column']:'N'; ?>'></td></tr> <tr valign='middle'><td align="right">MQTT Host</td><td><input type="text" name='mqtt_host' value='<?php if(isset($settings['mqtt_host'])) echo $settings['mqtt_host']; ?>'></td></tr> <tr valign='middle'><td align="right">MQTT Port</td><td><input type="text" name='mqtt_port' value='<?php echo isset($settings['mqtt_port'])?$settings['mqtt_port']:1883; ?>'></td></tr> <tr valign='middle'><td align="right">MQTT Username</td><td><input type="text" name='mqtt_user' value='<?php if(isset($settings['mqtt_user'])) echo $settings['mqtt_user']; ?>'></td></tr> <tr valign='middle'><td align="right">MQTT Password</td><td><input type="password" name='mqtt_password' value='<?php if(isset($settings['mqtt_password'])) echo $settings['mqtt_password']; ?>'></td></tr> <tr valign='middle'><td align="right">MQTT Topic</td><td><input type="text" name='mqtt_topic' value='<?php echo isset($settings['mqtt_topic'])?$settings['mqtt_topic']:'tasmotas'; ?>'></td></tr> <tr valign='middle'><td align="right">MQTT Topic Format</td><td><input type="text" name='mqtt_topic_format' value='<?php echo isset($settings['mqtt_topic_format'])?$settings['mqtt_topic_format']:'%prefix%/%topic%'; ?>'></td></tr> <tr valign='middle'><td align="right">Backup-All Min Hours between backups</td><td><input type="text" name='backup_minhours' value='<?php echo isset($settings['backup_minhours'])?$settings['backup_minhours']:'23'; ?>'></td></tr> <tr valign='middle'><td align="right">Backup Max Days Old to keep</td><td><input type="text" name='backup_maxdays' value='<?php echo isset($settings['backup_maxdays'])?$settings['backup_maxdays']:''; ?>'></td></tr> <tr valign='middle'><td align="right">Backup Max Count to keep</td><td><input type="text" name='backup_maxcount' value='<?php echo isset($settings['backup_maxcount'])?$settings['backup_maxcount']:''; ?>'></td></tr> <tr valign='middle'><td align="right">Backup Data Directory</td><td><input type="text" name='backup_folder' value='<?php echo $settings['backup_folder']; ?>'></td></tr> </tbody> <tfoot> <tr><td>&nbsp;</td><td><button type='submit' class='btn btn-sm btn-success'>Save</button></td></tr> </tfoot> </table> </form> <hr> <table > <tr valign='middle'> <td>Export Devices</td> <td style="padding-left:8px;"> <form method='POST' action='export.php'> <input type="hidden" name="export" value="export"> <select name ="sortoption"> <option value="0">CSV</option> </td> <td style="padding-left:8px;"><button type='submit' class='btn btn-sm btn-success'>Submit</button></form></td> </tr> </table> </div> <?php TBFooter();
php
MIT
ff65d7aeade785f40b50f91351f7786592ea5d2d
2026-01-05T04:48:49.060847Z
false
danmed/TasmoBackupV1
https://github.com/danmed/TasmoBackupV1/blob/ff65d7aeade785f40b50f91351f7786592ea5d2d/lib/functions.inc.php
lib/functions.inc.php
<?php require_once (__DIR__.'/db.inc.php'); $strJsonFileContents = file_get_contents(__DIR__.'/../HA_addon/config.json'); $array = json_decode($strJsonFileContents, true); $GLOBALS['VERSION']=$array['version']; function getBetween($content, $start, $end) { $r = explode($start, $content); if (isset($r[1])) { $r = explode($end, $r[1]); return $r[0]; } return ''; } function jsonTasmotaDecode($json) { $data=json_decode($json,true); if(json_last_error() == JSON_ERROR_CTRL_CHAR) { $data=json_decode(preg_replace('/[[:cntrl:]]/','',$json),true); } if(json_last_error() !== JSON_ERROR_NONE) { $string = substr( $json, strpos( $json, "STATUS = " ) ); if( strpos( $string, "POWER = " ) !== FALSE ) { $string = substr( $string, strpos( $string, "{" ) ); $string = substr( $string, 0, strrpos( $string, "}" )+1 ); } if( strpos( $string, "ERGEBNIS = " ) !== FALSE ) { $string = substr( $string, strpos( $string, "{" ) ); $string = substr( $string, 0, strrpos( $string, "}" )+1 ); } if( strpos( $string, "RESULT = " ) !== FALSE ) { $string = substr( $string, strpos( $string, "{" ) ); $string = substr( $string, 0, strrpos( $string, "}" )+1 ); } $remove = [ PHP_EOL, "\n", "STATUS = ", "}STATUS1 = {", "}STATUS2 = {", "}STATUS3 = {", "}STATUS4 = {", "}STATUS5 = {", "}STATUS6 = {", "}STATUS7 = {", "}in = {", "}STATUS8 = {", "}STATUS9 = {", "}STATUS10 = {", "}STATUS11 = {", "STATUS2 = ", ":nan,", ":nan}", ]; $replace = [ "", "", "", ",", ",", ",", ",", ",", ",", ",", ",", ",", ",", ",", ",", "", ":\"NaN\",", ":\"NaN\"}", ]; $string = str_replace( $remove, $replace, $string ); //remove everything befor ethe first { $string = strstr( $string, '{' ); $data=json_decode($string,true); if(json_last_error() !== JSON_ERROR_NONE) { $data=array(); } } return $data; } function getTasmotaScan($ip, $user, $password) { $url = 'http://'.rawurlencode($user).':'.rawurlencode($password).'@'. $ip . '/'; $ch = curl_init($url); curl_setopt_array($ch, array( CURLOPT_FOLLOWLOCATION => false, CURLOPT_TIMEOUT => 30, CURLOPT_CONNECTTIMEOUT => 12, CURLOPT_RETURNTRANSFER => true, CURLOPT_USERAGENT => 'TasmoBackup '.$GLOBALS['VERSION'], CURLOPT_ENCODING => "", CURLOPT_REFERER => 'http://'.$ip.'/', CURLOPT_HTTPHEADER => array('Origin: http://'.$ip), )); $data = curl_exec($ch); $err = curl_errno($ch); $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($err || $statusCode != 200) { return false; } if (strpos($data, 'Tasmota') !== false) { if (isset($settings['autoadd_scan']) && $settings['autoadd_scan']=='Y') { addTasmotaDevice($ip, $user, $password, true, false, 0); } else { return 0; } } if (strpos($data, 'WLED') !== false) { if (isset($settings['autoadd_scan']) && $settings['autoadd_scan']=='Y') { addTasmotaDevice($ip, $user, $password, true, false, 1); } else { return 1; } } return false; } function getTasmotaScanRange($iprange, $user, $password) { global $settings; $result=array(); $options = array( CURLOPT_FOLLOWLOCATION => false, CURLOPT_TIMEOUT => 30, CURLOPT_CONNECTTIMEOUT => 12, CURLOPT_RETURNTRANSFER => true, CURLOPT_USERAGENT => 'TasmoBackup '.$GLOBALS['VERSION'], CURLOPT_ENCODING => "", ); $range=15; if($range > count($iprange)) $range=count($iprange); $master = curl_multi_init(); for($i=0;$i<$range;$i++) { $url = 'http://'.rawurlencode($user).':'.rawurlencode($password).'@'. $iprange[$i] . '/'; $ch = curl_init($url); $options[CURLOPT_REFERER]='http://'.$iprange[$i].'/'; $options[CURLOPT_HTTPHEADER]=array('Origin: http://'.$iprange[$i]); curl_setopt_array($ch, $options); curl_multi_add_handle($master, $ch); } $i--; do { while(($execrun = curl_multi_exec($master, $run)) == CURLM_CALL_MULTI_PERFORM) { ; } if($execrun != CURLM_OK) { break; } while($done = curl_multi_info_read($master)) { $statusCode = curl_getinfo($done['handle'], CURLINFO_HTTP_CODE); $url = parse_url(curl_getinfo($done['handle'], CURLINFO_EFFECTIVE_URL)); $data = curl_multi_getcontent($done['handle']); if ($statusCode == 200) { if (strpos($data, 'Tasmota') !== false) { if (isset($settings['autoadd_scan']) && $settings['autoadd_scan']=='Y') { addTasmotaDevice($url['host'], $user, $password, true); } else { array_push($result,array($url['host'],0)); } } if (strpos($data, 'WLED') !== false) { if (isset($settings['autoadd_scan']) && $settings['autoadd_scan']=='Y') { addTasmotaDevice($url['host'], $user, $password, true, false, 1); } else { array_push($result,array($url['host'],1)); } } } unset($data); unset($url); unset($statusCode); if($i<count($iprange)) { $url = 'http://'.rawurlencode($user).':'.rawurlencode($password).'@'. $iprange[$i] . '/'; $ch = curl_init($url); $options[CURLOPT_REFERER]='http://'.$iprange[$i].'/'; $options[CURLOPT_HTTPHEADER]=array('Origin: http://'.$iprange[$i]); curl_setopt_array($ch, $options); $i++; curl_multi_add_handle($master, $ch); } curl_multi_remove_handle($master, $done['handle']); curl_close($done['handle']); } } while($run); curl_multi_close($master); return $result; } function getTasmotaStatus($ip, $user, $password, $type=0) { //Get Name $url = 'http://' .rawurlencode($user).':'.rawurlencode($password).'@'. $ip . '/cm?cmnd=status%200&user='.rawurlencode($user).'&password=' . rawurlencode($password); if(intval($type)===1) $url = 'http://' .rawurlencode($user).':'.rawurlencode($password).'@'. $ip . '/json'; $options = array( CURLOPT_FOLLOWLOCATION => false, CURLOPT_TIMEOUT => 30, CURLOPT_CONNECTTIMEOUT => 12, CURLOPT_RETURNTRANSFER => true, CURLOPT_USERAGENT => 'TasmoBackup '.$GLOBALS['VERSION'], CURLOPT_ENCODING => "", CURLOPT_REFERER => 'http://'.$ip.'/', CURLOPT_HTTPHEADER => array('Origin: http://'.$ip), ); $ch = curl_init($url); curl_setopt_array($ch, $options); $data = curl_exec($ch); $err = curl_errno($ch); $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($err || $statusCode != 200) { return false; } $json=jsonTasmotaDecode($data); if(isset($json["Status"])) return $json; if(isset($json["info"])) return $json; sleep(1); $data=getTasmotaOldStatus($ip, $user, $password); if(isset($data['Status'])) { $json["Status"]=$data["Status"]; } return $json; } function getTasmotaOldStatus($ip, $user, $password) { //Get Name $url = 'http://' .rawurlencode($user).':'.rawurlencode($password).'@'. $ip . '/cm?cmnd=status&user='.rawurlencode($user).'&password=' . rawurlencode($password); $options = array( CURLOPT_FOLLOWLOCATION => false, CURLOPT_TIMEOUT => 30, CURLOPT_CONNECTTIMEOUT => 12, CURLOPT_RETURNTRANSFER => true, CURLOPT_USERAGENT => 'TasmoBackup '.$GLOBALS['VERSION'], CURLOPT_ENCODING => "", CURLOPT_REFERER => 'http://'.$ip.'/', CURLOPT_HTTPHEADER => array('Origin: http://'.$ip), ); $ch = curl_init($url); curl_setopt_array($ch, $options); $data = curl_exec($ch); $err = curl_errno($ch); $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($err || $statusCode != 200) { return false; } return jsonTasmotaDecode($data); } function getTasmotaStatus2($ip, $user, $password) { //Get Version $url = 'http://' . rawurlencode($user).':'.rawurlencode($password).'@'. $ip . '/cm?cmnd=status%202&user='.rawurlencode($user).'&password=' . rawurlencode($password); $options = array( CURLOPT_FOLLOWLOCATION => false, CURLOPT_TIMEOUT => 30, CURLOPT_CONNECTTIMEOUT => 12, CURLOPT_RETURNTRANSFER => true, CURLOPT_USERAGENT => 'TasmoBackup '.$GLOBALS['VERSION'], CURLOPT_ENCODING => "", CURLOPT_REFERER => 'http://'.$ip.'/', CURLOPT_HTTPHEADER => array('Origin: http://'.$ip), ); $ch = curl_init($url); curl_setopt_array($ch, $options); $data = curl_exec($ch); $err = curl_errno($ch); $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($err || $statusCode != 200) { return false; } return jsonTasmotaDecode($data); } function getTasmotaStatus5($ip, $user, $password) { //Get Mac $url = 'http://' . rawurlencode($user).':'.rawurlencode($password).'@'. $ip . '/cm?cmnd=status%205&user='.rawurlencode($user).'&password=' . rawurlencode($password); $options = array( CURLOPT_FOLLOWLOCATION => false, CURLOPT_TIMEOUT => 30, CURLOPT_CONNECTTIMEOUT => 12, CURLOPT_RETURNTRANSFER => true, CURLOPT_USERAGENT => 'TasmoBackup '.$GLOBALS['VERSION'], CURLOPT_ENCODING => "", CURLOPT_REFERER => 'http://'.$ip.'/', CURLOPT_HTTPHEADER => array('Origin: http://'.$ip), ); $ch = curl_init($url); curl_setopt_array($ch, $options); $data = curl_exec($ch); $err = curl_errno($ch); $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($err || $statusCode != 200) { return false; } return jsonTasmotaDecode($data); } function restoreTasmotaBackup($ip, $user, $password, $filename) { $url = 'http://'.rawurlencode($user).':'.rawurlencode($password)."@".$ip.'/u2'; $cfile = new CURLFile($filename,'application/octet-stream','config.dmp'); $fields = array('u2' => $cfile); $options = array( CURLOPT_FOLLOWLOCATION => false, CURLOPT_TIMEOUT => 60, CURLOPT_CONNECTTIMEOUT => 12, CURLOPT_RETURNTRANSFER => true, CURLOPT_USERAGENT => 'TasmoBackup '.$GLOBALS['VERSION'], CURLOPT_POST => true, CURLOPT_POSTFIELDS => $fields, CURLOPT_HTTPHEADER => array('Content-Type: multipart/form-data'), CURLOPT_ENCODING => "", CURLOPT_REFERER => 'http://'.$ip.'/', CURLOPT_HTTPHEADER => array('Origin: http://'.$ip, 'Expect:'), ); $ch = curl_init($url); curl_setopt_array($ch, $options); $result=curl_exec($ch); $err = curl_errno($ch); $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if (!$err && $statusCode == 200) { return true; } return false; } function downloadTasmotaBackup($backup) { if(file_exists($backup['filename'])) { $filename = $backup['name'] . '-' . $backup['version'] . '-' . $backup['date']; $filename = preg_replace('/(\s+|:|\.|\()/', '_', $filename); $filename = preg_replace('/[^A-Za-z0-9_\-]/', '', $filename); header("Cache-Control: no-cache private",true); header("Content-Description: Backup ".$backup['name']); header('Content-disposition: attachment; filename="'.$filename.'.dmp"',true); header("Content-Type: application/octet-stream",true); header("Content-Transfer-Encoding: binary",true); header('Content-Length: '. filesize($backup['filename']),true); readfile($backup['filename']); exit(0); } return false; } function getTasmotaBackup($ip, $user, $password, $filename, $type=0) { //Get Backup if(intval($type)===0) { // Tasmota $fp = fopen($filename, 'w+'); if ($fp === false) { return false; } $url = 'http://'.rawurlencode($user).':'.rawurlencode($password)."@".$ip.'/dl'; $options = array( CURLOPT_FOLLOWLOCATION => false, CURLOPT_TIMEOUT => 60, CURLOPT_CONNECTTIMEOUT => 12, CURLOPT_RETURNTRANSFER => true, CURLOPT_USERAGENT => 'TasmoBackup '.$GLOBALS['VERSION'], CURLOPT_ENCODING => "", CURLOPT_REFERER => 'http://'.$ip.'/', CURLOPT_HTTPHEADER => array('Origin: http://'.$ip), ); $ch = curl_init($url); curl_setopt_array($ch, $options); curl_setopt($ch,CURLOPT_FILE,$fp); curl_exec($ch); $err = curl_errno($ch); $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); fclose($fp); curl_close($ch); if (!$err && $statusCode == 200) { return true; } } else if(intval($type)===1) { // WLED $url = 'http://'.rawurlencode($user).':'.rawurlencode($password)."@".$ip.'/edit?download=cfg.json'; //parsing version from filename $version = substr(strstr(basename($filename, '.zip'), 'v'), 1); if (version_compare($version,'0.13.1', '>')){ $url = 'http://'.rawurlencode($user).':'.rawurlencode($password)."@".$ip.'/cfg.json?download'; } $options = array( CURLOPT_FOLLOWLOCATION => false, CURLOPT_TIMEOUT => 60, CURLOPT_CONNECTTIMEOUT => 12, CURLOPT_RETURNTRANSFER => true, CURLOPT_USERAGENT => 'TasmoBackup '.$GLOBALS['VERSION'], CURLOPT_ENCODING => "", CURLOPT_REFERER => 'http://'.$ip.'/', CURLOPT_HTTPHEADER => array('Origin: http://'.$ip), ); $ch = curl_init($url); curl_setopt_array($ch, $options); $cfg = curl_exec($ch); $err = curl_errno($ch); $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if($err || $statusCode !== 200) return false; $url = 'http://'.rawurlencode($user).':'.rawurlencode($password)."@".$ip.'/edit?download=presets.json'; if (version_compare($version,'0.13.0', '>')){ $url = 'http://'.rawurlencode($user).':'.rawurlencode($password)."@".$ip.'/presets.json?download'; } $ch = curl_init($url); curl_setopt_array($ch, $options); $presets = curl_exec($ch); $err = curl_errno($ch); $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if($err || $statusCode !== 200) return false; $zip = new ZipArchive; if($zip->open($filename, ZipArchive::CREATE) === FALSE) return false; if($zip->addFromString('cfg.json', $cfg) === FALSE) return false; if($zip->addFromString('presets.json', $presets) === FALSE) return false; $zip->close(); return true; } return false; } function backupCleanup($id) { global $settings; $backupfolder = $settings['backup_folder']; $days=0; $count=0; if(isset($settings['backup_maxdays'])) $days=intval($settings['backup_maxdays']); if(isset($settings['backup_maxcount'])) $count=intval($settings['backup_maxcount']); if($days>0 || $count>0) return dbBackupTrim($id,$days,$count); return true; } function backupSingle($id, $name, $ip, $user, $password, $type=0) { global $settings; $backupfolder = $settings['backup_folder']; if ($status=getTasmotaStatus($ip, $user, $password, $type)) { if(intval($type)===0) { // Tasmota if (!isset($status['StatusFWR'])) { sleep(1); if ($status2=getTasmotaStatus2($ip, $user, $password)) { $status['StatusFWR']=$status2['StatusFWR']; } else return true; // Device Offline } if (!isset($status['StatusNET'])) { sleep(1); if ($status5=getTasmotaStatus5($ip, $user, $password)) { $status['StatusNET']=$status5['StatusNET']; } else return true; // Device Offline } } if(intval($type)===1) { // WLED if (!isset($status['info']['ver'])) return true; } } else { return true; // Device Offline } if(intval($type)===0) { // Tasmota $version = $status['StatusFWR']['Version']; $mac = strtoupper($status['StatusNET']['Mac']); if (!isset($settings['autoupdate_name']) || (isset($settings['autoupdate_name']) && $settings['autoupdate_name']=='Y')) { if(isset($settings['use_topic_as_name']) && $settings['use_topic_as_name']=='F') { // Empty } else { if (isset($status['Status']['Topic'])) $name=$status['Status']['Topic']; if(!isset($settings['use_topic_as_name']) || $settings['use_topic_as_name']=='N') { if (isset($status['Status']['DeviceName']) && strlen(preg_replace('/\s+/', '',$status['Status']['DeviceName']))>0) $name=$status['Status']['DeviceName']; else if (isset($status['Status']['FriendlyName'][0])) $name=$status['Status']['FriendlyName'][0]; } } } } else if (intval($type)===1) { // WLED if(isset($status['info']['name'])) $name=trim($status['info']['name']); if(isset($status['info']['ver'])) $version=trim($status['info']['ver']); if(isset($status['info']['mac'])) $mac=implode(':',str_split(str_replace(array('.',':'),array('',''),trim($status['info']['mac'])),2)); } $savename = preg_replace('/\s+/', '_', $name); $savename = preg_replace('/[^A-Za-z0-9_\-]/', '', $savename); $savemac = preg_replace('/[^A-Za-z0-9_\-]/','', $mac); if (!file_exists($backupfolder . $savename)) { $oldmask = umask(0); mkdir($backupfolder . $savename, 0777, true); umask($oldmask); } $date = date('Y-m-d H:i:s'); $savedate = preg_replace('/(\s+|:)/', '_', $date); $savedate = preg_replace('/[^A-Za-z0-9_\-]/', '', $savedate); $ext='.dmp'; if(intval($type)===1) $ext='.zip'; $saveto = $backupfolder . $savename . "/" . $savemac . "-" . $savedate . '-v' . $version . $ext; sleep(1); if (getTasmotaBackup($ip, $user, $password, $saveto, $type)) { $directory = $backupfolder . $savename . "/"; /* // Initialize filecount variavle $filecount = 0; $files2 = glob($directory . "*"); if ($files2) { $noofbackups = count($files2); #echo $noofbackups; } */ if (!dbNewBackup($id, $name, $version, $date, 1, $saveto, $mac, $type)) { return true; } return false; } return false; } function backupAll($docker=false) { global $db_handle; global $settings; $hours=0; if(isset($settings['backup_minhours'])) $hours=intval($settings['backup_minhours']); if($docker && $hours==0) return false; if ($docker && isset($settings['autoadd_scan']) && $settings['autoadd_scan']=='Y') { // auto scan on schedule if(isset($settings['mqtt_host']) && isset($settings['mqtt_port']) && strlen($settings['mqtt_host'])>1) { require_once(__DIR__.'/mqtt.inc.php'); $mqtt=setupMQTT($settings['mqtt_host'], $settings['mqtt_port'], $settings['mqtt_user'], $settings['mqtt_password']); $username='admin'; if(isset($settings['tasmota_username'])) $username=$settings['tasmota_username']; $password=''; if(isset($settings['tasmota_password'])) $password=$settings['tasmota_password']; if($mqtt) getTasmotaMQTTScan($mqtt,$settings['mqtt_topic'],$username,$password,true); } } $stm = $db_handle->prepare("select * from devices where lastbackup < :date or lastbackup is NULL "); $stm->execute(array(":date" => date('Y-m-d H:i:s',time()-(3600*$hours)))); $errorcount = 0; $totalcount = 0; while ($db_field = $stm->fetch(PDO::FETCH_ASSOC)) { $totalcount++; if (backupSingle($db_field['id'], $db_field['name'], $db_field['ip'], 'admin', $db_field['password'], $db_field['type'])) { $errorcount++; } else { backupCleanup($db_field['id']); } } return array($errorcount,$totalcount); } function addTasmotaDevice($ip, $user, $password, $verified=false, $status=false, $type=null) { global $settings; if(!$verified || !isset($type)) { if (($type=getTasmotaScan($ip, $user, $password))===false) { return $ip.': Device not found.'; } } if (!dbDeviceExist($ip)) { if ($status===false) $status=getTasmotaStatus($ip, $user, $password, $type); if (isset($status) && $status) { if(intval($type)===0) { // Tasmota if (!isset($status['StatusNET'])) { sleep(1); if ($status5=getTasmotaStatus5($ip, $user, $password)) $status['StatusNET']=$status5['StatusNET']; else return $ip.': Device not responding to status5 request.'; } if(!isset($status['StatusFWR'])) { sleep(1); if ($status2=getTasmotaStatus2($ip, $user, $password)) $status['StatusFWR']=$status2['StatusFWR']; else return $ip.': Device not responding to status2 request.'; } if(isset($settings['use_topic_as_name']) && $settings['use_topic_as_name']=='F' && isset($status['Topic'])) { $name=trim(str_replace(array('/stat','stat/'),array('',''),$status['Topic'])," \t\r\n\v\0/");; } else { if (isset($status['Status']['Topic'])) $name=$status['Status']['Topic']; if(!isset($settings['use_topic_as_name']) || $settings['use_topic_as_name']=='N') { if (isset($status['Status']['DeviceName']) && strlen(preg_replace('/\s+/', '',$status['Status']['DeviceName']))>0) $name=$status['Status']['DeviceName']; else if ($status['Status']['FriendlyName'][0]) $name=$status['Status']['FriendlyName'][0]; } } if (isset($status['StatusFWR']['Version'])) $version=$status['StatusFWR']['Version']; if (isset($status['StatusNET']['Mac'])) $mac=strtoupper($status['StatusNET']['Mac']); } else if (intval($type)===1) { // WLED if(isset($status['info']['name'])) $name=trim($status['info']['name']); if(isset($status['info']['ver'])) $version=trim($status['info']['ver']); if(isset($status['info']['mac'])) $mac=implode(':',str_split(str_replace(array('.',':'),array('',''),trim($status['info']['mac'])),2)); } if (($id=dbDeviceFind($ip,$mac))>0) { if (!isset($settings['autoupdate_name']) || (isset($settings['autoupdate_name']) && $settings['autoupdate_name']=='Y')) $newname=$name; if(dbDeviceUpdate($id,$newname,$ip,$version,$password,$mac,$type)) return $ip.': ' . $name . ' infomation has been updated!'; else return $ip.': ' . $name . ' already exists in the database!'; } else { if (dbDeviceAdd($name, $ip, $version, $password, $mac, $type)) { return $ip.': ' . $name . ' Added Successfully!'; } } return $ip.': '. $name . ' Error adding device to database.'; } return $ip.': Device not responding to status request.'; } else { // Update device metadata, but only if scanned via mqtt as not to add more overhead if (isset($status) && $status) { if(intval($type)===0) { if(isset($settings['use_topic_as_name']) && $settings['use_topic_as_name']=='F' && isset($status['Topic'])) { $name=trim(str_replace(array('/stat','stat/'),array('',''),$status['Topic'])," \t\r\n\v\0/");; } else { if (isset($status['Status']['Topic'])) $name=$status['Status']['Topic']; if(!isset($settings['use_topic_as_name']) || $settings['use_topic_as_name']=='N') { if (isset($status['Status']['DeviceName']) && strlen(preg_replace('/\s+/', '',$status['Status']['DeviceName']))>0) $name=$status['Status']['DeviceName']; else if (isset($status['Status']['FriendlyName'][0])) $name=$status['Status']['FriendlyName'][0]; } } if (isset($status['StatusFWR']['Version'])) $version=$status['StatusFWR']['Version']; if (isset($status['StatusNET']['Mac'])) $mac=strtoupper($status['StatusNET']['Mac']); } else if (intval($type)===1) { // WLED if(isset($status['info']['name'])) $name=trim($status['info']['name']); if(isset($status['info']['ver'])) $version=trim($status['info']['ver']); if(isset($status['info']['mac'])) $mac=implode(':',str_split(str_replace(array('.',':'),array('',''),trim($status['info']['mac'])),2)); } if (($id=dbDeviceFind($ip,$mac))>0) { if (!isset($settings['autoupdate_name']) || (isset($settings['autoupdate_name']) && $settings['autoupdate_name']=='Y') && isset($name)) $newname=$name; if(dbDeviceUpdate($id,isset($newname)?$newname:NULL,$ip,isset($version)?$version:NULL,$password,isset($mac)?$mac:NULL,$type)) return $ip.': ' . (isset($name)?$name:'') . ' infomation has been updated!'; else return $ip.': ' . (isset($name)?$name:'') . ' already exists in the database!'; } } } return $ip.': This device already exists in the database!'; } function TBHeader($name=false,$favicon=true,$init=false,$track=true,$redirect=false) { global $settings; $colormode = 'auto'; if(isset($settings['theme']) && $settings['theme']=='light') { // Enforce Light mode $colormode = 'light'; } if(isset($settings['theme']) && $settings['theme']=='dark') { // Enforce Dark mode $colormode = 'dark'; } echo '<!DOCTYPE html><html lang="en"><head>'; if($redirect!==false && $redirect>0) { echo '<meta http-equiv="refresh" content="'.$redirect.';url=index.php" />'; } if($favicon) { ?> <link rel="shortcut icon" href="favicon.ico"> <link rel="icon" sizes="16x16 32x32 64x64" href="favicon.ico"> <link rel="icon" type="image/png" sizes="196x196" href="favicon/192.png"> <link rel="icon" type="image/png" sizes="160x160" href="favicon/160.png"> <link rel="icon" type="image/png" sizes="96x96" href="favicon/96.png"> <link rel="icon" type="image/png" sizes="64x64" href="favicon/64.png"> <link rel="icon" type="image/png" sizes="32x32" href="favicon/32.png"> <link rel="icon" type="image/png" sizes="16x16" href="favicon/16.png"> <link rel="apple-touch-icon" href="favicon/57.png"> <link rel="apple-touch-icon" sizes="114x114" href="favicon/114.png"> <link rel="apple-touch-icon" sizes="72x72" href="favicon/72.png"> <link rel="apple-touch-icon" sizes="144x144" href="favicon/144.png"> <link rel="apple-touch-icon" sizes="60x60" href="favicon/60.png"> <link rel="apple-touch-icon" sizes="120x120" href="favicon/120.png"> <link rel="apple-touch-icon" sizes="76x76" href="favicon/76.png"> <link rel="apple-touch-icon" sizes="152x152" href="favicon/152.png"> <link rel="apple-touch-icon" sizes="180x180" href="favicon/180.png"> <?php } if($track) { ?> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-116906-4"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-116906-4'); </script> <?php } ?> <title>TasmoBackup<?php if($name!==false) { echo ': '.$name; } ?></title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="resources/bootstrap.min.css"> <script src="resources/jquery.min.js"></script> <script src="resources/bootstrap.min.js"></script> <?php if($init !== false) { ?> <script src="resources/datatables.min.js"></script> <script src="resources/sorting.min.js"></script> <link rel="stylesheet" type="text/css" href="resources/datatables.min.css"/> <script class="init"> <?php echo $init; ?> </script> <?php } ?> <script> function updateColorScheme(mode) { if(mode === 'light') { document.documentElement.setAttribute('data-bs-theme', 'light'); } else if(mode === 'dark') { document.documentElement.setAttribute('data-bs-theme', 'dark'); } else { document.documentElement.setAttribute('data-bs-theme', window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'); } } updateColorScheme('<?php echo $colormode; ?>'); window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', updateColorScheme); </script> </head> <?php } function TBFooter() { global $VERSION; ?> <br><br> <div style='text-align:right;font-size:11px;'><hr/><a href='https://github.com/danmed/TasmoBackupV1' target='_blank' style='color:#aaa;'>TasmoBackup <?php echo $GLOBALS['VERSION']; ?> by Dan Medhurst</a></div> <?php } function getGithubTasmotaReleaseData() { global $settings; // put the releases json in the backup_folder $backupfolder = $settings['backup_folder']; $get_new_version = false; $github_tasmota_release_data_file = $backupfolder . "/github-tasmota-release-data.json"; // check if file exists if ( file_exists($github_tasmota_release_data_file) === true ) { $_mtime = filemtime($github_tasmota_release_data_file); $yesterday = strtotime("-1 days"); if ( $_mtime <= $yesterday ) { $get_new_version = true; } } else { $get_new_version = true; } if ( $get_new_version ) { // get Tasmota release data from github - but only if it is the next calendar day $opts = [ 'http' => [ 'method' => 'GET', 'header' => [ 'User-Agent: PHP' ] ] ]; $context = stream_context_create($opts); $github_tasmota_version_release_details = file_get_contents("https://api.github.com/repos/arendst/Tasmota/releases", false, $context); file_put_contents($github_tasmota_release_data_file, $github_tasmota_version_release_details); } else { $github_tasmota_version_release_details = file_get_contents($github_tasmota_release_data_file); } $github_tasmota_release_data = json_decode($github_tasmota_version_release_details, true); return $github_tasmota_release_data; }
php
MIT
ff65d7aeade785f40b50f91351f7786592ea5d2d
2026-01-05T04:48:49.060847Z
false
danmed/TasmoBackupV1
https://github.com/danmed/TasmoBackupV1/blob/ff65d7aeade785f40b50f91351f7786592ea5d2d/lib/db.inc.php
lib/db.inc.php
<?php require_once(__DIR__.'/../data/config.inc.php'); global $db_handle; global $settings; global $db_upgrade; if ($DBType=='mysql') { $db_handle = new \PDO('mysql:host='.$DBServer.';dbname='.$DBName, $DBUser, $DBPassword); $GLOBALS['DBType']='mysql'; } if ($DBType=='sqlite') { if (!isset($DBName)) { $DBName = 'data/tasmobackupdb'; } if (substr_compare($DBName,'data/',0,5)==0) { $DBName = __DIR__.'/../'.$DBName; } $db_handle = new \PDO('sqlite:'.$DBName.'.sqlite3'); $GLOBALS['DBType']='sqlite'; } if ($db_handle && $db_upgrade) { if ($GLOBALS['DBType']=='mysql') { $db_handle->exec("CREATE TABLE IF NOT EXISTS devices ( id int(11) AUTO_INCREMENT PRIMARY KEY NOT NULL, name varchar(128) NOT NULL, ip varchar(64) NOT NULL, mac varchar(32) NOT NULL, type int(4) NOT NULL DEFAULT 0, version varchar(128) NOT NULL, lastbackup datetime DEFAULT NULL, noofbackups int(11) DEFAULT NULL, password varchar(128) DEFAULT NULL ) "); $db_handle->exec("CREATE TABLE IF NOT EXISTS backups ( id bigint(20) AUTO_INCREMENT PRIMARY KEY NOT NULL, deviceid int(11) NOT NULL, name varchar(128) NOT NULL, version varchar(128) NOT NULL, date datetime DEFAULT NULL, filename varchar(1080), data text, INDEX (deviceid,date) ) "); $db_handle->exec("CREATE TABLE IF NOT EXISTS settings ( name varchar(128) PRIMARY KEY NOT NULL, value varchar(255) NOT NULL ) "); $stm=$db_handle->prepare("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='".$GLOBALS['DBName']."' AND TABLE_NAME='devices' AND COLUMN_NAME='mac';"); $stm->execute(); $cnt=intval($stm->fetchColumn()); if($cnt<1) { $db_handle->exec("ALTER TABLE devices ADD COLUMN mac varchar(32) NOT NULL DEFAULT '' AFTER ip;"); } $stm=$db_handle->prepare("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='".$GLOBALS['DBName']."' AND TABLE_NAME='devices' AND COLUMN_NAME='type';"); $stm->execute(); $cnt=intval($stm->fetchColumn()); if($cnt<1) { $db_handle->exec("ALTER TABLE devices ADD COLUMN type int(3) NOT NULL DEFAULT 0 AFTER mac;"); } } if ($GLOBALS['DBType']=='sqlite') { $db_handle->exec("CREATE TABLE IF NOT EXISTS devices ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name varchar(128) NOT NULL, ip varchar(64) NOT NULL, mac varchar(32) NOT NULL, type INTEGER NOT NULL DEFAULT 0, version varchar(128) NOT NULL, lastbackup datetime DEFAULT NULL, noofbackups INTEGER DEFAULT NULL, password varchar(128) DEFAULT NULL ) "); $db_handle->exec("CREATE TABLE IF NOT EXISTS backups ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, deviceid INTEGER NOT NULL, name varchar(128) NOT NULL, version varchar(128) NOT NULL, date datetime DEFAULT NULL, filename varchar(1080), data text ) "); $db_handle->exec("CREATE INDEX IF NOT EXISTS backupsdeviceid ON backups(deviceid, date) "); $db_handle->exec("CREATE TABLE IF NOT EXISTS settings ( name varchar(128) PRIMARY KEY NOT NULL, value varchar(255) NOT NULL ) "); $curstate = error_reporting(); error_reporting(0); @$db_handle->exec("ALTER TABLE devices ADD COLUMN mac varchar(32) NOT NULL DEFAULT ''"); @$db_handle->exec("ALTER TABLE devices ADD COLUMN type INTEGER NOT NULL DEFAULT 0"); error_reporting($curstate); } } if ($db_handle) { $stm = $db_handle->prepare("select name,value from settings"); if($stm && $stm->execute()) { while($result=$stm->fetch(PDO::FETCH_ASSOC)) { $settings[$result['name']]=$result['value']; } } } if(!isset($settings['backup_folder'])) $settings['backup_folder']='data/backups/'; else if(substr($settings['backup_folder'],-1) !== '/') $settings['backup_folder'] .= '/'; if(isset($settings['mqtt_topic_format'])) $settings['mqtt_topic_format']=trim($settings['mqtt_topic_format']," \t\n\r\0\v/"); function dbSettingsUpdate($name,$value) { global $db_handle; global $settings; $stm = $db_handle->prepare("REPLACE INTO settings(name,value) VALUES(:name,:value)"); if(!$stm->execute(array(':value'=>$value,':name'=>$name))) return false; $settings[$name]=$value; return true; } function dbDeviceExist($ip=NULL,$mac=NULL) { global $db_handle; if(isset($mac)){ $stm = $db_handle->prepare("select count(*) from devices where mac = :mac"); $stm->bindValue(':mac', $mac, PDO::PARAM_STR); if ($stm->execute()) { if ($stm->fetchColumn() > 0 ) return true; } } if(isset($ip)) { $stm = $db_handle->prepare("select count(*) from devices where ip = :ip"); $stm->bindValue(':ip', $ip, PDO::PARAM_STR); } if ($stm->execute()) { if ($stm->fetchColumn() > 0) return true; } return false; } function dbDeviceFind($ip=NULL,$mac=NULL) { global $db_handle; if(isset($mac)){ $stm = $db_handle->prepare("select id from devices where mac = :mac"); $stm->bindValue(':mac', $mac, PDO::PARAM_STR); if ($stm->execute()) { if (($data=$stm->fetchColumn()) > 0 ) return $data; } } if(isset($ip)) { $stm = $db_handle->prepare("select id from devices where ip = :ip"); $stm->bindValue(':ip', $ip, PDO::PARAM_STR); } if ($stm->execute()) { if (($data=$stm->fetchColumn()) > 0) return $data; } return false; } function dbDeviceIp($ip) { global $db_handle; $stm = $db_handle->prepare("select * from devices where ip = :ip"); $stm->bindValue(':ip', $ip, PDO::PARAM_STR); if (!$stm->execute()) { return false; } return $stm->fetchAll(PDO::FETCH_ASSOC); } function dbDeviceMac($mac) { global $db_handle; $stm = $db_handle->prepare("select * from devices where mac = :mac"); $stm->bindValue(':mac', $mac, PDO::PARAM_STR); if (!$stm->execute()) { return false; } return $stm->fetchAll(PDO::FETCH_ASSOC); } function dbDeviceId($id) { global $db_handle; $stm = $db_handle->prepare("select * from devices where id = :id"); $stm->bindValue(':id', $id, PDO::PARAM_INT); if (!$stm->execute()) { return false; } return $stm->fetch(PDO::FETCH_ASSOC); } function dbDevices() { global $db_handle; $stm = $db_handle->prepare("select * from devices"); if (!$stm->execute()) { return false; } return $stm->fetchAll(PDO::FETCH_ASSOC); } function dbBackupId($id) { global $db_handle; $stm = $db_handle->prepare("select * from backups where id = :id "); $stm->bindValue(':id', $id, PDO::PARAM_INT); if (!$stm->execute()) { return false; } return $stm->fetch(PDO::FETCH_ASSOC); } function dbBackupList($id,$days=0) { global $db_handle; $days=intval($days); $datecond=''; if($days>0) { $date = date('Y-m-d H:i:s',time()-(86400*$days)); $datecond = ' and date < "'.$date.'" '; } $stm = $db_handle->prepare("select * from backups where deviceid = :id ".$datecond." order by date desc"); $stm->bindValue(':id', $id, PDO::PARAM_INT); if (!$stm->execute()) { return false; } return $stm->fetchAll(PDO::FETCH_ASSOC); } function dbBackupCount($id) { global $db_handle; $stm = $db_handle->prepare("select count(*) from backups where deviceid = :id"); $stm->bindValue(':id', $id, PDO::PARAM_INT); if (!$stm->execute()) { return false; } return $stm->fetchColumn(); } function dbBackupTrim($id,$days,$count,$all=false) { global $db_handle; $days=intval($days); $count=intval($count); if($days==0 && $count==0 && !$all) return true; $result=dbBackupList($id,$days); if(!is_array($result)) return false; if(count($result)<1) return true; if($count>0) { $backups=dbBackupCount($id); $count=($backups-$count); // Number to save - total backups - Number over age = number to remove if($count>count($result)) $count=count($result); } else { $count=count($result); } if($count>0) { for(;$count>0;$count--) { $backup=array_pop($result); unlink($backup['filename']); $stm = $db_handle->prepare("delete from backups where id = :id"); $stm->execute(array(":id" => $backup['id'])); } dbDeviceBackups($id); } } function dbBackupDel($id) { global $db_handle; $stm = $db_handle->prepare("select * from backups where id = :id"); $stm->bindValue(':id',$id, PDO::PARAM_INT); if(!$stm->execute()) return false; $row=$stm->fetch(PDO::FETCH_ASSOC); if(isset($row['filename'])) unlink($row['filename']); $stm = $db_handle->prepare("delete from backups where id = :id"); $stm->bindValue(':id',$id, PDO::PARAM_INT); return $stm->execute(); } function dbDevicesListBackups($count) { global $db_handle; $stm = $db_handle->prepare("select id from devices where noofbackups > :count "); $stm->bindValue(':count', $count, PDO::PARAM_INT); if (!$stm->execute()) { return false; } return $stm->fetchAll(PDO::FETCH_ASSOC); } function dbDevicesSort() { global $db_handle; $stm = $db_handle->prepare("select * from devices order by name desc"); if (!$stm->execute()) { return false; } return $stm->fetchAll(PDO::FETCH_ASSOC); } function dbDeviceAdd($name, $ip, $version, $password, $mac, $type=0) { global $db_handle; $stm = $db_handle->prepare("INSERT INTO devices (name,ip,mac,type,version,password) VALUES (:name, :ip, :mac, :type, :version, :password)"); $stm->bindValue(':name', $name, PDO::PARAM_STR); $stm->bindValue(':ip', $ip, PDO::PARAM_STR); $stm->bindValue(':mac', $mac, PDO::PARAM_STR); $stm->bindValue(':type', $type, PDO::PARAM_INT); $stm->bindValue(':version', $version, PDO::PARAM_STR); $stm->bindValue(':password', $password, PDO::PARAM_STR); return $stm->execute(); } function dbDeviceRename($oldip, $name, $ip, $password, $mac=NULL) { global $db_handle; $stm = $db_handle->prepare("UPDATE devices SET name = :name, ip = :ip, password = :password WHERE ip = :oldip"); $stm->bindValue(':name', $name, PDO::PARAM_STR); $stm->bindValue(':ip', $ip, PDO::PARAM_STR); $stm->bindValue(':password', $password, PDO::PARAM_STR); $stm->bindValue(':oldip', $oldip, PDO::PARAM_STR); return $stm->execute(); } function dbDeviceDel($ip) { global $db_handle; $stm = $db_handle->prepare("select id from devices where ip = :ip"); $stm->bindValue(':ip', $ip, PDO::PARAM_STR); if (!$stm->execute()) return false; $id=intval($stm->fetchColumn()); if($id==0) return false; dbBackupTrim($id,0,0,true); $stm = $db_handle->prepare("delete from devices where id = :id"); $stm->bindValue(':id', $id, PDO::PARAM_INT); return $stm->execute(); } function dbDeviceUpdate($id=NULL,$name=NULL,$ip=NULL,$version=NULL,$password=NULL,$mac=NULL,$type=NULL) { global $db_handle; $versioncond=''; if(isset($version)) $versioncond='version = :version, '; $maccond=''; if(isset($mac)) $maccond='mac = :mac, '; $typecond=''; if(isset($type)) $typecond='type = :type, '; $namecond=''; if(isset($name)) $namecond='name = :name, '; $ipcond=''; if(isset($ip)) $ipcond='ip = :ip, '; $passwordcond=''; if(isset($password)) $passwordcond='password = :password '; if(isset($id)) { $stm = $db_handle->prepare('UPDATE devices SET '.$versioncond.$ipcond.$namecond.$maccond.$typecond.$passwordcond.' WHERE id = :id'); #echo "\r\n<!-- Doing id update \r\n".'UPDATE devices SET '.$versioncond.$maccond.$namecond.$typecond.$passwordcond." WHERE id = $id -->\r\n"; } else if(isset($mac) && isset($ip)) { $stm = $db_handle->prepare('UPDATE devices SET '.$versioncond.$ipcond.$namecond.$maccond.$typecond.$passwordcond.' WHERE (mac = :mac ) or (ip = :ip and mac="")'); # } else if(isset($ip)) { # $stm = $db_handle->prepare('UPDATE devices SET '.$versioncond.$maccond.$namecond.$passwordcond.' WHERE ip = :ip AND mac=""'); #echo "\r\n<!-- Doing mac update \r\n".'UPDATE devices SET '.$versioncond.$maccond.$namecond.$passwordcond." WHERE ip = $ip AND mac=$mac -->\r\n"; } if(isset($stm)) { if(isset($version)) $stm->bindValue(':version', $version, PDO::PARAM_STR); if(isset($password)) $stm->bindValue(':password', $password, PDO::PARAM_STR); if(isset($mac)) $stm->bindValue(':mac', $mac, PDO::PARAM_STR); if(isset($type)) $stm->bindValue(':type', $type, PDO::PARAM_INT); if(isset($name)) $stm->bindValue(':name', $name, PDO::PARAM_STR); if(isset($ip)) $stm->bindValue(':ip', $ip, PDO::PARAM_STR); if(isset($id)) $stm->bindValue(':id', $id, PDO::PARAM_INT); return $stm->execute(); } return false; } function dbDeviceBackups($id,$date=NULL,$version=NULL,$name=NULL,$mac=NULL,$type=NULL) { global $db_handle; $count = dbBackupCount($id); $versioncond=''; if(isset($version)) $versioncond='version = :version, '; $maccond=''; if(isset($mac)) $maccond='mac = :mac, '; $typecond=''; if(isset($type)) $typecond='type = :type, '; $namecond=''; if(isset($name)) $namecond='name = :name, '; $datecond=''; if(isset($date)) $datecond='lastbackup = :date, '; $stm = $db_handle->prepare("UPDATE devices SET ".$versioncond.$datecond.$namecond.$maccond.$typecond.' noofbackups = :noofbackups WHERE id = :id'); if(isset($version)) $stm->bindValue(':version', $version, PDO::PARAM_STR); if(isset($mac)) $stm->bindValue(':mac', $mac, PDO::PARAM_STR); if(isset($type)) $stm->bindValue(':type', $type, PDO::PARAM_INT); if(isset($name)) $stm->bindValue(':name', $name, PDO::PARAM_STR); if(isset($date)) $stm->bindValue(':date', $date, PDO::PARAM_STR); $stm->bindValue(':noofbackups', $count, PDO::PARAM_STR); $stm->bindValue(':id', $id, PDO::PARAM_INT); return $stm->execute(); } function dbNewBackup($id, $name, $version, $date, $noofbackups, $filename, $mac=NULL, $type=NULL) { global $db_handle; if(!isset($version) || strlen($version)<2) { $version='Unknown'; } $stm = $db_handle->prepare("INSERT INTO backups(deviceid,name,version,date,filename) VALUES(:deviceid, :name, :version, :date, :filename)"); $stm->bindValue(':deviceid', $id, PDO::PARAM_INT); $stm->bindValue(':name', $name, PDO::PARAM_STR); $stm->bindValue(':version', $version, PDO::PARAM_STR); $stm->bindValue(':date', $date, PDO::PARAM_STR); $stm->bindValue(':filename', $filename, PDO::PARAM_STR); if (!$stm->execute()) { trigger_error("insert error: ".$stm->errorInfo()[2], E_USER_NOTICE); return false; } return dbDeviceBackups($id,$date,$version,$name,$mac,$type); }
php
MIT
ff65d7aeade785f40b50f91351f7786592ea5d2d
2026-01-05T04:48:49.060847Z
false
danmed/TasmoBackupV1
https://github.com/danmed/TasmoBackupV1/blob/ff65d7aeade785f40b50f91351f7786592ea5d2d/lib/phpMQTT2.php
lib/phpMQTT2.php
<?php /* phpMQTT A simple php class to connect/publish/subscribe to an MQTT broker */ /* Licence Copyright (c) 2010 Blue Rhinos Consulting | Andrew Milsted andrew@bluerhinos.co.uk | http://www.bluerhinos.co.uk Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* phpMQTT */ class phpMQTT { protected $socket; /* holds the socket */ protected $msgid = 1; /* counter for message id */ public $keepalive = 10; /* default keepalive timmer */ public $timesinceping; /* host unix time, used to detect disconects */ public $topics = []; /* used to store currently subscribed topics */ public $debug = false; /* should output debug messages */ public $address; /* broker address */ public $port; /* broker port */ public $clientid; /* client id sent to brocker */ public $will; /* stores the will of the client */ protected $username; /* stores username */ protected $password; /* stores password */ public $cafile; protected static $known_commands = [ 1 => 'CONNECT', 2 => 'CONNACK', 3 => 'PUBLISH', 4 => 'PUBACK', 5 => 'PUBREC', 6 => 'PUBREL', 7 => 'PUBCOMP', 8 => 'SUBSCRIBE', 9 => 'SUBACK', 10 => 'UNSUBSCRIBE', 11 => 'UNSUBACK', 12 => 'PINGREQ', 13 => 'PINGRESP', 14 => 'DISCONNECT' ]; /** * phpMQTT constructor. * * @param $address * @param $port * @param $clientid * @param null $cafile */ public function __construct($address, $port, $clientid, $cafile = null) { $this->broker($address, $port, $clientid, $cafile); } /** * Sets the broker details * * @param $address * @param $port * @param $clientid * @param null $cafile */ public function broker($address, $port, $clientid, $cafile = null) { $this->address = $address; $this->port = $port; $this->clientid = $clientid; $this->cafile = $cafile; } /** * Will try and connect, if fails it will sleep 10s and try again, this will enable the script to recover from a network outage * * @param bool $clean - should the client send a clean session flag * @param null $will * @param null $username * @param null $password * * @return bool */ public function connect_auto($clean = true, $will = null, $username = null, $password = null) { while ($this->connect($clean, $will, $username, $password) === false) { sleep(10); } return true; } /** * @param bool $clean - should the client send a clean session flag * @param null $will * @param null $username * @param null $password * * @return bool */ public function connect($clean = true, $will = null, $username = null, $password = null) { if ($will) { $this->will = $will; } if ($username) { $this->username = $username; } if ($password) { $this->password = $password; } if ($this->cafile) { $socketContext = stream_context_create( [ 'ssl' => [ 'verify_peer_name' => true, 'cafile' => $this->cafile ] ] ); $this->socket = stream_socket_client('tls://' . $this->address . ':' . $this->port, $errno, $errstr, 60, STREAM_CLIENT_CONNECT, $socketContext); } else { $this->socket = stream_socket_client('tcp://' . $this->address . ':' . $this->port, $errno, $errstr, 60, STREAM_CLIENT_CONNECT); } if (!$this->socket) { $this->_errorMessage("stream_socket_create() $errno, $errstr"); return false; } stream_set_timeout($this->socket, 5); stream_set_blocking($this->socket, 0); $i = 0; $buffer = ''; $buffer .= chr(0x00); $i++; // Length MSB $buffer .= chr(0x04); $i++; // Length LSB $buffer .= chr(0x4d); $i++; // M $buffer .= chr(0x51); $i++; // Q $buffer .= chr(0x54); $i++; // T $buffer .= chr(0x54); $i++; // T $buffer .= chr(0x04); $i++; // // Protocol Level //No Will $var = 0; if ($clean) { $var += 2; } //Add will info to header if ($this->will !== null) { $var += 4; // Set will flag $var += ($this->will['qos'] << 3); //Set will qos if ($this->will['retain']) { $var += 32; } //Set will retain } if ($this->username !== null) { $var += 128; } //Add username to header if ($this->password !== null) { $var += 64; } //Add password to header $buffer .= chr($var); $i++; //Keep alive $buffer .= chr($this->keepalive >> 8); $i++; $buffer .= chr($this->keepalive & 0xff); $i++; $buffer .= $this->strwritestring($this->clientid, $i); //Adding will to payload if ($this->will !== null) { $buffer .= $this->strwritestring($this->will['topic'], $i); $buffer .= $this->strwritestring($this->will['content'], $i); } if ($this->username !== null) { $buffer .= $this->strwritestring($this->username, $i); } if ($this->password !== null) { $buffer .= $this->strwritestring($this->password, $i); } $head = chr(0x10); while ($i > 0) { $encodedByte = $i % 128; $i /= 128; $i = (int)$i; if ($i > 0) { $encodedByte |= 128; } $head .= chr($encodedByte); } fwrite($this->socket, $head, 2); fwrite($this->socket, $buffer); $string = $this->read(4); if (ord($string[0]) >> 4 === 2 && $string[3] === chr(0)) { $this->_debugMessage('Connected to Broker'); } else { $this->_errorMessage( sprintf( "Connection failed! (Error: 0x%02x 0x%02x)\n", ord($string[0]), ord($string[3]) ) ); return false; } $this->timesinceping = time(); return true; } /** * Reads in so many bytes * * @param int $int * @param bool $nb * * @return false|string */ public function read($int = 8192, $nb = false) { $string = ''; $togo = $int; if ($nb) { return fread($this->socket, $togo); } while (!feof($this->socket) && $togo > 0) { $fread = fread($this->socket, $togo); $string .= $fread; $togo = $int - strlen($string); } return $string; } /** * Subscribes to a topic, wait for message and return it * * @param $topic * @param $qos * * @return string */ public function subscribeAndWaitForMessage($topic, $qos) { $this->subscribe( [ $topic => [ 'qos' => $qos, 'function' => '__direct_return_message__' ] ] ); do { $return = $this->proc(); } while ($return === true); return $return; } /** * subscribes to topics * * @param $topics * @param int $qos */ public function subscribe($topics, $qos = 0) { $i = 0; $buffer = ''; $id = $this->msgid; $buffer .= chr($id >> 8); $i++; $buffer .= chr($id % 256); $i++; foreach ($topics as $key => $topic) { $buffer .= $this->strwritestring($key, $i); $buffer .= chr($topic['qos']); $i++; $this->topics[$key] = $topic; } $cmd = 0x82; //$qos $cmd += ($qos << 1); $head = chr($cmd); $head .= $this->setmsglength($i); fwrite($this->socket, $head, strlen($head)); $this->_fwrite($buffer); $string = $this->read(2); $bytes = ord(substr($string, 1, 1)); $this->read($bytes); } /** * Sends a keep alive ping */ public function ping() { $head = chr(0xc0); $head .= chr(0x00); fwrite($this->socket, $head, 2); $this->timesinceping = time(); $this->_debugMessage('ping sent'); } /** * sends a proper disconnect cmd */ public function disconnect() { $head = ' '; $head[0] = chr(0xe0); $head[1] = chr(0x00); fwrite($this->socket, $head, 2); } /** * Sends a proper disconnect, then closes the socket */ public function close() { $this->disconnect(); stream_socket_shutdown($this->socket, STREAM_SHUT_WR); } /** * Publishes $content on a $topic * * @param $topic * @param $content * @param int $qos * @param bool $retain */ public function publish($topic, $content, $qos = 0, $retain = false) { $i = 0; $buffer = ''; $buffer .= $this->strwritestring($topic, $i); if ($qos) { $id = $this->msgid++; $buffer .= chr($id >> 8); $i++; $buffer .= chr($id % 256); $i++; } $buffer .= $content; $i += strlen($content); $head = ' '; $cmd = 0x30; if ($qos) { $cmd += $qos << 1; } if (empty($retain) === false) { ++$cmd; } $head[0] = chr($cmd); $head .= $this->setmsglength($i); fwrite($this->socket, $head, strlen($head)); $this->_fwrite($buffer); } /** * Writes a string to the socket * * @param $buffer * * @return bool|int */ protected function _fwrite($buffer) { $buffer_length = strlen($buffer); for ($written = 0; $written < $buffer_length; $written += $fwrite) { $fwrite = fwrite($this->socket, substr($buffer, $written)); if ($fwrite === false) { return false; } } return $buffer_length; } /** * Processes a received topic * * @param $msg * * @retrun bool|string */ public function message($msg) { $tlen = (ord($msg[0]) << 8) + ord($msg[1]); $topic = substr($msg, 2, $tlen); $msg = substr($msg, ($tlen + 2)); $found = false; foreach ($this->topics as $key => $top) { if (preg_match( '/^' . str_replace( '#', '.*', str_replace( '+', "[^\/]*", str_replace( '/', "\/", str_replace( '$', '\$', $key ) ) ) ) . '$/', $topic )) { if ($top['function'] === '__direct_return_message__') { return $msg; } if (is_callable($top['function'])) { call_user_func($top['function'], $topic, $msg); } else { $this->_errorMessage('Message received on topic ' . $topic. ' but function is not callable.'); } $found = true; } } if ($found === false) { $this->_debugMessage('msg received but no match in subscriptions'); } else { $this->_debugMessage('msg received that matched a subscribed topic'); } return $found; } /** * The processing loop for an "always on" client * set true when you are doing other stuff in the loop good for * watching something else at the same time * * @param bool $loop * * @return bool | string */ public function proc(bool $loop = true) { if (feof($this->socket)) { $this->_debugMessage('eof receive going to reconnect for good measure'); fclose($this->socket); $this->connect_auto(false); if (count($this->topics)) { $this->subscribe($this->topics); } } $byte = $this->read(1, true); if ((string)$byte === '') { if ($loop === true) { usleep(100000); } } else { $cmd = (int)(ord($byte) / 16); $this->_debugMessage( sprintf( 'Received CMD: %d (%s)', $cmd, isset(static::$known_commands[$cmd]) === true ? static::$known_commands[$cmd] : 'Unknown' ) ); $multiplier = 1; $value = 0; do { $digit = ord($this->read(1)); $value += ($digit & 127) * $multiplier; $multiplier *= 128; } while (($digit & 128) !== 0); $this->_debugMessage('Fetching: ' . $value . ' bytes'); $string = $value > 0 ? $this->read($value) : ''; if ($cmd) { switch ($cmd) { case 3: //Publish MSG $return = $this->message($string); if (is_bool($return) === false) { return $return; } break; } } } if ($this->timesinceping < (time() - $this->keepalive)) { $this->_debugMessage('not had something in a while so ping'); $this->ping(); } if ($this->timesinceping < (time() - ($this->keepalive * 2))) { $this->_debugMessage('not seen a packet in a while, disconnecting/reconnecting'); fclose($this->socket); $this->connect_auto(false); if (count($this->topics)) { $this->subscribe($this->topics); } } return true; } /** * Gets the length of a msg, (and increments $i) * * @param $msg * @param $i * * @return float|int */ protected function getmsglength(&$msg, &$i) { $multiplier = 1; $value = 0; do { $digit = ord($msg[$i]); $value += ($digit & 127) * $multiplier; $multiplier *= 128; $i++; } while (($digit & 128) !== 0); return $value; } /** * @param $len * * @return string */ protected function setmsglength($len) { $string = ''; do { $digit = $len % 128; $len >>= 7; // if there are more digits to encode, set the top bit of this digit if ($len > 0) { $digit |= 0x80; } $string .= chr($digit); } while ($len > 0); return $string; } /** * @param $str * @param $i * * @return string */ protected function strwritestring($str, &$i) { $len = strlen($str); $msb = $len >> 8; $lsb = $len % 256; $ret = chr($msb); $ret .= chr($lsb); $ret .= $str; $i += ($len + 2); return $ret; } /** * Prints a sting out character by character * * @param $string */ public function printstr($string) { $strlen = strlen($string); for ($j = 0; $j < $strlen; $j++) { $num = ord($string[$j]); if ($num > 31) { $chr = $string[$j]; } else { $chr = ' '; } printf("%4d: %08b : 0x%02x : %s \n", $j, $num, $num, $chr); } } /** * @param string $message */ protected function _debugMessage(string $message) { if ($this->debug === true) { echo date('r: ') . $message . PHP_EOL; } } /** * @param string $message */ protected function _errorMessage(string $message) { error_log('Error:' . $message); } }
php
MIT
ff65d7aeade785f40b50f91351f7786592ea5d2d
2026-01-05T04:48:49.060847Z
false
danmed/TasmoBackupV1
https://github.com/danmed/TasmoBackupV1/blob/ff65d7aeade785f40b50f91351f7786592ea5d2d/lib/phpMQTT.php
lib/phpMQTT.php
<?php /* phpMQTT A simple php class to connect/publish/subscribe to an MQTT broker */ /* Licence Copyright (c) 2010 Blue Rhinos Consulting | Andrew Milsted andrew@bluerhinos.co.uk | http://www.bluerhinos.co.uk Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* phpMQTT */ class phpMQTT { private $socket; /* holds the socket */ private $msgid = 1; /* counter for message id */ public $keepalive = 10; /* default keepalive timmer */ public $timesinceping; /* host unix time, used to detect disconects */ public $topics = array(); /* used to store currently subscribed topics */ public $debug = false; /* should output debug messages */ public $address; /* broker address */ public $port; /* broker port */ public $clientid; /* client id sent to brocker */ public $will; /* stores the will of the client */ private $username; /* stores username */ private $password; /* stores password */ public $cafile; function __construct($address, $port, $clientid, $cafile = NULL){ $this->broker($address, $port, $clientid, $cafile); } /* sets the broker details */ function broker($address, $port, $clientid, $cafile = NULL){ $this->address = $address; $this->port = $port; $this->clientid = $clientid; $this->cafile = $cafile; } function connect_auto($clean = true, $will = NULL, $username = NULL, $password = NULL){ while($this->connect($clean, $will, $username, $password)==false){ sleep(10); } return true; } /* connects to the broker inputs: $clean: should the client send a clean session flag */ function connect($clean = true, $will = NULL, $username = NULL, $password = NULL){ if($will) $this->will = $will; if($username) $this->username = $username; if($password) $this->password = $password; if ($this->cafile) { $socketContext = stream_context_create(["ssl" => [ "verify_peer_name" => true, "cafile" => $this->cafile ]]); $this->socket = stream_socket_client("tls://" . $this->address . ":" . $this->port, $errno, $errstr, 60, STREAM_CLIENT_CONNECT, $socketContext); } else { $this->socket = stream_socket_client("tcp://" . $this->address . ":" . $this->port, $errno, $errstr, 60, STREAM_CLIENT_CONNECT); } if (!$this->socket ) { if($this->debug) error_log("stream_socket_create() $errno, $errstr \n"); return false; } stream_set_timeout($this->socket, 5); stream_set_blocking($this->socket, 0); $i = 0; $buffer = ""; $buffer .= chr(0x00); $i++; $buffer .= chr(0x06); $i++; $buffer .= chr(0x4d); $i++; $buffer .= chr(0x51); $i++; $buffer .= chr(0x49); $i++; $buffer .= chr(0x73); $i++; $buffer .= chr(0x64); $i++; $buffer .= chr(0x70); $i++; $buffer .= chr(0x03); $i++; //No Will $var = 0; if($clean) $var+=2; //Add will info to header if($this->will != NULL){ $var += 4; // Set will flag $var += ($this->will['qos'] << 3); //Set will qos if($this->will['retain']) $var += 32; //Set will retain } if($this->username != NULL) $var += 128; //Add username to header if($this->password != NULL) $var += 64; //Add password to header $buffer .= chr($var); $i++; //Keep alive $buffer .= chr($this->keepalive >> 8); $i++; $buffer .= chr($this->keepalive & 0xff); $i++; $buffer .= $this->strwritestring($this->clientid,$i); //Adding will to payload if($this->will != NULL){ $buffer .= $this->strwritestring($this->will['topic'],$i); $buffer .= $this->strwritestring($this->will['content'],$i); } if($this->username) $buffer .= $this->strwritestring($this->username,$i); if($this->password) $buffer .= $this->strwritestring($this->password,$i); $head = " "; $head[0] = chr(0x10); $head[1] = chr($i); fwrite($this->socket, $head, 2); fwrite($this->socket, $buffer); $string = $this->read(4); if(ord($string[0])>>4 == 2 && $string[3] == chr(0)){ if($this->debug) echo "Connected to Broker\n"; }else{ error_log(sprintf("Connection failed! (Error: 0x%02x 0x%02x)\n", ord($string[0]),ord($string[3]))); return false; } $this->timesinceping = time(); return true; } /* read: reads in so many bytes */ function read($int = 8192, $nb = false){ // print_r(socket_get_status($this->socket)); $string=""; $togo = $int; if($nb){ return fread($this->socket, $togo); } while (!feof($this->socket) && $togo>0) { $fread = fread($this->socket, $togo); $string .= $fread; $togo = $int - strlen($string); } return $string; } /* subscribe: subscribes to topics */ function subscribe($topics, $qos = 0){ $i = 0; $buffer = ""; $id = $this->msgid; $buffer .= chr($id >> 8); $i++; $buffer .= chr($id % 256); $i++; foreach($topics as $key => $topic){ $buffer .= $this->strwritestring($key,$i); $buffer .= chr($topic["qos"]); $i++; $this->topics[$key] = $topic; } $cmd = 0x80; //$qos $cmd += ($qos << 1); $head = chr($cmd); $head .= chr($i); fwrite($this->socket, $head, 2); fwrite($this->socket, $buffer, $i); $string = $this->read(2); $bytes = ord(substr($string,1,1)); $string = $this->read($bytes); } /* ping: sends a keep alive ping */ function ping(){ $head = " "; $head = chr(0xc0); $head .= chr(0x00); fwrite($this->socket, $head, 2); if($this->debug) echo "ping sent\n"; } /* disconnect: sends a proper disconect cmd */ function disconnect(){ $head = " "; $head[0] = chr(0xe0); $head[1] = chr(0x00); fwrite($this->socket, $head, 2); } /* close: sends a proper disconect, then closes the socket */ function close(){ $this->disconnect(); stream_socket_shutdown($this->socket, STREAM_SHUT_WR); } /* publish: publishes $content on a $topic */ function publish($topic, $content, $qos = 0, $retain = 0){ $i = 0; $buffer = ""; $buffer .= $this->strwritestring($topic,$i); //$buffer .= $this->strwritestring($content,$i); if($qos){ $id = $this->msgid++; $buffer .= chr($id >> 8); $i++; $buffer .= chr($id % 256); $i++; } $buffer .= $content; $i+=strlen($content); $head = " "; $cmd = 0x30; if($qos) $cmd += $qos << 1; if($retain) $cmd += 1; $head[0] = chr($cmd); $head .= $this->setmsglength($i); fwrite($this->socket, $head, strlen($head)); fwrite($this->socket, $buffer, $i); } /* message: processes a recieved topic */ function message($msg){ $tlen = (ord($msg[0])<<8) + ord($msg[1]); $topic = substr($msg,2,$tlen); $msg = substr($msg,($tlen+2)); $found = 0; foreach($this->topics as $key=>$top){ if( preg_match("/^".str_replace("#",".*", str_replace("+","[^\/]*", str_replace("/","\/", str_replace("$",'\$', $key))))."$/",$topic) ){ if(is_callable($top['function'])){ call_user_func($top['function'],$topic,$msg); $found = 1; } } } if($this->debug && !$found) echo "msg recieved but no match in subscriptions\n"; } /* proc: the processing loop for an "allways on" client set true when you are doing other stuff in the loop good for watching something else at the same time */ function proc( $loop = true){ if(1){ $sockets = array($this->socket); $w = $e = NULL; $cmd = 0; //$byte = fgetc($this->socket); if(feof($this->socket)){ if($this->debug) echo "eof receive going to reconnect for good measure\n"; fclose($this->socket); $this->connect_auto(false); if(count($this->topics)) $this->subscribe($this->topics); } $byte = $this->read(1, true); if(!strlen($byte)){ if($loop){ usleep(100000); return true; } else return false; }else{ $cmd = (int)(ord($byte)/16); if($this->debug) echo "Recevid: $cmd\n"; $multiplier = 1; $value = 0; do{ $digit = ord($this->read(1)); $value += ($digit & 127) * $multiplier; $multiplier *= 128; }while (($digit & 128) != 0); if($this->debug) echo "Fetching: $value\n"; if($value) $string = $this->read($value); if($cmd){ switch($cmd){ case 3: $this->message($string); break; } $this->timesinceping = time(); } } if($this->timesinceping < (time() - $this->keepalive )){ if($this->debug) echo "not found something so ping\n"; $this->ping(); } if($this->timesinceping<(time()-($this->keepalive*2))){ if($this->debug) echo "not seen a package in a while, disconnecting\n"; fclose($this->socket); $this->connect_auto(false); if(count($this->topics)) $this->subscribe($this->topics); } return true; } return false; } /* getmsglength: */ function getmsglength(&$msg, &$i){ $multiplier = 1; $value = 0 ; do{ $digit = ord($msg[$i]); $value += ($digit & 127) * $multiplier; $multiplier *= 128; $i++; }while (($digit & 128) != 0); return $value; } /* setmsglength: */ function setmsglength($len){ $string = ""; do{ $digit = $len % 128; $len = $len >> 7; // if there are more digits to encode, set the top bit of this digit if ( $len > 0 ) $digit = ($digit | 0x80); $string .= chr($digit); }while ( $len > 0 ); return $string; } /* strwritestring: writes a string to a buffer */ function strwritestring($str, &$i){ $ret = " "; $len = strlen($str); $msb = $len >> 8; $lsb = $len % 256; $ret = chr($msb); $ret .= chr($lsb); $ret .= $str; $i += ($len+2); return $ret; } function printstr($string){ $strlen = strlen($string); for($j=0;$j<$strlen;$j++){ $num = ord($string[$j]); if($num > 31) $chr = $string[$]}; else $chr = " "; printf("%4d: %08b : 0x%02x : %s \n",$j,$num,$num,$chr); } } }
php
MIT
ff65d7aeade785f40b50f91351f7786592ea5d2d
2026-01-05T04:48:49.060847Z
false
danmed/TasmoBackupV1
https://github.com/danmed/TasmoBackupV1/blob/ff65d7aeade785f40b50f91351f7786592ea5d2d/lib/mqtt.inc.php
lib/mqtt.inc.php
<?php require_once(__DIR__.'/phpMQTT2.php'); GLOBAL $mqtt_found; $mqtt_found=[]; function setupMQTT($server, $port=1883, $user, $password) { $mqtt = new phpMQTT($server, $port, 'TasmoBackup'); //$mqtt = new Bluerhinos\phpMQTT($server, $port, 'TasmoBackup'); if(!$mqtt->connect(true, NULL, $user, $password)) return false; return $mqtt; } function getTasmotaMQTTScan($mqtt,$topic,$user=false,$password=false,$slim=false) { GLOBAL $mqtt_found,$settings; $topics['+/stat/STATUS'] = array('qos' => 0, 'function' => 'collectMQTTStatus'); $topics['+/stat/STATUS2'] = array('qos' => 0, 'function' => 'collectMQTTStatus2'); $topics['+/stat/STATUS5'] = array('qos' => 0, 'function' => 'collectMQTTStatus5'); $topics['stat/+/STATUS'] = array('qos' => 0, 'function' => 'collectMQTTStatus'); $topics['stat/+/STATUS2'] = array('qos' => 0, 'function' => 'collectMQTTStatus2'); $topics['stat/+/STATUS5'] = array('qos' => 0, 'function' => 'collectMQTTStatus5'); if(isset($settings['mqtt_topic_format'])) { $custom_topic=str_replace(array('%prefix%','%topic%'),array('stat','+'),$settings['mqtt_topic_format']); $topics[$custom_topic.'/STATUS'] = array('qos' => 0, 'function' => 'collectMQTTStatus'); $topics[$custom_topic.'/STATUS2'] = array('qos' => 0, 'function' => 'collectMQTTStatus2'); $topics[$custom_topic.'/STATUS5'] = array('qos' => 0, 'function' => 'collectMQTTStatus5'); } $mqtt->subscribe($topics); $step1=$step2=$step3=$step4=$step5=$step6=true; $ts=time(); while(($i=time()-$ts)<10) { if($step1 && !$slim) { $step1=false; // HomeAssistant swapped $mqtt->publish($topic.'/cmnd/STATUS','0'); if($topic=='tasmotas') $mqtt->publish('sonoffs/cmnd/STATUS','0'); } if($step2 && $i>0.60 && !$slim) { $step2=false; if(isset($settings['mqtt_topic_format'])) { $mqtt->publish(str_replace(array('%prefix%','%topic%'),array('stat',$topic),$settings['mqtt_topic_format']).'/STATUS','0'); if($topic=='tasmotas') $mqtt->publish(str_replace(array('%prefix%','%topic%'),array('stat','sonoffs'),$settings['mqtt_topic_format']).'/STATUS','0'); } } if($step3 && $i>1.10 && !$slim) { $step3=false; $mqtt->publish('cmnd/'.$topic.'/STATUS','0'); if($topic=='tasmotas') $mqtt->publish('cmnd/sonoffs/STATUS','0'); } if($step4 && $i>2.10) { $step4=false; // Default $mqtt->publish($topic.'/cmnd/STATUS','5'); if($topic=='tasmotas') $mqtt->publish('sonoffs/cmnd/STATUS','5'); } if($step5 && $i>2.60) { $step5=false; if(isset($settings['mqtt_topic_format'])) { $mqtt->publish(str_replace(array('%prefix%','%topic%'),array('stat',$topic),$settings['mqtt_topic_format']).'/STATUS','5'); if($topic=='tasmotas') $mqtt->publish(str_replace(array('%prefix%','%topic%'),array('stat','sonoffs'),$settings['mqtt_topic_format']).'/STATUS','5'); } } if($step6 && $i>3.20) { $step6=false; $mqtt->publish('cmnd/'.$topic.'/STATUS','5'); if($topic=='tasmotas') $mqtt->publish('cmnd/sonoffs/STATUS','5'); } $mqtt->proc(false); usleep(30000); } $results=[]; foreach($mqtt_found as $topic => $found) { $status=array('Topic'=>$topic); if(isset($found['status5'])) { $status=array_merge(jsonTasmotaDecode($found['status5'])); if(isset($status['StatusNET']['IP'])) // < 5.12.0 $tmp['ip']=$status['StatusNET']['IP']; if(isset($status['StatusNET']['IPAddress'])) // >= 5.12.0 $tmp['ip']=$status['StatusNET']['IPAddress']; if(isset($status['StatusNET']['Mac'])) $tmp['mac']=$status['StatusNET']['Mac']; if(isset($found['status'])) { $status=array_merge($status,jsonTasmotaDecode($found['status'])); if(isset($settings['use_topic_as_name']) && $settings['use_topic_as_name']=='F') $tmp['name']=trim(str_replace(array('/stat','stat/'),array('',''),$topic)," \t\r\n\v\0/"); else { if (isset($status['Status']['Topic'])) $tmp['name']=$status['Status']['Topic']; } if(!isset($settings['use_topic_as_name']) || $settings['use_topic_as_name']=='N') { if (isset($status['Status']['DeviceName']) && strlen(preg_replace('/\s+/', '',$status['Status']['DeviceName']))>0) $tmp['name']=$status['Status']['DeviceName']; else if (isset($status['Status']['FriendlyName'][0])) $tmp['name']=$status['Status']['FriendlyName'][0]; } } if(isset($found['status2'])) { $status=array_merge($status,jsonTasmotaDecode($found['status2'])); } if (isset($settings['autoadd_scan']) && $settings['autoadd_scan']=='Y') { addTasmotaDevice($tmp['ip'], $user, $password,false,$status); } else { $results[]=$tmp; } } } return $results; } function collectMQTTStatus($topic, $msg) { GLOBAL $mqtt_found; //Get Name $name=false; if(isset($topic)) $name=substr($topic,0,strrpos($topic,'/')); if($name) { $mqtt_found[$name]['status']=$msg; } return; } function collectMQTTStatus2($topic, $msg) { GLOBAL $mqtt_found; //Get Version $name=false; if(isset($topic)) $name=substr($topic,0,strrpos($topic,'/')); if($name) { $mqtt_found[$name]['status2']=$msg; } return; } function collectMQTTStatus5($topic, $msg) { GLOBAL $mqtt_found; //Get IP $name=false; if(isset($topic)) $name=substr($topic,0,strrpos($topic,'/')); if($name) { $mqtt_found[$name]['status5']=$msg; } return; }
php
MIT
ff65d7aeade785f40b50f91351f7786592ea5d2d
2026-01-05T04:48:49.060847Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/src/BIP32.php
src/BIP32.php
<?php namespace BitWasp\BitcoinLib; use Mdanter\Ecc\EccFactory; /** * BIP32 * * This library contains function which implement BIP32. * More information on this implementation can be found here: * https://github.com/sipa/bips/blob/bip32update/bip-0032.mediawiki * The library supports Bitcoin and Dogecoin mainnet/testnet keys. * * - Master keys can be generated from a hex seed. * - A child key derivation function is defined which when supplied with * a parent extended key and a tuple of address bytes, a 32bit number * treated as a hex string. * - A function to generate the tuple of address bytes given a parent * extended key and a string describing the desired definition. * - A master function used to derive an extended key from a parent * extended key and a string describing the desired definition. * - A master function used to derive an address given an extended key * and a string describing the desired definition. * - A function to encode an array of the key's properties as base58check * encoded key. * - A function to decode a base58check encoded key into an array of * properties. * - A function to convert an extended key to it's address. * - A function to convert an extended private to public key. * - A function which takes an extended keys magic bytes and returns an * array of information, if it's supported. * - A function to calculate the address bytes for a given number, and * if the number is to have the MSB set. * - A function to check if the address bytes calls for a prime derivation. * - A function which checks if the generated private key, given as a * hex string, is a valid private key. * - A function to extract the decimal number encoded in the hex bytes. * * Thomas Kerin */ class BIP32 { // Bitcoin public static $bitcoin_mainnet_public = '0488b21e'; public static $bitcoin_mainnet_private = '0488ade4'; public static $bitcoin_mainnet_version = '00'; public static $bitcoin_testnet_public = '043587cf'; public static $bitcoin_testnet_private = '04358394'; public static $bitcoin_testnet_version = '6f'; // Dogecoin public static $dogecoin_mainnet_public = '02facafd'; public static $dogecoin_mainnet_private = '02fac398'; public static $dogecoin_mainnet_version = '1e'; public static $dogecoin_testnet_public = '0432a9a8'; public static $dogecoin_testnet_private = '0432a243'; public static $dogecoin_testnet_version = '71'; // Litecoin public static $litecoin_mainnet_public = '019da462'; public static $litecoin_mainnet_private = '019d9cfe'; public static $litecoin_mainnet_version = '30'; public static $litecoin_testnet_public = '0436f6e1'; public static $litecoin_testnet_private = '0436ef7d'; public static $litecoin_testnet_version = '6f'; /** * Master Key * * This function accepts a hex string as a $seed, and allows you to * select which network/coin you want to generate, as well as testnet * extended keys. * * Returns false if the key is invalid, or 'm' - the extended master private key. * * @param string $seed * @param string $network * @param boolean $testnet * @param boolean $ignoreLengthCheck disable the length checks * @return string */ public static function master_key($seed, $network = 'bitcoin', $testnet = false, $ignoreLengthCheck = false) { $seed = pack("H*", $seed); // seed min length is 128 bits (16 bytes) if (!$ignoreLengthCheck && strlen($seed) < 16) { throw new \InvalidArgumentException("Seed should be at least 128 bits'"); } // seed max length is 512 bits (64 bytes) if (!$ignoreLengthCheck && strlen($seed) > 64) { throw new \InvalidArgumentException("Seed should be at most 512 bits'"); } // Generate HMAC hash, and the key/chaincode. $I = hash_hmac('sha512', $seed, "Bitcoin seed"); $I_l = substr($I, 0, 64); $I_r = substr($I, 64, 64); // Error checking! if (self::check_valid_hmac_key($I_l) == false) { throw new \InvalidArgumentException("Seed results in invalid key"); } $data = array( 'network' => $network, 'testnet' => $testnet, 'type' => 'private', 'depth' => '0', 'fingerprint' => '00000000', 'i' => '00000000', 'chain_code' => $I_r, 'key' => $I_l, ); return array(self::encode($data), 'm'); } /** * CKD * * This recursive function accepts $master, a parent extended key, * and an array of address bytes (the $address_definition tuple). It * pop's the next value from the $address_definition tuple and * generates the desired key. If the $address_definition tuple is * empty, then it returns the key. If not, then it calls itself again * with the new key and the tuple with the remaining key indexes to * generate, but will terminate with an array containing the desired * key at index 0, and it's human readable definition in the second. * * @param string $master * @param array $address_definition * @param array $generated (internal, should never be set in your code) * @return array */ public static function CKD($master, $address_definition, $generated = array()) { $previous = self::import($master); if ($previous['type'] == 'private') { $private_key = $previous['key']; $public_key = null; } else { $private_key = null; $public_key = $previous['key']; } $i = array_pop($address_definition); $is_prime = self::check_is_prime_hex($i); if ($is_prime == 1) { if ($previous['type'] == 'public') { throw new \InvalidArgumentException("Can't derive private key from public key"); } $data = '00' . $private_key . $i; } else { $public_key = $public_key ?: BitcoinLib::private_key_to_public_key($private_key, true); $data = $public_key . $i; } /* * optimization; * if this isn't the last derivation then the fingerprint is irrelevant so we can just spoof it! * that way we don't need the public key for the fingerprint */ if (empty($address_definition)) { $public_key = $public_key ?: BitcoinLib::private_key_to_public_key($private_key, true); $fingerprint = substr(hash('ripemd160', hash('sha256', pack("H*", $public_key), true)), 0, 8); } else { $fingerprint = "FFFFFFFF"; } $I = hash_hmac('sha512', pack("H*", $data), pack("H*", $previous['chain_code'])); $I_l = substr($I, 0, 64); $I_r = substr($I, 64, 64); if (self::check_valid_hmac_key($I_l) == false) { // Check the key is in a valid range. // calculate the next i in the sequence, and start over with that. $new_i = self::calc_address_bytes(self::get_address_number($i) + 1, $is_prime); array_push($address_definition, $new_i); return self::CKD($master, $address_definition, $generated); } // Keep a record of the address being built. Done after error // checking so only valid keys get to this point. if (count($generated) == 0 && $previous['depth'] == 0) { array_push($generated, (($previous['type'] == 'private') ? 'm' : 'M')); } array_push($generated, (self::get_address_number($i, $is_prime) . (($is_prime == 1) ? "'" : null))); $math = EccFactory::getAdapter(); $g = EccFactory::getSecgCurves($math)->generator256k1(); $n = $g->getOrder(); $Il_dec = $math->hexDec($I_l); if ($previous['type'] == 'private') { $private_key_dec = $math->hexDec($private_key); $key_dec = $math->mod($math->add($Il_dec, $private_key_dec), $n); $key = str_pad(BitcoinLib::hex_encode($key_dec), 64, '0', STR_PAD_LEFT); } else if ($previous['type'] == 'public') { // newPoint + parentPubkeyPoint $decompressed = BitcoinLib::decompress_public_key($public_key); // Can return false. Throw exception? $new_point = $g->mul($Il_dec)->add($decompressed['point']); // Prepare offset, by multiplying Il by g, and adding this to the previous public key point. // Create a new point by adding the two. $new_x = str_pad(BitcoinLib::hex_encode($new_point->getX()), 64, '0', STR_PAD_LEFT); $new_y = str_pad(BitcoinLib::hex_encode($new_point->getY()), 64, '0', STR_PAD_LEFT); $key = BitcoinLib::compress_public_key('04' . $new_x . $new_y); } else { throw new \InvalidArgumentException("Unknown previous type in CKD"); } $data = array( 'network' => $previous['network'], 'testnet' => $previous['testnet'], 'magic_bytes' => $previous['magic_bytes'], 'type' => $previous['type'], 'depth' => $previous['depth'] + 1, 'fingerprint' => $fingerprint, 'i' => $i, 'address_number' => self::get_address_number($i), 'chain_code' => $I_r, 'key' => $key ); return (count($address_definition) > 0) ? self::CKD(self::encode($data), $address_definition, $generated) : array(self::encode($data), implode('/', $generated)); } /** * Get Definition Tuple * * This function accepts a '/' separated string of numbers, and generates * an array of 32-bit numbers (in hex) which are address child number * for the derivation in CKD. It needs $parent, an extended key, in * order to generate the correct hex bytes for the address. * * @param string $parent * @param string $string_def * @return array */ public static function get_definition_tuple($parent, $string_def) { // Extract the child numbers. $address_definition = explode("/", $string_def); // Load the depth of the parent key. $import = self::import($parent); $depth = $import['depth']; // Start building the address bytes tuple. foreach ($address_definition as &$def) { // Check if we want the prime derivation $want_prime = 0; if (strpos($def, "'") !== false) { // Remove ' from the number, and set $want_prime $def = str_replace("'", '', $def); $want_prime = 1; } $def = self::calc_address_bytes($def, $want_prime); $depth++; } // Reverse the array (to allow array_pop to work) and return. return array_reverse($address_definition); } /** * Build Key * * This function accepts a parent extended key, and a string definition * describing the desired derivation '0/0/1' or '0/1'. See get_definition_tuple() * for information on generating the address bytes from this definition. * The address bytes tuple is then passed to the recursive CKD function, * which pops a value from the array, generates that key, and then * decides if it needs to process more ($address_definition array * still has values) where it will call itself again, or else if its * work is done it returns the key. * * @param string $input * @param string $string_def * @return string */ public static function build_key($input, $string_def) { if (is_array($input) && count($input) == 2) { $parent = $input[0]; $def = $input[1]; } else if (is_string($input) == true) { $parent = $input; $def = "m"; } else { throw new \InvalidArgumentException("input should be string or [key, path]"); } if (!preg_match("#^[mM/0-9']*$#", $string_def)) { throw new \InvalidArgumentException("Path can only contain chars: [mM/0-9']"); } // if the desired path is public while the input is private $toPublic = substr($string_def, 0, 1) == "M" && substr($def, 0, 1) == "m"; if ($toPublic) { // derive the private path, convert to public when returning $string_def[0] = "m"; } // if the desired definition starts with m/ or M/ then it's an absolute path // this function however works with relative paths, so we need to make the path relative if (strtolower(substr($string_def, 0, 1)) == 'm') { // the desired definition should start with the definition if (strpos($string_def, $def) !== 0) { throw new \InvalidArgumentException("Path ({$string_def}) should match parent path ({$def}) when building key by absolute path"); } // unshift the definition to make the desired definition relative $string_def = substr($string_def, strlen($def)) ?: ""; // if nothing remains we have nothing to do if ($string_def) { // unshift the / that remains $string_def = substr($string_def, 1); } } // do child key derivation if (strlen($string_def)) { $address_definition = self::get_definition_tuple($parent, $string_def); $extended_key = self::CKD($parent, $address_definition, explode("/", $def)); } else { $extended_key = [$parent, $def]; } // convert to public key if necessary if ($toPublic) { return self::extended_private_to_public($extended_key); } else { return $extended_key; } } /** * Build Address * * This function calls build_key() to generate the desired key, and * then converts the generated key to it's corresponding address. * * @param string $master * @param string $string_def * @return string */ public static function build_address($master, $string_def) { $extended_key = self::build_key($master, $string_def); return array(self::key_to_address($extended_key[0]), $extended_key[1]); } /** * Encode * * This function accepts an array of information describing the * extended key. It will determine the magic bytes depending on the * network, testnet, and type indexes. The fingerprint is accepted * as-is, because the CKD() and master_key() functions work that out * themselves. The child number is fixed at '00000000'. Private key's * are padded with \x00 to ensure they are 33 bytes. This information * is concatenated and converted to base58check encoding. * The input array has the same indexes as the output from the import() * function to ensure compatibility. * * @param array $data * @return string */ public static function encode($data) { // Magic Byte - 4 bytes / 8 characters - left out for now $magic_byte_var = strtolower($data['network']) . "_" . (($data['testnet'] == true) ? 'testnet' : 'mainnet') . "_{$data['type']}"; $magic_byte = self::$$magic_byte_var; $fingerprint = $data['fingerprint']; $child_number = $data['i']; $depth = BitcoinLib::hex_encode($data['depth']); $chain_code = $data['chain_code']; $key_data = ($data['type'] == 'public') ? $data['key'] : '00' . $data['key']; $string = $magic_byte . $depth . $fingerprint . $child_number . $chain_code . $key_data; return BitcoinLib::base58_encode_checksum($string); } /* * Import * * This function generates an array containing the properties of the * extended key. It decodes the extended key, and works determines * as much information as possible to allow compatibility with the * encode function, which accepts a similarly constructed array. * * @param string $ext_key * @return array */ public static function import($ext_key) { $hex = BitcoinLib::base58_decode($ext_key); $key = []; $key['magic_bytes'] = substr($hex, 0, 8); $magic_byte_info = self::describe_magic_bytes($key['magic_bytes']); // Die if key type isn't supported by this library. if ($magic_byte_info == false) { throw new \InvalidArgumentException("Unsupported magic byte"); } $key['type'] = $magic_byte_info['type']; $key['testnet'] = $magic_byte_info['testnet']; $key['network'] = $magic_byte_info['network']; $key['version'] = $magic_byte_info['version']; $key['depth'] = gmp_strval(gmp_init(substr($hex, 8, 2), 16), 10); $key['fingerprint'] = substr($hex, 10, 8); $key['i'] = substr($hex, 18, 8); $key['address_number'] = self::get_address_number($key['i']); $key['chain_code'] = substr($hex, 26, 64); $key['is_compressed'] = true; if ($key['type'] == 'public') { $key_start_position = 90; $offset = 66; } else { $key_start_position = 92; $offset = 64; } $key['key'] = substr($hex, $key_start_position, $offset); if (!in_array($key['type'], ['public', 'private'])) { throw new \InvalidArgumentException("Invalid type"); } // Validate obtained key if ($key['type'] == 'public' && !BitcoinLib::validate_public_key($key['key'])) { throw new \InvalidArgumentException("Invalid public key"); } if ($key['type'] == 'private' && !self::check_valid_hmac_key($key['key'])) { throw new \InvalidArgumentException("Invalid private key"); } return $key; } /** * BIP32 Private Keys To Wallet * * This function accepts $wallet - a reference to an array containing * wallet info, indexed by hash160 of expected address. * It will attempt to add each key to this wallet, as well as all the * details that could be needed later on: public key, uncompressed key, * address, an indicator for address compression. Type is always set * to pubkeyhash for private key entries in the wallet. * * @param $wallet * @param array $keys * @param null $magic_byte */ public static function bip32_keys_to_wallet(&$wallet, array $keys, $magic_byte = null) { $magic_byte = BitcoinLib::magicByte($magic_byte); RawTransaction::private_keys_to_wallet($wallet, array_map(function ($key) { return BIP32::import($key[0]); }, $keys), $magic_byte); } /** * Extended Private To Public * * Converts the encoded private key to a public key, and alters the * properties so it's displayed as a public key. * * @param string|array $input xpriv or [xpriv, path] * @return string */ public static function extended_private_to_public($input) { if (is_array($input) && count($input) == 2) { $ext_private_key = $input[0]; $generated = $input[1]; } else if (is_string($input) == true) { $ext_private_key = $input; $generated = false; } else { throw new \InvalidArgumentException("input should be string or [key, path]"); } $pubkey = self::import($ext_private_key); if ($pubkey['type'] !== 'private') { throw new \InvalidArgumentException("input is not a private key"); } $pubkey['key'] = BitcoinLib::private_key_to_public_key($pubkey['key'], true); $pubkey['type'] = 'public'; if ($generated !== false) { $generated = str_replace('m', 'M', $generated); return array(self::encode($pubkey), $generated); } else { return self::encode($pubkey); } } /** * Extract Public Key * * This function accepts a BIP32 key, and either calculates the public * key if it's an extended private key, or just extracts the public * key if it's an extended public key. * * @param array|string $input * @return FALSE|string */ public static function extract_public_key($input) { if (is_array($input) && count($input) == 2) { $ext_key = $input[0]; } else if (is_string($input) == true) { $ext_key = $input; } else { throw new \InvalidArgumentException("input should be string or [key, path]"); } $import = self::import($ext_key); return ($import['type'] == 'private') ? BitcoinLib::private_key_to_public_key($import['key'], true) : $import['key']; } /** * Key To Address * * This function accepts a bip32 extended key, and converts it to a * bitcoin address. * * @param string $extended_key * @return string */ public static function key_to_address($extended_key) { $import = self::import($extended_key); if ($import['type'] == 'public') { $public = $import['key']; } else { $public = BitcoinLib::private_key_to_public_key($import['key'], true); } // Convert the public key to the address. return BitcoinLib::public_key_to_address($public, $import['version']); } /** * Describe Magic Bytes * * This function accepts a $magic_bytes string, which is compared to * a predefined list of constants. If the $magic_bytes string is found, * it returns an array of information about the bytes: the key type, * a boolean for whether its a testnet key, and the cryptocoin network. * * @param string $magic_bytes * @return array|FALSE */ public static function describe_magic_bytes($magic_bytes) { $key = array(); switch ($magic_bytes) { case self::$bitcoin_mainnet_public: $key['type'] = 'public'; $key['testnet'] = false; $key['network'] = 'bitcoin'; $key['version'] = self::$bitcoin_mainnet_version; break; case self::$bitcoin_mainnet_private: $key['type'] = 'private'; $key['testnet'] = false; $key['network'] = 'bitcoin'; $key['version'] = self::$bitcoin_mainnet_version; break; case self::$bitcoin_testnet_public: $key['type'] = 'public'; $key['testnet'] = true; $key['network'] = 'bitcoin'; $key['version'] = self::$bitcoin_testnet_version; break; case self::$bitcoin_testnet_private: $key['type'] = 'private'; $key['testnet'] = true; $key['network'] = 'bitcoin'; $key['version'] = self::$bitcoin_testnet_version; break; case self::$dogecoin_mainnet_public: $key['type'] = 'public'; $key['testnet'] = false; $key['network'] = 'dogecoin'; $key['version'] = self::$dogecoin_mainnet_version; break; case self::$dogecoin_mainnet_private: $key['type'] = 'private'; $key['testnet'] = false; $key['network'] = 'dogecoin'; $key['version'] = self::$dogecoin_mainnet_version; break; case self::$dogecoin_testnet_public: $key['type'] = 'public'; $key['testnet'] = true; $key['network'] = 'dogecoin'; $key['version'] = self::$dogecoin_testnet_version; break; case self::$dogecoin_testnet_private: $key['type'] = 'private'; $key['testnet'] = true; $key['network'] = 'dogecoin'; $key['version'] = self::$dogecoin_testnet_version; break; case self::$litecoin_mainnet_public: $key['type'] = 'public'; $key['testnet'] = false; $key['network'] = 'litecoin'; $key['version'] = self::$litecoin_mainnet_version; break; case self::$litecoin_mainnet_private: $key['type'] = 'private'; $key['testnet'] = false; $key['network'] = 'litecoin'; $key['version'] = self::$litecoin_mainnet_version; break; case self::$litecoin_testnet_public: $key['type'] = 'public'; $key['testnet'] = true; $key['network'] = 'litecoin'; $key['version'] = self::$litecoin_testnet_version; break; case self::$litecoin_testnet_private: $key['type'] = 'private'; $key['testnet'] = true; $key['network'] = 'litecoin'; $key['version'] = self::$litecoin_testnet_version; break; default: return false; } return $key; } /** * Calc Address Bytes * * This function is used to convert the $address_number, i, into a 32 * bit unsigned integer. If $set_prime = 1, then it will flip the left-most * bit, indicating a prime derivation must be used. * * @param int $address_number * @param int $set_prime * @return string */ public static function calc_address_bytes($address_number, $set_prime = 0) { $and_result = ($set_prime == 1) ? $address_number | 0x80000000 : $address_number; $hex = unpack("H*", pack("N", $and_result)); return $hex[1]; } /** * Check Is Prime Hex * * Checks if the highest most bit is set - that prime derivation must * be used. Test is done by initializing the address $hex as a number, * and checking if it is greater than 0x80000000. Returns 0 if not * prime, and 1 if the number is prime. * * @param string $hex * @return int */ public static function check_is_prime_hex($hex) { $math = EccFactory::getAdapter(); $cmp = $math->cmp($math->hexDec($hex), $math->hexDec('80000000')); $is_prime = ($cmp == -1) ? 0 : 1; return $is_prime; } /** * Check Valid HMAC Key * * This function checks that the generated private keys meet the standard * for private keys, as imposed by the secp256k1 curve. The key can't * be zero, nor can it >= $n, which is the order of the secp256k1 * curve. Returning false trigger an error, or cause the program to * increase the address number and rerun the CKD function. * * @param string $key * @return boolean */ public static function check_valid_hmac_key($key) { $math = EccFactory::getAdapter(); $g = EccFactory::getSecgCurves($math)->generator256k1(); $n = $g->getOrder(); // initialize the key as a base 16 number. $g_l = $math->hexDec($key); // compare it to zero $_equal_zero = $math->cmp($g_l, 0); // compare it to the order of the curve $_GE_n = $math->cmp($g_l, $n); // Check for invalid data if ($_equal_zero == 0 || $_GE_n == 1 || $_GE_n == 0) { return false; } return true; } /** * Get Address Number * * Convert the 32 bit integer into a decimal numbe, and perform an & * to unset the byte. * @param $hex * @param int $is_prime * @return int */ public static function get_address_number($hex, $is_prime = 0) { $math = EccFactory::getAdapter(); $dec = $math->hexDec($hex); if ($is_prime == 1) { $dec = $math->sub($math->hexDec($hex), $math->hexDec('80000000')); } $n = $dec & 0x7fffffff; return $n; } }
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/src/Jsonrpcclient.php
src/Jsonrpcclient.php
<?php namespace BitWasp\BitcoinLib; /* COPYRIGHT Copyright 2007 Sergio Vaccaro <sergio@inservibile.org> This file is part of JSON-RPC PHP. JSON-RPC PHP is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. JSON-RPC PHP is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with JSON-RPC PHP; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** * The object of this class are generic jsonRPC 1.0 clients * http://json-rpc.org/wiki/specification * * @author sergio <jsonrpcphp@inservibile.org> */ /** * This file has been modified to return an array containing details * of an error instead of throwing an exception, to fit the BitWasp's * purposes. */ /** * jsonRPCclient library */ class Jsonrpcclient { /** * Debug state * * @var boolean */ private $debug; /** * The server URL * * @var string */ private $url; /** * The request id * * @var integer */ private $id; /** * If true, notifications are performed instead of requests * * @var boolean */ private $notification = false; /** * Takes the connection parameters * * @param array ($url, $debug) */ public function __construct($params) { // server URL $this->url = $params['url']; // proxy empty($params['proxy']) ? $this->proxy = '' : $this->proxy = $params['proxy']; // debug state empty($params['debug']) ? $this->debug = false : $this->debug = true; // message id // $this->id = 1; } /** * Sets the notification state of the object. In this state, notifications are performed, instead of requests. * * @param boolean $notification */ public function setRPCNotification($notification) { empty($notification) ? $this->notification = false : $this->notification = true; } /** * Performs a jsonRCP request and gets the results as an array * * @param string $method * @param array $params * @return bool * @throws \Exception */ public function __call($method, $params) { // check the method/function if (!is_scalar($method)) { throw new \InvalidArgumentException('Method name has no scalar value'); } // check the params are entered as an array if (is_array($params)) { // no keys $params = array_values($params); } else { throw new \InvalidArgumentException('Params must be given as array'); } // sets notification or request task $currentId = ($this->notification) ? null : $this->id; // prepares the request $request = array( 'method' => $method, 'params' => $params, 'id' => $currentId ); $request = json_encode($request); $this->debug && $this->debug .= '***** Request *****' . "\n" . $request . "\n" . '***** End Of request *****' . "\n\n"; // performs the HTTP POST $ch = curl_init($this->url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json')); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $request); $response = json_decode(curl_exec($ch), true); curl_close($ch); // debug output if ($this->debug) { echo nl2br($this->debug); } // final checks and return if (!$this->notification) { // check if ($response['id'] != $currentId) { throw new \Exception('Incorrect response id (request id: ' . $currentId . ', response id: ' . $response['id'] . ')'); } if (!is_null($response['error'])) { //throw new Exception('Request error: '.$response['error']); // return the error array. return $response['error']; } return $response['result']; } else { return true; } } }
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/src/Electrum.php
src/Electrum.php
<?php namespace BitWasp\BitcoinLib; use Mdanter\Ecc\EccFactory; /** * Electrum Library * * This class contains functions which implement the electrum standard * functionality. * * - A function which stretches the seed many times into a 64bit key. * - A function to generate a master public key from the seed. * - A function to generate a private key given the seed, child number, * and whether it's a change address. * - A function to generate the public key from the master public key. * - A function to generate an address from the master public key and an * address version. * - A function to decode a seed from a sequence of words from the electrum * word list. */ class Electrum { /** * Stretch Seed * * This function accepts the wallets $seed as input, and stretches it by * hashing it many times. It returns the result as a hexadecimal string. * * @param string $seed * @return string */ public static function stretch_seed($seed) { $oldseed = $seed; // Perform sha256 hash 5 times per iteration for ($i = 0; $i < 20000; $i++) { // Hash should return binary data $seed = hash('sha256', hash('sha256', hash('sha256', hash('sha256', hash('sha256', $seed . $oldseed, true) . $oldseed, true) . $oldseed, true) . $oldseed, true) . $oldseed, true); } // Convert binary data to hex. $seed = bin2hex($seed); return array('original' => $oldseed, 'seed' => $seed); } /** * Generate MPK * * This function accepts a seed, or secret exponent, and returns the * master public key, from which new public keys and addresses are * derived. * * @param string $seed * @return string */ public static function generate_mpk($seed) { if (strlen($seed) == 32) { $seed = self::stretch_seed($seed); $seed = $seed['seed']; } $math = EccFactory::getAdapter(); $g = EccFactory::getSecgCurves($math)->generator256k1(); $seed = gmp_strval(gmp_init($seed, 16), 10); $secretG = $g->mul($seed); $x = str_pad($math->decHex($secretG->getX()), 64, '0', STR_PAD_LEFT); $y = str_pad($math->decHex($secretG->getY()), 64, '0', STR_PAD_LEFT); // Return the master public key. return $x . $y; } /** * Generate Private Key * * This function accepts a string or a secret exponent as a $seed, * and generates a private key for the $i'th address. Setting the * change parameter to 1 will create different addresses, which the * client uses for change. * * @param string $seed * @param int $iteration * @param int $change (optional) * @return string - hex private key */ public static function generate_private_key($seed, $iteration, $change = 0) { $change = ($change == 0) ? '0' : '1'; if (strlen($seed) == 32) { $seed = self::stretch_seed($seed); $seed = $seed['seed']; } $mpk = self::generate_mpk($seed); $math = EccFactory::getAdapter(); $g = EccFactory::getSecgCurves($math)->generator256k1(); $n = $g->getOrder(); $seedDec = $math->hexDec($seed); $offsetDec = $math->hexDec(hash('sha256', hash('sha256', "$iteration:$change:" . pack('H*', $mpk), true))); $private_key = $math->decHex($math->mod($math->add($seedDec, $offsetDec), $n)); $private_key = str_pad($private_key, 64, '0', STR_PAD_LEFT); return $private_key; } /** * Public Key From MPK * * This function is used to generate a public key from the supplied * $mpk - the master public key, and an $iteration indicating which * address in the sequence should be generated. * * @param string $mpk * @param int $iteration * @return string */ public static function public_key_from_mpk($mpk, $iteration, $change = 0, $compressed = false) { $change = ($change == 0) ? '0' : '1'; $math = EccFactory::getAdapter(); $gen = EccFactory::getSecgCurves($math)->generator256k1(); // Generate the curve, and the generator point. // Prepare the input values, by converting the MPK to X and Y coordinates $x = $math->hexDec(substr($mpk, 0, 64)); $y = $math->hexDec(substr($mpk, 64, 64)); // Generate a scalar from the $iteration and $mpk $z = $math->hexDec(hash('sha256', hash('sha256', "$iteration:$change:" . pack('H*', $mpk), true))); // Add the Point defined by $x and $y, to the result of EC multiplication of $z by $gen $pt = $gen->getCurve()->getPoint($x, $y, $gen->getOrder()); $pt = $pt->add($gen->mul($z)); // Generate the uncompressed public key. $keystr = '04' . str_pad($math->decHex($pt->getX()), 64, '0', STR_PAD_LEFT) . str_pad($math->decHex($pt->getY()), 64, '0', STR_PAD_LEFT); return ($compressed == true) ? BitcoinLib::compress_public_key($keystr) : $keystr; } /** * Address from MPK * * Generate an address from the $mpk, and $iteration. This function * uses the public_key_from_mpk() function, and converts the result * to the bitcoin address. * * @param string $mpk - master public key * @param int $sequence - pubkey sequence # to derive * @param string $magic_byte for address * @param int $change - 0 for regular sequence, 1 for change sequence * @param bool $compressed - return the compressed address * @return string */ public static function address_from_mpk($mpk, $sequence, $magic_byte, $change = 0, $compressed = false) { $change = ($change == 0) ? 0 : 1; $public_key = self::public_key_from_mpk($mpk, $sequence, $change, $compressed); $address = BitcoinLib::public_key_to_address($public_key, $magic_byte); return $address; } /** * Decode Mnemonic * * This function decodes a string of 12 words to convert to the electrum * seed. This is an implementation of http://tools.ietf.org/html/rfc1751, * which is how electrum generates a 128-bit key from 12 words. * * @param string $words * @return string */ public static function decode_mnemonic($words) { $math = EccFactory::getAdapter(); $words = explode(" ", $words); $out = ''; $n = 1626; for ($i = 0; $i < (count($words) / 3); $i++) { $a = (3 * $i); list($word1, $word2, $word3) = array($words[$a], $words[$a + 1], $words[$a + 2]); $index_w1 = array_search($word1, self::$words); $index_w2 = array_search($word2, self::$words) % $n; $index_w3 = array_search($word3, self::$words) % $n; $x = $index_w1 + $n * ($math->mod($index_w2 - $index_w1, $n)) + $n * $n * ($math->mod($index_w3 - $index_w2, $n)); $out .= BitcoinLib::hex_encode($x); } return $out; } /** * Words * * These words are used in electrum to generate 128 bit keys from * 12 word combinations, in accordance with http://tools.ietf.org/html/rfc1751 */ public static $words = array("like", "just", "love", "know", "never", "want", "time", "out", "there", "make", "look", "eye", "down", "only", "think", "heart", "back", "then", "into", "about", "more", "away", "still", "them", "take", "thing", "even", "through", "long", "always", "world", "too", "friend", "tell", "try", "hand", "thought", "over", "here", "other", "need", "smile", "again", "much", "cry", "been", "night", "ever", "little", "said", "end", "some", "those", "around", "mind", "people", "girl", "leave", "dream", "left", "turn", "myself", "give", "nothing", "really", "off", "before", "something", "find", "walk", "wish", "good", "once", "place", "ask", "stop", "keep", "watch", "seem", "everything", "wait", "got", "yet", "made", "remember", "start", "alone", "run", "hope", "maybe", "believe", "body", "hate", "after", "close", "talk", "stand", "own", "each", "hurt", "help", "home", "god", "soul", "new", "many", "two", "inside", "should", "true", "first", "fear", "mean", "better", "play", "another", "gone", "change", "use", "wonder", "someone", "hair", "cold", "open", "best", "any", "behind", "happen", "water", "dark", "laugh", "stay", "forever", "name", "work", "show", "sky", "break", "came", "deep", "door", "put", "black", "together", "upon", "happy", "such", "great", "white", "matter", "fill", "past", "please", "burn", "cause", "enough", "touch", "moment", "soon", "voice", "scream", "anything", "stare", "sound", "red", "everyone", "hide", "kiss", "truth", "death", "beautiful", "mine", "blood", "broken", "very", "pass", "next", "forget", "tree", "wrong", "air", "mother", "understand", "lip", "hit", "wall", "memory", "sleep", "free", "high", "realize", "school", "might", "skin", "sweet", "perfect", "blue", "kill", "breath", "dance", "against", "fly", "between", "grow", "strong", "under", "listen", "bring", "sometimes", "speak", "pull", "person", "become", "family", "begin", "ground", "real", "small", "father", "sure", "feet", "rest", "young", "finally", "land", "across", "today", "different", "guy", "line", "fire", "reason", "reach", "second", "slowly", "write", "eat", "smell", "mouth", "step", "learn", "three", "floor", "promise", "breathe", "darkness", "push", "earth", "guess", "save", "song", "above", "along", "both", "color", "house", "almost", "sorry", "anymore", "brother", "okay", "dear", "game", "fade", "already", "apart", "warm", "beauty", "heard", "notice", "question", "shine", "began", "piece", "whole", "shadow", "secret", "street", "within", "finger", "point", "morning", "whisper", "child", "moon", "green", "story", "glass", "kid", "silence", "since", "soft", "yourself", "empty", "shall", "angel", "answer", "baby", "bright", "dad", "path", "worry", "hour", "drop", "follow", "power", "war", "half", "flow", "heaven", "act", "chance", "fact", "least", "tired", "children", "near", "quite", "afraid", "rise", "sea", "taste", "window", "cover", "nice", "trust", "lot", "sad", "cool", "force", "peace", "return", "blind", "easy", "ready", "roll", "rose", "drive", "held", "music", "beneath", "hang", "mom", "paint", "emotion", "quiet", "clear", "cloud", "few", "pretty", "bird", "outside", "paper", "picture", "front", "rock", "simple", "anyone", "meant", "reality", "road", "sense", "waste", "bit", "leaf", "thank", "happiness", "meet", "men", "smoke", "truly", "decide", "self", "age", "book", "form", "alive", "carry", "escape", "damn", "instead", "able", "ice", "minute", "throw", "catch", "leg", "ring", "course", "goodbye", "lead", "poem", "sick", "corner", "desire", "known", "problem", "remind", "shoulder", "suppose", "toward", "wave", "drink", "jump", "woman", "pretend", "sister", "week", "human", "joy", "crack", "grey", "pray", "surprise", "dry", "knee", "less", "search", "bleed", "caught", "clean", "embrace", "future", "king", "son", "sorrow", "chest", "hug", "remain", "sat", "worth", "blow", "daddy", "final", "parent", "tight", "also", "create", "lonely", "safe", "cross", "dress", "evil", "silent", "bone", "fate", "perhaps", "anger", "class", "scar", "snow", "tiny", "tonight", "continue", "control", "dog", "edge", "mirror", "month", "suddenly", "comfort", "given", "loud", "quickly", "gaze", "plan", "rush", "stone", "town", "battle", "ignore", "spirit", "stood", "stupid", "yours", "brown", "build", "dust", "hey", "kept", "pay", "phone", "twist", "although", "ball", "beyond", "hidden", "nose", "taken", "fail", "float", "pure", "somehow", "wash", "wrap", "angry", "cheek", "creature", "forgotten", "heat", "rip", "single", "space", "special", "weak", "whatever", "yell", "anyway", "blame", "job", "choose", "country", "curse", "drift", "echo", "figure", "grew", "laughter", "neck", "suffer", "worse", "yeah", "disappear", "foot", "forward", "knife", "mess", "somewhere", "stomach", "storm", "beg", "idea", "lift", "offer", "breeze", "field", "five", "often", "simply", "stuck", "win", "allow", "confuse", "enjoy", "except", "flower", "seek", "strength", "calm", "grin", "gun", "heavy", "hill", "large", "ocean", "shoe", "sigh", "straight", "summer", "tongue", "accept", "crazy", "everyday", "exist", "grass", "mistake", "sent", "shut", "surround", "table", "ache", "brain", "destroy", "heal", "nature", "shout", "sign", "stain", "choice", "doubt", "glance", "glow", "mountain", "queen", "stranger", "throat", "tomorrow", "city", "either", "fish", "flame", "rather", "shape", "spin", "spread", "ash", "distance", "finish", "image", "imagine", "important", "nobody", "shatter", "warmth", "became", "feed", "flesh", "funny", "lust", "shirt", "trouble", "yellow", "attention", "bare", "bite", "money", "protect", "amaze", "appear", "born", "choke", "completely", "daughter", "fresh", "friendship", "gentle", "probably", "six", "deserve", "expect", "grab", "middle", "nightmare", "river", "thousand", "weight", "worst", "wound", "barely", "bottle", "cream", "regret", "relationship", "stick", "test", "crush", "endless", "fault", "itself", "rule", "spill", "art", "circle", "join", "kick", "mask", "master", "passion", "quick", "raise", "smooth", "unless", "wander", "actually", "broke", "chair", "deal", "favorite", "gift", "note", "number", "sweat", "box", "chill", "clothes", "lady", "mark", "park", "poor", "sadness", "tie", "animal", "belong", "brush", "consume", "dawn", "forest", "innocent", "pen", "pride", "stream", "thick", "clay", "complete", "count", "draw", "faith", "press", "silver", "struggle", "surface", "taught", "teach", "wet", "bless", "chase", "climb", "enter", "letter", "melt", "metal", "movie", "stretch", "swing", "vision", "wife", "beside", "crash", "forgot", "guide", "haunt", "joke", "knock", "plant", "pour", "prove", "reveal", "steal", "stuff", "trip", "wood", "wrist", "bother", "bottom", "crawl", "crowd", "fix", "forgive", "frown", "grace", "loose", "lucky", "party", "release", "surely", "survive", "teacher", "gently", "grip", "speed", "suicide", "travel", "treat", "vein", "written", "cage", "chain", "conversation", "date", "enemy", "however", "interest", "million", "page", "pink", "proud", "sway", "themselves", "winter", "church", "cruel", "cup", "demon", "experience", "freedom", "pair", "pop", "purpose", "respect", "shoot", "softly", "state", "strange", "bar", "birth", "curl", "dirt", "excuse", "lord", "lovely", "monster", "order", "pack", "pants", "pool", "scene", "seven", "shame", "slide", "ugly", "among", "blade", "blonde", "closet", "creek", "deny", "drug", "eternity", "gain", "grade", "handle", "key", "linger", "pale", "prepare", "swallow", "swim", "tremble", "wheel", "won", "cast", "cigarette", "claim", "college", "direction", "dirty", "gather", "ghost", "hundred", "loss", "lung", "orange", "present", "swear", "swirl", "twice", "wild", "bitter", "blanket", "doctor", "everywhere", "flash", "grown", "knowledge", "numb", "pressure", "radio", "repeat", "ruin", "spend", "unknown", "buy", "clock", "devil", "early", "false", "fantasy", "pound", "precious", "refuse", "sheet", "teeth", "welcome", "add", "ahead", "block", "bury", "caress", "content", "depth", "despite", "distant", "marry", "purple", "threw", "whenever", "bomb", "dull", "easily", "grasp", "hospital", "innocence", "normal", "receive", "reply", "rhyme", "shade", "someday", "sword", "toe", "visit", "asleep", "bought", "center", "consider", "flat", "hero", "history", "ink", "insane", "muscle", "mystery", "pocket", "reflection", "shove", "silently", "smart", "soldier", "spot", "stress", "train", "type", "view", "whether", "bus", "energy", "explain", "holy", "hunger", "inch", "magic", "mix", "noise", "nowhere", "prayer", "presence", "shock", "snap", "spider", "study", "thunder", "trail", "admit", "agree", "bag", "bang", "bound", "butterfly", "cute", "exactly", "explode", "familiar", "fold", "further", "pierce", "reflect", "scent", "selfish", "sharp", "sink", "spring", "stumble", "universe", "weep", "women", "wonderful", "action", "ancient", "attempt", "avoid", "birthday", "branch", "chocolate", "core", "depress", "drunk", "especially", "focus", "fruit", "honest", "match", "palm", "perfectly", "pillow", "pity", "poison", "roar", "shift", "slightly", "thump", "truck", "tune", "twenty", "unable", "wipe", "wrote", "coat", "constant", "dinner", "drove", "egg", "eternal", "flight", "flood", "frame", "freak", "gasp", "glad", "hollow", "motion", "peer", "plastic", "root", "screen", "season", "sting", "strike", "team", "unlike", "victim", "volume", "warn", "weird", "attack", "await", "awake", "built", "charm", "crave", "despair", "fought", "grant", "grief", "horse", "limit", "message", "ripple", "sanity", "scatter", "serve", "split", "string", "trick", "annoy", "blur", "boat", "brave", "clearly", "cling", "connect", "fist", "forth", "imagination", "iron", "jock", "judge", "lesson", "milk", "misery", "nail", "naked", "ourselves", "poet", "possible", "princess", "sail", "size", "snake", "society", "stroke", "torture", "toss", "trace", "wise", "bloom", "bullet", "cell", "check", "cost", "darling", "during", "footstep", "fragile", "hallway", "hardly", "horizon", "invisible", "journey", "midnight", "mud", "nod", "pause", "relax", "shiver", "sudden", "value", "youth", "abuse", "admire", "blink", "breast", "bruise", "constantly", "couple", "creep", "curve", "difference", "dumb", "emptiness", "gotta", "honor", "plain", "planet", "recall", "rub", "ship", "slam", "soar", "somebody", "tightly", "weather", "adore", "approach", "bond", "bread", "burst", "candle", "coffee", "cousin", "crime", "desert", "flutter", "frozen", "grand", "heel", "hello", "language", "level", "movement", "pleasure", "powerful", "random", "rhythm", "settle", "silly", "slap", "sort", "spoken", "steel", "threaten", "tumble", "upset", "aside", "awkward", "bee", "blank", "board", "button", "card", "carefully", "complain", "crap", "deeply", "discover", "drag", "dread", "effort", "entire", "fairy", "giant", "gotten", "greet", "illusion", "jeans", "leap", "liquid", "march", "mend", "nervous", "nine", "replace", "rope", "spine", "stole", "terror", "accident", "apple", "balance", "boom", "childhood", "collect", "demand", "depression", "eventually", "faint", "glare", "goal", "group", "honey", "kitchen", "laid", "limb", "machine", "mere", "mold", "murder", "nerve", "painful", "poetry", "prince", "rabbit", "shelter", "shore", "shower", "soothe", "stair", "steady", "sunlight", "tangle", "tease", "treasure", "uncle", "begun", "bliss", "canvas", "cheer", "claw", "clutch", "commit", "crimson", "crystal", "delight", "doll", "existence", "express", "fog", "football", "gay", "goose", "guard", "hatred", "illuminate", "mass", "math", "mourn", "rich", "rough", "skip", "stir", "student", "style", "support", "thorn", "tough", "yard", "yearn", "yesterday", "advice", "appreciate", "autumn", "bank", "beam", "bowl", "capture", "carve", "collapse", "confusion", "creation", "dove", "feather", "girlfriend", "glory", "government", "harsh", "hop", "inner", "loser", "moonlight", "neighbor", "neither", "peach", "pig", "praise", "screw", "shield", "shimmer", "sneak", "stab", "subject", "throughout", "thrown", "tower", "twirl", "wow", "army", "arrive", "bathroom", "bump", "cease", "cookie", "couch", "courage", "dim", "guilt", "howl", "hum", "husband", "insult", "led", "lunch", "mock", "mostly", "natural", "nearly", "needle", "nerd", "peaceful", "perfection", "pile", "price", "remove", "roam", "sanctuary", "serious", "shiny", "shook", "sob", "stolen", "tap", "vain", "void", "warrior", "wrinkle", "affection", "apologize", "blossom", "bounce", "bridge", "cheap", "crumble", "decision", "descend", "desperately", "dig", "dot", "flip", "frighten", "heartbeat", "huge", "lazy", "lick", "odd", "opinion", "process", "puzzle", "quietly", "retreat", "score", "sentence", "separate", "situation", "skill", "soak", "square", "stray", "taint", "task", "tide", "underneath", "veil", "whistle", "anywhere", "bedroom", "bid", "bloody", "burden", "careful", "compare", "concern", "curtain", "decay", "defeat", "describe", "double", "dreamer", "driver", "dwell", "evening", "flare", "flicker", "grandma", "guitar", "harm", "horrible", "hungry", "indeed", "lace", "melody", "monkey", "nation", "object", "obviously", "rainbow", "salt", "scratch", "shown", "shy", "stage", "stun", "third", "tickle", "useless", "weakness", "worship", "worthless", "afternoon", "beard", "boyfriend", "bubble", "busy", "certain", "chin", "concrete", "desk", "diamond", "doom", "drawn", "due", "felicity", "freeze", "frost", "garden", "glide", "harmony", "hopefully", "hunt", "jealous", "lightning", "mama", "mercy", "peel", "physical", "position", "pulse", "punch", "quit", "rant", "respond", "salty", "sane", "satisfy", "savior", "sheep", "slept", "social", "sport", "tuck", "utter", "valley", "wolf", "aim", "alas", "alter", "arrow", "awaken", "beaten", "belief", "brand", "ceiling", "cheese", "clue", "confidence", "connection", "daily", "disguise", "eager", "erase", "essence", "everytime", "expression", "fan", "flag", "flirt", "foul", "fur", "giggle", "glorious", "ignorance", "law", "lifeless", "measure", "mighty", "muse", "north", "opposite", "paradise", "patience", "patient", "pencil", "petal", "plate", "ponder", "possibly", "practice", "slice", "spell", "stock", "strife", "strip", "suffocate", "suit", "tender", "tool", "trade", "velvet", "verse", "waist", "witch", "aunt", "bench", "bold", "cap", "certainly", "click", "companion", "creator", "dart", "delicate", "determine", "dish", "dragon", "drama", "drum", "dude", "everybody", "feast", "forehead", "former", "fright", "fully", "gas", "hook", "hurl", "invite", "juice", "manage", "moral", "possess", "raw", "rebel", "royal", "scale", "scary", "several", "slight", "stubborn", "swell", "talent", "tea", "terrible", "thread", "torment", "trickle", "usually", "vast", "violence", "weave", "acid", "agony", "ashamed", "awe", "belly", "blend", "blush", "character", "cheat", "common", "company", "coward", "creak", "danger", "deadly", "defense", "define", "depend", "desperate", "destination", "dew", "duck", "dusty", "embarrass", "engine", "example", "explore", "foe", "freely", "frustrate", "generation", "glove", "guilty", "health", "hurry", "idiot", "impossible", "inhale", "jaw", "kingdom", "mention", "mist", "moan", "mumble", "mutter", "observe", "ode", "pathetic", "pattern", "pie", "prefer", "puff", "rape", "rare", "revenge", "rude", "scrape", "spiral", "squeeze", "strain", "sunset", "suspend", "sympathy", "thigh", "throne", "total", "unseen", "weapon", "weary"); }
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/src/BitcoinLib.php
src/BitcoinLib.php
<?php namespace BitWasp\BitcoinLib; use Mdanter\Ecc\EccFactory; use Mdanter\Ecc\Primitives\GeneratorPoint; use Mdanter\Ecc\Primitives\PointInterface; use Mdanter\Ecc\Crypto\Signature\Signature; use Mdanter\Ecc\Crypto\Signature\Signer; use Mdanter\Ecc\Crypto\Key\PublicKey; /** * BitcoinLib * * This library is largely a rewrite of theymos' bitcoin library, * along with some more functions for key manipulation. * * It depends on php-ecc, written by Mathyas Danter. * * Thomas Kerin */ class BitcoinLib { /** * Base58Chars * * This is a string containing the allowed characters in base58. */ private static $base58chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; /** * magic_byte presets * * MAKE SURE alphabetic chars in the HEX are LOWERCASE! * * @var array */ private static $magic_byte_presets = array( 'bitcoin' => '00|05', 'bitcoin-testnet' => '6f|c4', ); /** * use self::magicByte() instead of directly accessing this property * which will initiated this to the 'bitcoin' preset on first call * * @var string */ private static $magic_byte; /** * use self::magicByte('p2sh') instead of directly accessing this property * which will initiated this to the 'bitcoin' 'p2sh' preset on first call * * @var string */ private static $magic_p2sh_byte; public static function setMagicByteDefaults($magic_byte_defaults) { if (isset(self::$magic_byte_presets[$magic_byte_defaults])) { $magic_byte_defaults = self::$magic_byte_presets[$magic_byte_defaults]; } $magic_byte_defaults = explode('|', $magic_byte_defaults); if (count($magic_byte_defaults) != 2) { throw new \InvalidArgumentException("magic_byte_defaults should magic_byte|magic_p2sh_byte"); } self::$magic_byte = $magic_byte_defaults[0]; self::$magic_p2sh_byte = $magic_byte_defaults[1]; } /** * normalizes magic_byte * * accepted: * - '<magic_byte>' -> <magic_byte> * - NULL -> default magic_byte * - '<alias>' -> magic_byte for specified alias * - 'p2sh' -> default magic_p2sh_byte * * @param string $magic_byte * @return string * @throws \Exception */ public static function magicByte($magic_byte = null) { if (self::$magic_byte === null) { self::setMagicByteDefaults('bitcoin'); } if ($magic_byte === null) { return self::$magic_byte; } if (strlen($magic_byte) == 5 && strpos($magic_byte, '|') == 2) { $magic_byte = explode('|', $magic_byte); return $magic_byte[0]; } if (strlen($magic_byte) == 2) { return $magic_byte; } if ($magic_byte == 'p2sh') { return self::magicP2SHByte(); } if (isset(self::$magic_byte_presets[$magic_byte])) { $preset_magic_byte = explode('|', self::$magic_byte_presets[$magic_byte]); return $preset_magic_byte[0]; } throw new \InvalidArgumentException("Failed to determine magic_byte"); } /** * normalizes magic_p2sh_byte * * accepted: * - '<magic_p2sh_byte>' -> <magic_p2sh_byte> * - NULL -> default magic_p2sh_byte * - '<alias>' -> magic_p2sh_byte for specified alias * * @param string $magic_byte * @return string * @throws \Exception */ public static function magicP2SHByte($magic_byte = null) { if (self::$magic_p2sh_byte === null) { self::setMagicByteDefaults('bitcoin'); } if ($magic_byte === null) { return self::$magic_p2sh_byte; } if (strlen($magic_byte) == 5 && strpos($magic_byte, '|') == 2) { $magic_byte = explode('|', $magic_byte); return $magic_byte[1]; } if (strlen($magic_byte) == 2) { return $magic_byte; } if (isset(self::$magic_byte_presets[$magic_byte])) { $preset_magic_byte = explode('|', self::$magic_byte_presets[$magic_byte]); return $preset_magic_byte[1]; } throw new \InvalidArgumentException("Failed to determine magic_p2sh_byte"); } /** * normalizes magic_p2sh_byte pair * * accepted: * - '<magic_byte>|<magic_p2sh_byte>' -> [<magic_byte>, <magic_p2sh_byte>] * - '<magic_byte>' -> default pair if '<magic_byte>' is the default magic_byte * - NULL -> default pair * - '<alias>' -> pair for specified alias * * @param string $magic_byte_pair * @return string[] [magic_byte, magic_p2sh_byte] * @throws \Exception */ public static function magicBytePair($magic_byte_pair = null) { if (self::$magic_byte === null || self::$magic_p2sh_byte === null) { self::setMagicByteDefaults('bitcoin'); } if ($magic_byte_pair === null) { return array(self::$magic_byte, self::$magic_p2sh_byte); } if (strlen($magic_byte_pair) == 5 && strpos($magic_byte_pair, '|') == 2) { return explode('|', $magic_byte_pair); } if (isset(self::$magic_byte_presets[$magic_byte_pair])) { $preset_magic_byte = explode('|', self::$magic_byte_presets[$magic_byte_pair]); return $preset_magic_byte; } throw new \InvalidArgumentException("Failed to determine magic_byte_pair"); } /** * Hex Encode * * Encodes a decimal $number into a hexadecimal string. * * @param int $number * @return string */ public static function hex_encode($number) { $hex = gmp_strval(gmp_init($number, 10), 16); return (strlen($hex) % 2 != 0) ? '0' . $hex : $hex; } /** * Hex Decode * * Decodes a hexadecimal $hex string into a decimal number. * * @param string $hex * @return int */ public static function hex_decode($hex) { return gmp_strval(gmp_init($hex, 16), 10); } /** * Base58 Decode * * This function accepts a base58 encoded string, and decodes the * string into a number, which is converted to hexadecimal. It is then * padded with zero's. * * @param $base58 * @return string */ public static function base58_decode($base58) { $origbase58 = $base58; $return = "0"; for ($i = 0; $i < strlen($base58); $i++) { // return = return*58 + current position of $base58[i]in self::$base58chars $return = gmp_add(gmp_mul($return, 58), strpos(self::$base58chars, $base58[$i])); } $return = gmp_strval($return, 16); for ($i = 0; $i < strlen($origbase58) && $origbase58[$i] == "1"; $i++) { $return = "00" . $return; } if (strlen($return) % 2 != 0) { $return = "0" . $return; } return $return; } /** * Base58 Encode * * Encodes a $hex string in base58 format. Borrowed from prusnaks * addrgen code: https://github.com/prusnak/addrgen/blob/master/php/addrgen.php * * @param string $hex * @return string * @author Pavel Rusnak */ public static function base58_encode($hex) { if (strlen($hex) == 0) { return ''; } // Convert the hex string to a base10 integer $num = gmp_strval(gmp_init($hex, 16), 58); // Check that number isn't just 0 - which would be all padding. if ($num != '0') { $num = strtr( $num, '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv', self::$base58chars ); } else { $num = ''; } // Pad the leading 1's $pad = ''; $n = 0; while (substr($hex, $n, 2) == '00') { $pad .= '1'; $n += 2; } return $pad . $num; } /** * Base58 Encode Checksum * * This function takes a checksum of the input $hex data, concatenates * it with the input, and returns a base58 encoded string with checksum. * * @param string $hex * @return string */ public static function base58_encode_checksum($hex) { $checksum = self::hash256($hex); $checksum = substr($checksum, 0, 8); $hash = $hex . $checksum; return self::base58_encode($hash); } /** * Base58 Decode Checksum * * Returns the original hex data that was encoded in base58 check format. * * @param string $base58 * @return string */ public static function base58_decode_checksum($base58) { $hex = self::base58_decode($base58); return substr($hex, 2, strlen($hex) - 10); } /** * Hash256 * * Takes a sha256(sha256()) hash of the $string. Intended only for * hex strings, as it is packed into raw bytes. * * @param string $string * @return string */ public static function hash256($string) { $bs = @pack("H*", $string); return hash("sha256", hash("sha256", $bs, true)); } /** * Hash160 * * Takes $data as input and returns a ripemd160(sha256()) hash of $string. * Intended for only hex strings, as it is packed into raw bytes. * * @param string $string * @return string */ public static function hash160($string) { $bs = @pack("H*", $string); return hash("ripemd160", hash("sha256", $bs, true)); } /** * Hash160 To Address * * This function accepts an $address_version (used to specify the * protocol or the purpose of the address) which is concatenated with * the $hash160 string, and converted to the basee58 encoded format * (with a checksum) * * @param string $hash160 * @param string $address_version * @return string */ public static function hash160_to_address($hash160, $address_version = null) { $hash160 = self::magicByte($address_version) . $hash160; return self::base58_encode_checksum($hash160); } /** * Generate a 32 byte string of random data. * * This function can be overridden if you have a more sophisticated * random number generator, such as a hardware based random number * generator, or a system capable of delivering lot's of entropy for * MCRYPT_DEV_RANDOM. Do not override this if you do not know what * you are doing! * * @return string */ protected static function get_random() { return mcrypt_create_iv(32, \MCRYPT_DEV_URANDOM); } /** * Public Key To Address * * This function accepts the $public_key, and $address_version (used * to specify the protocol or purpose for the address) as input, and * returns a bitcoin address by taking the hash160 of the $public_key, * and converting this to a base_ * * @param string $public_key * @param string $address_version * @return string */ public static function public_key_to_address($public_key, $address_version = null) { $hash160 = self::hash160($public_key); return self::hash160_to_address($hash160, self::magicByte($address_version)); } /** * Get New Private Key * * This function generates a new private key, a number from 1 to $n. * Once it finds an acceptable value, it will encode it in hex, pad it, * and return the private key. * * @return string */ public static function get_new_private_key() { $math = EccFactory::getAdapter(); $g = EccFactory::getSecgCurves($math)->generator256k1(); $privKey = gmp_strval(gmp_init(bin2hex(self::get_random()), 16)); while ($math->cmp($privKey, $g->getOrder()) !== -1) { $privKey = gmp_strval(gmp_init(bin2hex(self::get_random()), 16)); } $privKeyHex = $math->dechex($privKey); return str_pad($privKeyHex, 64, '0', STR_PAD_LEFT); } /** * Private Key To Public Key * * Accepts a $privKey as input, and does EC multiplication to obtain * a new point along the curve. The X and Y coordinates are the public * key, which are returned as a hexadecimal string in uncompressed * format. * * @param string $privKey * @param boolean $compressed * @return string */ public static function private_key_to_public_key($privKey, $compressed = false) { $math = EccFactory::getAdapter(); $g = EccFactory::getSecgCurves($math)->generator256k1(); $privKey = self::hex_decode($privKey); $secretG = $g->mul($privKey); $xHex = self::hex_encode($secretG->getX()); $yHex = self::hex_encode($secretG->getY()); $xHex = str_pad($xHex, 64, '0', STR_PAD_LEFT); $yHex = str_pad($yHex, 64, '0', STR_PAD_LEFT); $public_key = '04' . $xHex . $yHex; return ($compressed == true) ? self::compress_public_key($public_key) : $public_key; } /** * Private Key To Address * * Converts a $privKey to the corresponding public key, and then * converts to the bitcoin address, using the $address_version. * * @param $private_key * @param $address_version * @return string */ public static function private_key_to_address($private_key, $address_version = null) { $address_version = self::magicByte($address_version); $public_key = self::private_key_to_public_key($private_key); return self::public_key_to_address($public_key, self::magicByte($address_version)); } /** * Get New Key Pair * * Generate a new private key, and convert to an uncompressed public key. * * @return array */ public static function get_new_key_pair() { $private_key = self::get_new_private_key(); $public_key = self::private_key_to_public_key($private_key); return array('privKey' => $private_key, 'pubKey' => $public_key); } /** * Get New Key Set * * This function requires the $address_version to be supplied in order * to generate the correct privateWIF and pubAddress. It returns an * array containing the hex private key, WIF private key, public key, * and bitcoin address * * @param $address_version * @param bool $compressed * @return array */ public static function get_new_key_set($address_version = null, $compressed = false) { $address_version = self::magicByte($address_version); do { $key_pair = self::get_new_key_pair(); $private_WIF = self::private_key_to_WIF($key_pair['privKey'], $compressed, $address_version); if ($compressed == true) { $key_pair['pubKey'] = self::compress_public_key($key_pair['pubKey']); } $public_address = self::public_key_to_address($key_pair['pubKey'], $address_version); } while (!self::validate_address($public_address, $address_version)); return array( 'privKey' => $key_pair['privKey'], 'pubKey' => $key_pair['pubKey'], 'privWIF' => $private_WIF, 'pubAdd' => $public_address ); } /** * Get Private Address Version * * This function * Generates a private key address version (the prefix) from the * supplied public key address version, by adding 0x80 to the number. * * @param string $address_version * @return string */ public static function get_private_key_address_version($address_version = null) { $address_version = self::magicByte($address_version); return gmp_strval( gmp_add( gmp_init($address_version, 16), gmp_init('80', 16) ), 16 ); } /** * Private Key To WIF * * Converts a hexadecimal $privKey to WIF key, using the $address_version * to yield the correct privkey version byte for that network (byte+0x80). * * $compressed = true will yield the private key for the compressed * public key address. * * @param $privKey * @param bool $compressed * @param $address_version * @return string */ public static function private_key_to_WIF($privKey, $compressed = false, $address_version = null) { $key = $privKey . (($compressed == true) ? '01' : ''); return self::hash160_to_address($key, self::get_private_key_address_version(self::magicByte($address_version))); } /** * WIF To Private Key * * Convert a base58 encoded $WIF private key to a hexadecimal private key. * * @param string $WIF * @return string */ public static function WIF_to_private_key($WIF) { $decode = self::base58_decode($WIF); return array('key' => substr($decode, 2, 64), 'is_compressed' => (((strlen($decode) - 10) == 66 && substr($decode, 66, 2) == '01') ? true : false)); } /** * Import Public Key * * Imports an arbitrary $public_key, and returns it untreated if the * left-most bit is '04', or else decompressed the public key if the * left-most bit is '02' or '03'. * * @param string $public_key * @return string */ public static function import_public_key($public_key) { $first = substr($public_key, 0, 2); if (($first == '02' || $first == '03') && strlen($public_key) == '66') { // Compressed public key, need to decompress. $decompressed = self::decompress_public_key($public_key); return ($decompressed == false) ? false : $decompressed['public_key']; } else if ($first == '04') { // Regular public key, pass back untreated. return $public_key; } throw new \InvalidArgumentException("Invalid public key"); } /** * Compress Public Key * * Converts an uncompressed public key to the shorter format. These * compressed public key's have a prefix of 02 or 03, indicating whether * Y is odd or even (tested by gmp_mod2(). With this information, and * the X coordinate, it is possible to regenerate the uncompressed key * at a later stage. * * @param string $public_key * @return string */ public static function compress_public_key($public_key) { $math = EccFactory::getAdapter(); $x_hex = substr($public_key, 2, 64); $y = $math->hexDec(substr($public_key, 66, 64)); $parity = $math->mod($y, 2); return (($parity == 0) ? '02' : '03') . $x_hex; } /** * Decompress Public Key * * Accepts a y_byte, 02 or 03 indicating whether the Y coordinate is * odd or even, and $passpoint, which is simply a hexadecimal X coordinate. * Using this data, it is possible to deconstruct the original * uncompressed public key. * * @param $key * @return array|bool */ public static function decompress_public_key($key) { $math = EccFactory::getAdapter(); $y_byte = substr($key, 0, 2); $x_coordinate = substr($key, 2); $x = self::hex_decode($x_coordinate); $theory = EccFactory::getNumberTheory($math); $generator = EccFactory::getSecgCurves($math)->generator256k1(); $curve = $generator->getCurve(); try { $x3 = $math->powmod($x, 3, $curve->getPrime()); $y2 = $math->add($x3, $curve->getB()); $y0 = $theory->squareRootModP($y2, $curve->getPrime()); if ($y0 == null) { throw new \InvalidArgumentException("Invalid public key"); } $y1 = $math->sub($curve->getPrime(), $y0); $y = ($y_byte == '02') ? (($math->mod($y0, 2) == '0') ? $y0 : $y1) : (($math->mod($y0, 2) !== '0') ? $y0 : $y1); $y_coordinate = str_pad($math->decHex($y), 64, '0', STR_PAD_LEFT); $point = $curve->getPoint($x, $y); } catch (\Exception $e) { throw new \InvalidArgumentException("Invalid public key"); } return array( 'x' => $x_coordinate, 'y' => $y_coordinate, 'point' => $point, 'public_key' => '04' . $x_coordinate . $y_coordinate ); } /** * Validate Public Key * * Validates a public key by attempting to create a point on the * secp256k1 curve. * * @param string $public_key * @return boolean */ public static function validate_public_key($public_key) { if (strlen($public_key) == '66') { // Compressed key // Attempt to decompress the public key. If the point is not // generated, or the function fails, then the key is invalid. $decompressed = self::decompress_public_key($public_key); return $decompressed == true; } else if (strlen($public_key) == '130') { $math = EccFactory::getAdapter(); $generator = EccFactory::getSecgCurves($math)->generator256k1(); // Uncompressed key, try to create the point $x = $math->hexDec(substr($public_key, 2, 64)); $y = $math->hexDec(substr($public_key, 66, 64)); // Attempt to create the point. Point returns false in the // constructor if anything is invalid. try { $generator->getCurve()->getPoint($x, $y); return true; } catch (\Exception $e) { return false; } } return false; } /** * Validate Address * * This function accepts a base58check encoded $address, which is * decoded and checked for validity. Returns FALSE for an invalid * address, otherwise returns TRUE; * * @param string $address * @param string $magic_byte * @param string $magic_p2sh_byte * @return boolean */ public static function validate_address($address, $magic_byte = null, $magic_p2sh_byte = null) { $magic_byte = $magic_byte !== false ? self::magicByte($magic_byte) : false; $magic_p2sh_byte = $magic_p2sh_byte !== false ? self::magicP2SHByte($magic_p2sh_byte) : false; // Check the address is decoded correctly. $decode = self::base58_decode($address); if (strlen($decode) !== 50) { return false; } // Compare the version. $version = substr($decode, 0, 2); if ($version !== $magic_byte && $version !== $magic_p2sh_byte) { return false; } // Finally compare the checksums. return substr($decode, -8) == substr(self::hash256(substr($decode, 0, 42)), 0, 8); } /** * Validate WIF * * This function validates that a WIFs checksum validates, and that * the private key is a valid number within the range 1 - n * * $ver is unused at the moment. * * @param string $wif * @param string $ver * @return boolean */ public static function validate_WIF($wif, $ver = null) { $hex = self::base58_decode($wif); // Learn checksum $crc = substr($hex, -8); $hex = substr($hex, 0, -8); // Learn version $version = substr($hex, 0, 2); $hex = substr($hex, 2); if ($ver !== null && $ver !== $version) { return false; } // Determine if pubkey is compressed $compressed = false; if (strlen($hex) == 66 && substr($hex, 64, 2) == '01') { $compressed = true; $hex = substr($hex, 0, 64); } // Check private key within limit. $math = EccFactory::getAdapter(); $generator = EccFactory::getSecgCurves($math)->generator256k1(); $n = $generator->getOrder(); if ($math->cmp($math->hexDec($hex), $n) > 0) { return false; } // Calculate checksum for what we have, see if it matches. $checksum = self::hash256($version . $hex . (($compressed) ? '01' : '')); $checksum = substr($checksum, 0, 8); return $checksum == $crc; } /** * sign a message with specified private key * * @param $message * @param $privateKey * @param null $k used for testing, don't use it! * @return string * @throws \Exception */ public static function signMessage($message, $privateKey, $k = null) { $math = EccFactory::getAdapter(); $generator = EccFactory::getSecgCurves($math)->generator256k1(); $messageHash = "\x18Bitcoin Signed Message:\n" . hex2bin(RawTransaction::_encode_vint(strlen($message))) . $message; $messageHash = hash('sha256', hash('sha256', $messageHash, true), true); $messageHash = $math->hexDec(bin2hex($messageHash)); $key_dec = $math->hexDec($privateKey['key']); $pubKey = self::private_key_to_public_key($privateKey['key'], false); $x = $math->hexDec(substr($pubKey, 2, 64)); $y = $math->hexDec(substr($pubKey, 66, 64)); $point = $generator->getCurve()->getPoint($x, $y); $_publicKey = new PublicKey($math, $generator, $point); $_privateKey = $generator->getPrivateKeyFrom($key_dec); $signer = new Signer($math); $sign = $signer->sign($_privateKey, $messageHash, $k ?: $math->hexDec((string)bin2hex(self::get_random()))); // calculate the recovery param // there should be a way to get this when signing too, but idk how ... $i = self::calcPubKeyRecoveryParam($sign->getR(), $sign->getS(), $messageHash, $_publicKey->getPoint()); return base64_encode(self::encodeMessageSignature($sign, $i, true)); } /** * attempt to calculate the public key recovery param by trial and error * * @param $r * @param $s * @param $e * @param PointInterface $Q * @return int * @throws \Exception */ private static function calcPubKeyRecoveryParam($r, $s, $e, PointInterface $Q) { $math = EccFactory::getAdapter(); $generator = EccFactory::getSecgCurves($math)->generator256k1(); for ($i = 0; $i < 4; $i++) { if ($pubKey = self::recoverPubKey($r, $s, $e, $i, $generator)) { if ($pubKey->getPoint()->getX() == $Q->getX() && $pubKey->getPoint()->getY() == $Q->getY()) { return $i; } } } throw new \Exception("Failed to find valid recovery factor"); } /** * encode a message signature * * @param Signature $signature * @param $i * @param bool $compressed * @return string * @throws \Exception */ private static function encodeMessageSignature(Signature $signature, $i, $compressed = false) { if (!$compressed) { throw new \Exception("Uncompressed message signing not supported!"); } $val = $i + 27; if ($compressed) { $val += 4; } return hex2bin(implode("", [ BitcoinLib::hex_encode($val), str_pad(BitcoinLib::hex_encode($signature->getR()), 64, '0', STR_PAD_LEFT), str_pad(BitcoinLib::hex_encode($signature->getS()), 64, '0', STR_PAD_LEFT), ])); } /** * based on php-bitcoin-signature-routines implementation (which is based on bitcoinjs-lib's implementation) * which is SEC 1: Elliptic Curve Cryptography, section 4.1.6, "Public Key Recovery Operation" * http://www.secg.org/sec1-v2.pdf * * @param $r * @param $s * @param $e * @param $recoveryFlags * @param GeneratorPoint $G * @return bool|PublicKey */ private static function recoverPubKey($r, $s, $e, $recoveryFlags, GeneratorPoint $G) { $math = EccFactory::getAdapter(); $isYEven = ($recoveryFlags & 1) != 0; $isSecondKey = ($recoveryFlags & 2) != 0; $curve = $G->getCurve(); $signature = new Signature($r, $s); // Precalculate (p + 1) / 4 where p is the field order $p_over_four = $math->div($math->add($curve->getPrime(), 1), 4); // 1.1 Compute x if (!$isSecondKey) { $x = $r; } else { $x = $math->add($r, $G->getOrder()); } // 1.3 Convert x to point $alpha = $math->mod($math->add($math->add($math->pow($x, 3), $math->mul($curve->getA(), $x)), $curve->getB()), $curve->getPrime()); $beta = $math->powmod($alpha, $p_over_four, $curve->getPrime()); // If beta is even, but y isn't or vice versa, then convert it, // otherwise we're done and y == beta. if (($math->mod($beta, 2) == 0) == $isYEven) { $y = $math->sub($curve->getPrime(), $beta); } else { $y = $beta; } // 1.4 Check that nR is at infinity (implicitly done in constructor) $R = $G->getCurve()->getPoint($x, $y); $point_negate = function (PointInterface $p) use ($math, $G) { return $G->getCurve()->getPoint($p->getX(), $math->mul($p->getY(), -1)); }; // 1.6.1 Compute a candidate public key Q = r^-1 (sR - eG) $rInv = $math->inverseMod($r, $G->getOrder()); $eGNeg = $point_negate($G->mul($e)); $Q = $R->mul($s)->add($eGNeg)->mul($rInv); // 1.6.2 Test Q as a public key $signer = new Signer($math); $Qk = new PublicKey($math, $G, $Q); if ($signer->verify($Qk, $signature, $e)) { return $Qk; } return false; } /** * verify a signed message * * @param $address * @param $signature * @param $message * @return bool * @throws \Exception */ public static function verifyMessage($address, $signature, $message) { // extract parameters $address = substr(hex2bin(self::base58_decode($address)), 0, -4); if (strlen($address) != 21 || $address[0] != hex2bin(self::magicByte())) { throw new \InvalidArgumentException('invalid Bitcoin address'); } //figure out what address signed this message - as binary data $derivedAddress = self::deriveAddressFromSignature($signature, $message, true); return $address === $derivedAddress; } /** * helper function to ensure a hex has all it's preceding 0's (which PHP tends to trim off) * * @param $hex * @param null $length * @return string */ public static function padHex($hex, $length = null) { if (!$length) { $length = strlen($hex); if ($length % 2 !== 0) { $length += 1; } } return str_pad($hex, $length, "0", STR_PAD_LEFT); } /** * convert a Satoshi value (int) to a BTC value (float value but as a string) * * @param int $satoshi * @return string */ public static function toBTC($satoshi) { return bcdiv((int)(string)$satoshi, 100000000, 8); } /** * convert a Satoshi value (int) to a BTC value (float) * and return it as a string formatted with 8 decimals * * @param int $satoshi * @return string */ public static function toBTCString($satoshi) { return self::toBTC($satoshi); } /** * convert a BTC value (float) to a Satoshi value (int) * * @param float $btc * @return int */ public static function toSatoshi($btc) { return (int)self::toSatoshiString($btc); } /** * convert a BTC value (float) to a Satoshi value (int) * and return it as a string * * @param float $btc * @return string */
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
true
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/src/RawTransaction.php
src/RawTransaction.php
<?php namespace BitWasp\BitcoinLib; use Mdanter\Ecc\EccFactory; use Mdanter\Ecc\Crypto\Key\PublicKey; use Mdanter\Ecc\Crypto\Signature\Signature; use Mdanter\Ecc\Crypto\Signature\Signer; /** * Raw Transaction Library * * This library contains functions used to decode hex-encoded raw transactions * into an array mirroring bitcoind's decoderawtransaction format. * * Highest level functions are: * - decode : decodes a raw transaction hex to a bitcoind-like array * - encode : encodes a bitcoind-like transaction array to a raw transaction hex. * - validate_signed_transaction : takes a raw transaction hex, it's json inputs, * and an optional input-specifier, and validates the signature(s). * - create_multisig : creates a multisig address from m, and the public keys. * - create_redeem_script - takes a set of public keys, and the number of signatures * required to redeem funds. * - decode_redeem_script - decodes a redeemScript to obtain the pubkeys, m, and n. */ class RawTransaction { /** * used in _check_sig to determine if we want to fail on high S values * * @var bool */ const ALLOW_HIGH_S = true; /** * Some of the defined OP CODES available in Bitcoins script. * */ public static $op_code = array( '00' => 'OP_0', // or OP_FALSE '51' => 'OP_1', // or OP_TRUE '61' => 'OP_NOP', '6a' => 'OP_RETURN', '76' => 'OP_DUP', '87' => 'OP_EQUAL', '88' => 'OP_EQUALVERIFY', 'a6' => 'OP_RIPEMD160', 'a7' => 'OP_SHA1', 'a8' => 'OP_SHA256', 'a9' => 'OP_HASH160', 'aa' => 'OP_HASH256', 'ac' => 'OP_CHECKSIG', 'ae' => 'OP_CHECKMULTISIG' ); /** * Flip Byte Order * * This function is used to swap the byte ordering from little to big * endian, and vice-versa. A byte string, not a reference, is supplied, * the byte order reversed, and the string returned. * * @param string $bytes * @return string */ public static function _flip_byte_order($bytes) { return implode('', array_reverse(str_split($bytes, 2))); } /** * Return Bytes * * This function accepts $string as a reference, and takes the first * $byte_count bytes of hex (twice the number when dealing with hex * characters in a string), and returns it to the user. * Setting the third parameter to TRUE will cause the byte order to flip. * Note: Because $string is a reference to the original copy, this * function actually removes the data from the string. * * @param string $string * @param int $byte_count * @param boolean $reverse * @return string */ public static function _return_bytes(&$string, $byte_count, $reverse = false) { if (strlen($string) < $byte_count * 2) { throw new \InvalidArgumentException("Could not read enough bytes"); } $requested_bytes = substr($string, 0, $byte_count * 2); // Overwrite $string, starting $byte_count bytes from the start. $string = substr($string, $byte_count * 2); // Flip byte order if requested. return ($reverse == false) ? $requested_bytes : self::_flip_byte_order($requested_bytes); } /** * Decimal to Bytes * * This function encodes a $decimal number as a $bytes byte long hex string. * Byte order can be flipped by setting $reverse to TRUE. * * @param int $decimal * @param int $bytes * @param boolean $reverse * @return string */ public static function _dec_to_bytes($decimal, $bytes, $reverse = false) { $hex = dechex($decimal); if (strlen($hex) % 2 != 0) { $hex = "0" . $hex; } $hex = str_pad($hex, $bytes * 2, "0", STR_PAD_LEFT); return ($reverse == true) ? self::_flip_byte_order($hex) : $hex; } /** * Get VarInt * * https://en.bitcoin.it/wiki/Protocol_specification#Variable_length_integer * * This function is used when dealing with a varint. Because their size * is variable, the first byte must be checked to learn the true length * of the encoded number. * $tx is passed by reference, and the first byte is popped. * It is compared against a list of bytes, which are used to infer the * following numbers length. * * @param string $string * @return int */ public static function _get_vint(&$string) { // Load the next byte, convert to decimal. $decimal = hexdec(self::_return_bytes($string, 1)); // Less than 253: Not encoding extra bytes. // More than 253, work out the $number of bytes using the 2^(offset) $num_bytes = ($decimal < 253) ? 0 : 2 ^ ($decimal - 253); // Num_bytes is 0: Just return the decimal // Otherwise, return $num_bytes bytes (order flipped) and converted to decimal return ($num_bytes == 0) ? $decimal : hexdec(self::_return_bytes($string, $num_bytes, true)); } /** * Encode VarInt * Accepts a $decimal number and attempts to encode it to a VarInt. * https://en.bitcoin.it/wiki/Protocol_specification#Variable_length_integer * * If the number is less than 0xFD/253, then the varint returned * is the decimal number, encoded as one hex byte. * If larger than this number, then the numbers magnitude determines * a prefix, out of FD, FE, and FF, depending on the number size. * Returns FALSE if the number is bigger than 64bit. * * @param int $decimal * @return string|FALSE */ public static function _encode_vint($decimal) { $hex = dechex($decimal); if ($decimal < 253) { $hint = self::_dec_to_bytes($decimal, 1); $num_bytes = 0; } elseif ($decimal < 65535) { $hint = 'fd'; $num_bytes = 2; } elseif ($hex < 4294967295) { $hint = 'fe'; $num_bytes = 4; } elseif ($hex < 18446744073709551615) { $hint = 'ff'; $num_bytes = 8; } else { throw new \InvalidArgumentException("Invalid decimal"); } // If the number needs no extra bytes, just return the 1-byte number. // If it needs to indicate a larger integer size (16bit, 32bit, 64bit) // then it returns the size hint and the 64bit number. return ($num_bytes == 0) ? $hint : $hint . self::_dec_to_bytes($decimal, $num_bytes, true); } public static function pushdata($script) { $length = strlen($script) / 2; /** Note that larger integers are serialized without flipping bits - Big endian */ if ($length < 75) { $l = self::_dec_to_bytes($length, 1); $string = $l . $script; } elseif ($length <= 0xff) { $l = self::_dec_to_bytes($length, 1); $string = '4c' . $l . $script; } elseif ($length <= 0xffff) { $l = self::_dec_to_bytes($length, 2, true); $string = '4d' . $l . $script; } elseif ($length <= 0xffffffff) { $l = self::_dec_to_bytes($length, 4, true); $string = '4e' . $l . $script; } else { throw new \RuntimeException('Size of pushdata too large'); } return $string; } /** * Decode Script * * This function accepts a $script (such as scriptSig) and converts it * into an assembled version. Written based on the pybitcointools * transaction.deserialize_script() function. * * @param string $script * @return string */ public static function _decode_script($script) { $pos = 0; $data = array(); while ($pos < strlen($script)) { $code = hexdec(substr($script, $pos, 2)); // hex opcode. $pos += 2; if ($code < 1) { // OP_FALSE $push = '0'; } elseif ($code <= 75) { // $code bytes will be pushed to the stack. $push = substr($script, $pos, ($code * 2)); $pos += $code * 2; } elseif ($code <= 78) { // In this range, 2^($code-76) is the number of bytes to take for the *next* number onto the stack. $szsz = pow(2, $code - 75); // decimal number of bytes. $sz = hexdec(substr($script, $pos, ($szsz * 2))); // decimal number of bytes to load and push. $pos += $szsz; $push = substr($script, $pos, ($pos + $sz * 2)); // Load the data starting from the new position. $pos += $sz * 2; } elseif ($code <= 96) { // OP_x, where x = $code-80 $push = ($code - 80); } else { $push = $code; } $data[] = $push; } return implode(" ", $data); } /** * Decode Inputs * * This function accepts a $raw_transaction by reference, and $input_count, * a decimal number of inputs to extract (learned by calling the get_vint() * function). Returns an array of the construction [vin] if successful, * returns FALSE if an error was encountered. * * @param string $raw_transaction * @param int $input_count * @return array */ public static function _decode_inputs(&$raw_transaction, $input_count) { $inputs = array(); // Loop until $input count is reached, sequentially removing the // leading data from $raw_transaction reference. for ($i = 0; $i < $input_count; $i++) { // Load the TxID (32bytes) and vout (4bytes) $txid = self::_return_bytes($raw_transaction, 32, true); $vout = self::_return_bytes($raw_transaction, 4, true); // Script is prefixed with a varint that must be decoded. $script_length = self::_get_vint($raw_transaction); // decimal number of bytes. $script = self::_return_bytes($raw_transaction, $script_length); // Build input body depending on whether the TxIn is coinbase. if ($txid == '0000000000000000000000000000000000000000000000000000000000000000') { $input_body = array('coinbase' => $script); } else { $input_body = array('txid' => $txid, 'vout' => hexdec($vout), 'scriptSig' => array('asm' => self::_decode_script($script), 'hex' => $script)); } // Append a sequence number, and finally add the input to the array. $input_body['sequence'] = hexdec(self::_return_bytes($raw_transaction, 4)); $inputs[$i] = $input_body; } return $inputs; } /** * Encode Inputs * * Accepts a decoded $transaction['vin'] array as input: $vin. Also * requires $input count. * This function encodes the txid, vout, and script into hex format. * * @param array $vin * @param int $input_count * @return string */ public static function _encode_inputs($vin, $input_count) { $inputs = ''; for ($i = 0; $i < $input_count; $i++) { if (isset($vin[$i]['coinbase'])) { // Coinbase $txHash = '0000000000000000000000000000000000000000000000000000000000000000'; $vout = 'ffffffff'; $script_size = strlen($vin[$i]['coinbase']) / 2; // Decimal number of bytes $script_varint = self::_encode_vint($script_size); // Varint $scriptSig = $script_varint . $vin[$i]['coinbase']; } else { // Regular transaction $txHash = self::_flip_byte_order($vin[$i]['txid']); $vout = self::_dec_to_bytes($vin[$i]['vout'], 4, true); $script_size = strlen($vin[$i]['scriptSig']['hex']) / 2; // decimal number of bytes $script_varint = self::_encode_vint($script_size); // Create the varint encoding scripts length $scriptSig = $script_varint . $vin[$i]['scriptSig']['hex']; } // Add the sequence number. $sequence = self::_dec_to_bytes($vin[$i]['sequence'], 4, true); // Append this encoded input to the byte string. $inputs .= $txHash . $vout . $scriptSig . $sequence; } return $inputs; } /** * Decode scriptPubKey * * This function takes $script (hex) as an argument, and decodes an * script hex into an assembled human readable string. * * @param string $script * @param bool $matchBitcoinCore * @return string */ public static function _decode_scriptPubKey($script, $matchBitcoinCore = false) { $data = array(); while (strlen($script) !== 0) { $byteHex = self::_return_bytes($script, 1); $byteInt = hexdec($byteHex); if (isset(self::$op_code[$byteHex])) { // This checks if the OPCODE is defined from the list of constants. if ($matchBitcoinCore && self::$op_code[$byteHex] == "OP_0") { $data[] = '0'; } else if ($matchBitcoinCore && self::$op_code[$byteHex] == "OP_1") { $data[] = '1'; } else { $data[] = self::$op_code[$byteHex]; } } elseif ($byteInt >= 0x01 && $byteInt <= 0x4b) { // This checks if the OPCODE falls in the PUSHDATA range $data[] = self::_return_bytes($script, $byteInt); } elseif ($byteInt >= 0x51 && $byteInt <= 0x60) { // This checks if the CODE falls in the OP_X range $data[] = $matchBitcoinCore ? ($byteInt - 0x50) : 'OP_' . ($byteInt - 0x50); } else { throw new \RuntimeException("Failed to decode scriptPubKey"); } } return implode(" ", $data); } /** * Get Transaction Type * * This function takes a $data string, from a decoded scriptPubKey, * explodes it into an array of the operations/data. Returns FALSE if * the decoded scriptPubKey does not match against the definition of * any type of transaction. * Currently identifies pay-to-pubkey-hash and pay-to-script-hash. * * Transaction types are defined using the $define array, and * corresponding rules are build using the $rule array. The function * will attempt to create the address based on the transaction type * and $address_version byte. * * * @param string $data * @param string $magic_byte * @param string $magic_p2sh_byte * @return array|FALSE */ public static function _get_transaction_type($data, $magic_byte = null, $magic_p2sh_byte = null) { $magic_byte = BitcoinLib::magicByte($magic_byte); $magic_p2sh_byte = BitcoinLib::magicP2SHByte($magic_p2sh_byte); $data = explode(" ", $data); // Define information about eventual transactions cases, and // the position of the hash160 address in the stack. $define = array(); $rule = array(); // Standard: pay to pubkey hash $define['p2ph'] = array('type' => 'pubkeyhash', 'reqSigs' => 1, 'data_index_for_hash' => 2); $rule['p2ph'] = array( '0' => '/^OP_DUP/', '1' => '/^OP_HASH160/', '2' => '/^[0-9a-f]{40}$/i', // 2 '3' => '/^OP_EQUALVERIFY/', '4' => '/^OP_CHECKSIG/'); // Pay to script hash $define['p2sh'] = array('type' => 'scripthash', 'reqSigs' => 1, 'data_index_for_hash' => 1); $rule['p2sh'] = array( '0' => '/^OP_HASH160/', '1' => '/^[0-9a-f]{40}$/i', // pos 1 '2' => '/^OP_EQUAL/'); // Work out how many rules are applied in each case $valid = array(); foreach ($rule as $tx_type => $def) { $valid[$tx_type] = count($def); } // Attempt to validate against each of these rules. $matches = array(); foreach ($data as $index => $test) { foreach ($rule as $tx_type => $def) { $matches[$tx_type] = array(); if (isset($def[$index])) { preg_match($def[$index], $test, $matches[$tx_type]); if (count($matches[$tx_type]) == 1) { $valid[$tx_type]--; break; } } } } // Loop through rules, check if any transaction is a match. foreach ($rule as $tx_type => $def) { if ($valid[$tx_type] == 0) { // Load predefined info for this transaction type if detected. $return = $define[$tx_type]; $return['hash160'] = $data[$define[$tx_type]['data_index_for_hash']]; $return['addresses'][0] = BitcoinLib::hash160_to_address($return['hash160'], ($return['type'] == 'scripthash') ? $magic_p2sh_byte : $magic_byte); unset($return['data_index_for_hash']); } } return (!isset($return)) ? false : $return; } /** * Decode Outputs * * This function accepts $tx - a reference to the raw transaction being * decoded, and $output_count. Also accepts $address_version for when * dealing with networks besides bitcoin. * Returns FALSE if * * @param string $tx * @param int $output_count * @param string $magic_byte * @param string $magic_p2sh_byte * @return array|FALSE */ public static function _decode_outputs(&$tx, $output_count, $magic_byte = null, $magic_p2sh_byte = null) { $math = EccFactory::getAdapter(); $magic_byte = BitcoinLib::magicByte($magic_byte); $magic_p2sh_byte = BitcoinLib::magicP2SHByte($magic_p2sh_byte); $outputs = array(); for ($i = 0; $i < $output_count; $i++) { // Pop 8 bytes (flipped) from the $tx string, convert to decimal, // and then convert to Satoshis. $satoshis = $math->hexDec(self::_return_bytes($tx, 8, true)); // Decode the varint for the length of the scriptPubKey $script_length = self::_get_vint($tx); // decimal number of bytes $script = self::_return_bytes($tx, $script_length); try { $asm = self::_decode_scriptPubKey($script); } catch (\Exception $e) { $asm = null; } // Begin building scriptPubKey $scriptPubKey = array( 'asm' => $asm, 'hex' => $script ); // Try to decode the scriptPubKey['asm'] to learn the transaction type. $txn_info = self::_get_transaction_type($scriptPubKey['asm'], $magic_byte, $magic_p2sh_byte); if ($txn_info !== false) { $scriptPubKey = array_merge($scriptPubKey, $txn_info); } else { $scriptPubKey['message'] = 'unable to decode tx type!'; } $outputs[$i] = array( 'value' => $satoshis, 'vout' => $i, 'scriptPubKey' => $scriptPubKey); } return $outputs; } /** * Encode Outputs * * This function encodes $tx['vin'] array into hex format. Requires * the $vout_arr, and also $output_count - the number of outputs * this transaction has. * * @param array * @param int * @return string|FALSE */ public static function _encode_outputs($vout_arr, $output_count) { // If $vout_arr is empty, check if it's MEANT to be before failing. if (count($vout_arr) == 0) { return ($output_count == 0) ? '' : false; } $outputs = ''; for ($i = 0; $i < $output_count; $i++) { $satoshis = $vout_arr[$i]['value']; $amount = self::_dec_to_bytes($satoshis, 8); $amount = self::_flip_byte_order($amount); $script_size = strlen($vout_arr[$i]['scriptPubKey']['hex']) / 2; // number of bytes $script_varint = self::_encode_vint($script_size); $scriptPubKey = $vout_arr[$i]['scriptPubKey']['hex']; $outputs .= $amount . $script_varint . $scriptPubKey; } return $outputs; } /** * Decode * * A high-level function which takes $raw_transaction hex, and decodes * it into an array similar to that returned by bitcoind. * Accepts an optional $address_version for creating the addresses * - defaults to bitcoins version byte. * * @param string $raw_transaction * @param string $magic_byte * @param string $magic_p2sh_byte * @return array|FALSE */ public static function decode($raw_transaction, $magic_byte = null, $magic_p2sh_byte = null) { $math = EccFactory::getAdapter(); $magic_byte = BitcoinLib::magicByte($magic_byte); $magic_p2sh_byte = BitcoinLib::magicP2SHByte($magic_p2sh_byte); $raw_transaction = trim($raw_transaction); if (((bool)preg_match('/^[0-9a-fA-F]{2,}$/i', $raw_transaction) !== true) || (strlen($raw_transaction)) % 2 !== 0 ) { throw new \InvalidArgumentException("Raw transaction is invalid hex"); } $txHash = hash('sha256', hash('sha256', pack("H*", trim($raw_transaction)), true)); $txid = self::_flip_byte_order($txHash); $info = array(); $info['txid'] = $txid; $info['version'] = $math->hexDec(self::_return_bytes($raw_transaction, 4, true)); if (!in_array($info['version'], array('0', '1'))) { throw new \InvalidArgumentException("Invalid transaction version"); } $input_count = self::_get_vint($raw_transaction); if (!($input_count >= 0 && $input_count <= 4294967296)) { throw new \InvalidArgumentException("Invalid input count"); } $info['vin'] = self::_decode_inputs($raw_transaction, $input_count); if ($info['vin'] == false) { throw new \InvalidArgumentException("No inputs in transaction"); } $output_count = self::_get_vint($raw_transaction); if (!($output_count >= 0 && $output_count <= 4294967296)) { throw new \InvalidArgumentException("Invalid output count"); } $info['vout'] = self::_decode_outputs($raw_transaction, $output_count, $magic_byte, $magic_p2sh_byte); $info['locktime'] = $math->hexDec(self::_return_bytes($raw_transaction, 4)); return $info; } /** * Encode * * This function takes an array in a format similar to bitcoind's * (and compatible with the output of debug above) and re-encodes it * into a raw transaction hex string. * * @param array $raw_transaction_array * @return string */ public static function encode($raw_transaction_array) { $encoded_version = self::_dec_to_bytes($raw_transaction_array['version'], 4, true); // TRUE - get little endian // $encoded_inputs - set the encoded varint, then work out if any input hex is to be displayed. $decimal_inputs_count = count($raw_transaction_array['vin']); $encoded_inputs = self::_encode_vint($decimal_inputs_count) . (($decimal_inputs_count > 0) ? self::_encode_inputs($raw_transaction_array['vin'], $decimal_inputs_count) : ''); // $encoded_outputs - set varint, then work out if output hex is required. $decimal_outputs_count = count($raw_transaction_array['vout']); $encoded_outputs = self::_encode_vint($decimal_outputs_count) . (($decimal_inputs_count > 0) ? self::_encode_outputs($raw_transaction_array['vout'], $decimal_outputs_count) : ''); // Transaction locktime $encoded_locktime = self::_dec_to_bytes($raw_transaction_array['locktime'], 4, true); return $encoded_version . $encoded_inputs . $encoded_outputs . $encoded_locktime; } /** * Get the txid from the raw transaction hex * * @param $raw_transaction * @return string */ public static function txid_from_raw($raw_transaction) { return self::decode($raw_transaction)['txid']; } /** * Create Signature Hash * * This function accepts a $raw_transaction hex, and generates a hash * for each input, against which a signature and public key can be * verified. * See https://en.bitcoin.it/w/images/en/7/70/Bitcoin_OpCheckSig_InDetail.png * * If $specific_input is not set, then a hash will be generated for * each input, and these values returned as an array for comparison * during another script. * * @param string $raw_transaction * @param string $json_inputs * @param int $specific_input * @param array $e * @return string */ public static function _create_txin_signature_hash($raw_transaction, $json_inputs, $specific_input = -1, $e = null) { $decode = ($e == null) ? self::decode($raw_transaction) : $e; $inputs = (array)json_decode($json_inputs); if ($specific_input !== -1 && !is_numeric($specific_input)) { throw new \InvalidArgumentException("Specified input should be numeric"); } // Check that $raw_transaction and $json_inputs correspond to the right inputs $inputCount = count($decode['vin']); for ($i = 0; $i < $inputCount; $i++) { if (!isset($inputs[$i])) { throw new \InvalidArgumentException("Raw transaction does not match expected inputs"); } if ($decode['vin'][$i]['txid'] !== $inputs[$i]->txid || $decode['vin'][$i]['vout'] !== $inputs[$i]->vout ) { throw new \InvalidArgumentException("Raw transaction does not match expected inputs"); } } $sighashcode = '01000000'; if ($specific_input == -1) { // Return a hash for each input. $hash = array(); foreach ($decode['vin'] as $vin => $input) { $copy = $decode; foreach ($copy['vin'] as &$copy_input) { $copy_input['scriptSig']['hex'] = ''; } $copy['vin'][$vin]['scriptSig']['hex'] = (isset($inputs[$vin]->redeemScript)) ? $inputs[$vin]->redeemScript : $inputs[$vin]->scriptPubKey; // Encode the transaction, convert to a raw byte sting, // and calculate a double sha256 hash for this input. $hash[] = hash('sha256', hash('sha256', pack("H*", self::encode($copy) . $sighashcode), true)); } } else { // Return a message hash for the specified output. $copy = $decode; $copy['vin'][$specific_input]['scriptSig']['hex'] = (isset($inputs[$specific_input]->redeemScript)) ? $inputs[$specific_input]->redeemScript : $inputs[$specific_input]->scriptPubKey; $hash = hash('sha256', hash('sha256', pack("H*", self::encode($copy) . $sighashcode), true)); } return $hash; } /** * Check Sig * * This function will check a provided DER encoded $sig, a digest of * the message to be signed - $hash (the output of _create_txin_signature_hash()), * and the $key for the signature to be tested against. * Returns TRUE if the signature is valid for this $hash and $key, * otherwise returns FALSE. * * @param string $sig * @param string $hash * @param string $key * @param bool $allowHighS * @return bool */ public static function _check_sig($sig, $hash, $key, $allowHighS = self::ALLOW_HIGH_S) { $math = EccFactory::getAdapter(); $generator = EccFactory::getSecgCurves()->generator256k1(); $curve = $generator->getCurve(); $hash = $math->hexDec($hash); $decodedSignature = self::decode_signature($sig); $signature = new Signature($math->hexDec($decodedSignature['r']), $math->hexDec($decodedSignature['s'])); if (!$allowHighS) { // if S is > half then someone should have fixed it if (self::check_signature_is_high_s($signature)) { return false; } } if (strlen($key) == '66') { $decompress = BitcoinLib::decompress_public_key($key); $public_key_point = $decompress['point']; } else { $x = $math->hexDec(substr($key, 2, 64)); $y = $math->hexDec(substr($key, 66, 64)); $public_key_point = $curve->getPoint($x, $y); } $signer = new Signer($math); $public_key = new PublicKey($math, $generator, $public_key_point); return $signer->verify($public_key, $signature, $hash) == true; } public static function check_signature_is_high_s(Signature $signature) { $math = EccFactory::getAdapter(); $generator = EccFactory::getSecgCurves()->generator256k1(); $n = $generator->getOrder(); $against = $n; $against = $math->rightShift($against, 1); // if S is > half then someone should have substracted N return $math->cmp($signature->getS(), $against) > 0; } /** * Decode Redeem Script * * This recursive function extracts the m and n values for the * multisignature address, as well as the public keys. * Don't set $data. * * @param string $redeem_script * @param array $data * @return array */ public static function decode_redeem_script($redeem_script, $data = array()) { $math = EccFactory::getAdapter(); // If there is no more work to be done (script is fully parsed, return the array) if (strlen($redeem_script) == 0) { return $data; } // Fail if the redeem_script has an uneven number of characters. if (strlen($redeem_script) % 2 !== 0) { throw new \InvalidArgumentException("Redeem script is invalid hex"); } // First step is to get m, the required number of signatures if (!isset($data['m']) || count($data) == 0) { $data['m'] = (int) $math->sub($math->hexDec(substr($redeem_script, 0, 2)), $math->hexDec('50')); if ($data['m'] < 0 || $data['m'] > 20) { throw new \RuntimeException("Invalid redeem script - m must be >0 and <=20"); } $data['keys'] = array(); $redeem_script = substr($redeem_script, 2); } elseif (count($data['keys']) == 0 && !isset($data['next_key_charlen'])) { // Next is to find out the length of the following public key. $hex = substr($redeem_script, 0, 2); // Set up the length of the following key. $data['next_key_charlen'] = $math->mul(2, $math->hexDec($hex)); $redeem_script = substr($redeem_script, 2); } elseif (isset($data['next_key_charlen'])) { // Extract the key, and work out the next step for the code. $data['keys'][] = substr($redeem_script, 0, $data['next_key_charlen']); $next_op = substr($redeem_script, $data['next_key_charlen'], 2); $redeem_script = substr($redeem_script, ($data['next_key_charlen'] + 2)); unset($data['next_key_charlen']); // If 1 <= $next_op >= 4b : A key is coming up next. This if block runs again. if (in_array($math->cmp($math->hexDec($next_op), 1), array(0, 1)) && in_array($math->cmp($math->hexDec($next_op), $math->hexDec('4b')), array(-1, 0)) ) { // Set the next key character length $data['next_key_charlen'] = $math->mul(2, $math->hexDec($next_op)); // If 52 <= $next_op >= 60 : End of keys, now have n. } elseif (in_array($math->cmp($math->hexDec($next_op), $math->hexDec('51')), array(0, 1)) && in_array($math->cmp($math->hexDec($next_op), $math->hexDec('60')), array(-1, 0)) ) {
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
true
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/src/BIP39/BIP39EnglishWordList.php
src/BIP39/BIP39EnglishWordList.php
<?php namespace BitWasp\BitcoinLib\BIP39; /** * Class BIP39EnglishWordList * word list as defined here: https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt * * @package BitWasp\BitcoinLib\BIP39 */ class BIP39EnglishWordList extends BIP39WordList { protected $wordsFlipped; public function getWords() { return $this->words; } public function getWord($idx) { if (!isset($this->words)) { throw new \InvalidArgumentException(__CLASS__ . " does not contain a word for index [{$idx}]"); } return $this->words[$idx]; } public function getIndex($word) { // create a flipped word list to speed up the searching of words if ($this->wordsFlipped === null) { $this->wordsFlipped = array_flip($this->words); } if (!isset($this->wordsFlipped[$word])) { throw new \InvalidArgumentException(__CLASS__ . " does not contain word [{$word}]"); } return $this->wordsFlipped[$word]; } protected $words = array( "abandon", "ability", "able", "about", "above", "absent", "absorb", "abstract", "absurd", "abuse", "access", "accident", "account", "accuse", "achieve", "acid", "acoustic", "acquire", "across", "act", "action", "actor", "actress", "actual", "adapt", "add", "addict", "address", "adjust", "admit", "adult", "advance", "advice", "aerobic", "affair", "afford", "afraid", "again", "age", "agent", "agree", "ahead", "aim", "air", "airport", "aisle", "alarm", "album", "alcohol", "alert", "alien", "all", "alley", "allow", "almost", "alone", "alpha", "already", "also", "alter", "always", "amateur", "amazing", "among", "amount", "amused", "analyst", "anchor", "ancient", "anger", "angle", "angry", "animal", "ankle", "announce", "annual", "another", "answer", "antenna", "antique", "anxiety", "any", "apart", "apology", "appear", "apple", "approve", "april", "arch", "arctic", "area", "arena", "argue", "arm", "armed", "armor", "army", "around", "arrange", "arrest", "arrive", "arrow", "art", "artefact", "artist", "artwork", "ask", "aspect", "assault", "asset", "assist", "assume", "asthma", "athlete", "atom", "attack", "attend", "attitude", "attract", "auction", "audit", "august", "aunt", "author", "auto", "autumn", "average", "avocado", "avoid", "awake", "aware", "away", "awesome", "awful", "awkward", "axis", "baby", "bachelor", "bacon", "badge", "bag", "balance", "balcony", "ball", "bamboo", "banana", "banner", "bar", "barely", "bargain", "barrel", "base", "basic", "basket", "battle", "beach", "bean", "beauty", "because", "become", "beef", "before", "begin", "behave", "behind", "believe", "below", "belt", "bench", "benefit", "best", "betray", "better", "between", "beyond", "bicycle", "bid", "bike", "bind", "biology", "bird", "birth", "bitter", "black", "blade", "blame", "blanket", "blast", "bleak", "bless", "blind", "blood", "blossom", "blouse", "blue", "blur", "blush", "board", "boat", "body", "boil", "bomb", "bone", "bonus", "book", "boost", "border", "boring", "borrow", "boss", "bottom", "bounce", "box", "boy", "bracket", "brain", "brand", "brass", "brave", "bread", "breeze", "brick", "bridge", "brief", "bright", "bring", "brisk", "broccoli", "broken", "bronze", "broom", "brother", "brown", "brush", "bubble", "buddy", "budget", "buffalo", "build", "bulb", "bulk", "bullet", "bundle", "bunker", "burden", "burger", "burst", "bus", "business", "busy", "butter", "buyer", "buzz", "cabbage", "cabin", "cable", "cactus", "cage", "cake", "call", "calm", "camera", "camp", "can", "canal", "cancel", "candy", "cannon", "canoe", "canvas", "canyon", "capable", "capital", "captain", "car", "carbon", "card", "cargo", "carpet", "carry", "cart", "case", "cash", "casino", "castle", "casual", "cat", "catalog", "catch", "category", "cattle", "caught", "cause", "caution", "cave", "ceiling", "celery", "cement", "census", "century", "cereal", "certain", "chair", "chalk", "champion", "change", "chaos", "chapter", "charge", "chase", "chat", "cheap", "check", "cheese", "chef", "cherry", "chest", "chicken", "chief", "child", "chimney", "choice", "choose", "chronic", "chuckle", "chunk", "churn", "cigar", "cinnamon", "circle", "citizen", "city", "civil", "claim", "clap", "clarify", "claw", "clay", "clean", "clerk", "clever", "click", "client", "cliff", "climb", "clinic", "clip", "clock", "clog", "close", "cloth", "cloud", "clown", "club", "clump", "cluster", "clutch", "coach", "coast", "coconut", "code", "coffee", "coil", "coin", "collect", "color", "column", "combine", "come", "comfort", "comic", "common", "company", "concert", "conduct", "confirm", "congress", "connect", "consider", "control", "convince", "cook", "cool", "copper", "copy", "coral", "core", "corn", "correct", "cost", "cotton", "couch", "country", "couple", "course", "cousin", "cover", "coyote", "crack", "cradle", "craft", "cram", "crane", "crash", "crater", "crawl", "crazy", "cream", "credit", "creek", "crew", "cricket", "crime", "crisp", "critic", "crop", "cross", "crouch", "crowd", "crucial", "cruel", "cruise", "crumble", "crunch", "crush", "cry", "crystal", "cube", "culture", "cup", "cupboard", "curious", "current", "curtain", "curve", "cushion", "custom", "cute", "cycle", "dad", "damage", "damp", "dance", "danger", "daring", "dash", "daughter", "dawn", "day", "deal", "debate", "debris", "decade", "december", "decide", "decline", "decorate", "decrease", "deer", "defense", "define", "defy", "degree", "delay", "deliver", "demand", "demise", "denial", "dentist", "deny", "depart", "depend", "deposit", "depth", "deputy", "derive", "describe", "desert", "design", "desk", "despair", "destroy", "detail", "detect", "develop", "device", "devote", "diagram", "dial", "diamond", "diary", "dice", "diesel", "diet", "differ", "digital", "dignity", "dilemma", "dinner", "dinosaur", "direct", "dirt", "disagree", "discover", "disease", "dish", "dismiss", "disorder", "display", "distance", "divert", "divide", "divorce", "dizzy", "doctor", "document", "dog", "doll", "dolphin", "domain", "donate", "donkey", "donor", "door", "dose", "double", "dove", "draft", "dragon", "drama", "drastic", "draw", "dream", "dress", "drift", "drill", "drink", "drip", "drive", "drop", "drum", "dry", "duck", "dumb", "dune", "during", "dust", "dutch", "duty", "dwarf", "dynamic", "eager", "eagle", "early", "earn", "earth", "easily", "east", "easy", "echo", "ecology", "economy", "edge", "edit", "educate", "effort", "egg", "eight", "either", "elbow", "elder", "electric", "elegant", "element", "elephant", "elevator", "elite", "else", "embark", "embody", "embrace", "emerge", "emotion", "employ", "empower", "empty", "enable", "enact", "end", "endless", "endorse", "enemy", "energy", "enforce", "engage", "engine", "enhance", "enjoy", "enlist", "enough", "enrich", "enroll", "ensure", "enter", "entire", "entry", "envelope", "episode", "equal", "equip", "era", "erase", "erode", "erosion", "error", "erupt", "escape", "essay", "essence", "estate", "eternal", "ethics", "evidence", "evil", "evoke", "evolve", "exact", "example", "excess", "exchange", "excite", "exclude", "excuse", "execute", "exercise", "exhaust", "exhibit", "exile", "exist", "exit", "exotic", "expand", "expect", "expire", "explain", "expose", "express", "extend", "extra", "eye", "eyebrow", "fabric", "face", "faculty", "fade", "faint", "faith", "fall", "false", "fame", "family", "famous", "fan", "fancy", "fantasy", "farm", "fashion", "fat", "fatal", "father", "fatigue", "fault", "favorite", "feature", "february", "federal", "fee", "feed", "feel", "female", "fence", "festival", "fetch", "fever", "few", "fiber", "fiction", "field", "figure", "file", "film", "filter", "final", "find", "fine", "finger", "finish", "fire", "firm", "first", "fiscal", "fish", "fit", "fitness", "fix", "flag", "flame", "flash", "flat", "flavor", "flee", "flight", "flip", "float", "flock", "floor", "flower", "fluid", "flush", "fly", "foam", "focus", "fog", "foil", "fold", "follow", "food", "foot", "force", "forest", "forget", "fork", "fortune", "forum", "forward", "fossil", "foster", "found", "fox", "fragile", "frame", "frequent", "fresh", "friend", "fringe", "frog", "front", "frost", "frown", "frozen", "fruit", "fuel", "fun", "funny", "furnace", "fury", "future", "gadget", "gain", "galaxy", "gallery", "game", "gap", "garage", "garbage", "garden", "garlic", "garment", "gas", "gasp", "gate", "gather", "gauge", "gaze", "general", "genius", "genre", "gentle", "genuine", "gesture", "ghost", "giant", "gift", "giggle", "ginger", "giraffe", "girl", "give", "glad", "glance", "glare", "glass", "glide", "glimpse", "globe", "gloom", "glory", "glove", "glow", "glue", "goat", "goddess", "gold", "good", "goose", "gorilla", "gospel", "gossip", "govern", "gown", "grab", "grace", "grain", "grant", "grape", "grass", "gravity", "great", "green", "grid", "grief", "grit", "grocery", "group", "grow", "grunt", "guard", "guess", "guide", "guilt", "guitar", "gun", "gym", "habit", "hair", "half", "hammer", "hamster", "hand", "happy", "harbor", "hard", "harsh", "harvest", "hat", "have", "hawk", "hazard", "head", "health", "heart", "heavy", "hedgehog", "height", "hello", "helmet", "help", "hen", "hero", "hidden", "high", "hill", "hint", "hip", "hire", "history", "hobby", "hockey", "hold", "hole", "holiday", "hollow", "home", "honey", "hood", "hope", "horn", "horror", "horse", "hospital", "host", "hotel", "hour", "hover", "hub", "huge", "human", "humble", "humor", "hundred", "hungry", "hunt", "hurdle", "hurry", "hurt", "husband", "hybrid", "ice", "icon", "idea", "identify", "idle", "ignore", "ill", "illegal", "illness", "image", "imitate", "immense", "immune", "impact", "impose", "improve", "impulse", "inch", "include", "income", "increase", "index", "indicate", "indoor", "industry", "infant", "inflict", "inform", "inhale", "inherit", "initial", "inject", "injury", "inmate", "inner", "innocent", "input", "inquiry", "insane", "insect", "inside", "inspire", "install", "intact", "interest", "into", "invest", "invite", "involve", "iron", "island", "isolate", "issue", "item", "ivory", "jacket", "jaguar", "jar", "jazz", "jealous", "jeans", "jelly", "jewel", "job", "join", "joke", "journey", "joy", "judge", "juice", "jump", "jungle", "junior", "junk", "just", "kangaroo", "keen", "keep", "ketchup", "key", "kick", "kid", "kidney", "kind", "kingdom", "kiss", "kit", "kitchen", "kite", "kitten", "kiwi", "knee", "knife", "knock", "know", "lab", "label", "labor", "ladder", "lady", "lake", "lamp", "language", "laptop", "large", "later", "latin", "laugh", "laundry", "lava", "law", "lawn", "lawsuit", "layer", "lazy", "leader", "leaf", "learn", "leave", "lecture", "left", "leg", "legal", "legend", "leisure", "lemon", "lend", "length", "lens", "leopard", "lesson", "letter", "level", "liar", "liberty", "library", "license", "life", "lift", "light", "like", "limb", "limit", "link", "lion", "liquid", "list", "little", "live", "lizard", "load", "loan", "lobster", "local", "lock", "logic", "lonely", "long", "loop", "lottery", "loud", "lounge", "love", "loyal", "lucky", "luggage", "lumber", "lunar", "lunch", "luxury", "lyrics", "machine", "mad", "magic", "magnet", "maid", "mail", "main", "major", "make", "mammal", "man", "manage", "mandate", "mango", "mansion", "manual", "maple", "marble", "march", "margin", "marine", "market", "marriage", "mask", "mass", "master", "match", "material", "math", "matrix", "matter", "maximum", "maze", "meadow", "mean", "measure", "meat", "mechanic", "medal", "media", "melody", "melt", "member", "memory", "mention", "menu", "mercy", "merge", "merit", "merry", "mesh", "message", "metal", "method", "middle", "midnight", "milk", "million", "mimic", "mind", "minimum", "minor", "minute", "miracle", "mirror", "misery", "miss", "mistake", "mix", "mixed", "mixture", "mobile", "model", "modify", "mom", "moment", "monitor", "monkey", "monster", "month", "moon", "moral", "more", "morning", "mosquito", "mother", "motion", "motor", "mountain", "mouse", "move", "movie", "much", "muffin", "mule", "multiply", "muscle", "museum", "mushroom", "music", "must", "mutual", "myself", "mystery", "myth", "naive", "name", "napkin", "narrow", "nasty", "nation", "nature", "near", "neck", "need", "negative", "neglect", "neither", "nephew", "nerve", "nest", "net", "network", "neutral", "never", "news", "next", "nice", "night", "noble", "noise", "nominee", "noodle", "normal", "north", "nose", "notable", "note", "nothing", "notice", "novel", "now", "nuclear", "number", "nurse", "nut", "oak", "obey", "object", "oblige", "obscure", "observe", "obtain", "obvious", "occur", "ocean", "october", "odor", "off", "offer", "office", "often", "oil", "okay", "old", "olive", "olympic", "omit", "once", "one", "onion", "online", "only", "open", "opera", "opinion", "oppose", "option", "orange", "orbit", "orchard", "order", "ordinary", "organ", "orient", "original", "orphan", "ostrich", "other", "outdoor", "outer", "output", "outside", "oval", "oven", "over", "own", "owner", "oxygen", "oyster", "ozone", "pact", "paddle", "page", "pair", "palace", "palm", "panda", "panel", "panic", "panther", "paper", "parade", "parent", "park", "parrot", "party", "pass", "patch", "path", "patient", "patrol", "pattern", "pause", "pave", "payment", "peace", "peanut", "pear", "peasant", "pelican", "pen", "penalty", "pencil", "people", "pepper", "perfect", "permit", "person", "pet", "phone", "photo", "phrase", "physical", "piano", "picnic", "picture", "piece", "pig", "pigeon", "pill", "pilot", "pink", "pioneer", "pipe", "pistol", "pitch", "pizza", "place", "planet", "plastic", "plate", "play", "please", "pledge", "pluck", "plug", "plunge", "poem", "poet", "point", "polar", "pole", "police", "pond", "pony", "pool", "popular", "portion", "position", "possible", "post", "potato", "pottery", "poverty", "powder", "power", "practice", "praise", "predict", "prefer", "prepare", "present", "pretty", "prevent", "price", "pride", "primary", "print", "priority", "prison", "private", "prize", "problem", "process", "produce", "profit", "program", "project", "promote", "proof", "property", "prosper", "protect", "proud", "provide", "public", "pudding", "pull", "pulp", "pulse", "pumpkin", "punch", "pupil", "puppy", "purchase", "purity", "purpose", "purse", "push", "put", "puzzle", "pyramid", "quality", "quantum", "quarter", "question", "quick", "quit", "quiz", "quote", "rabbit", "raccoon", "race", "rack", "radar", "radio", "rail", "rain", "raise", "rally", "ramp", "ranch", "random", "range", "rapid", "rare", "rate", "rather", "raven", "raw", "razor", "ready", "real", "reason", "rebel", "rebuild", "recall", "receive", "recipe", "record", "recycle", "reduce", "reflect", "reform", "refuse", "region", "regret", "regular", "reject", "relax", "release", "relief", "rely", "remain", "remember", "remind", "remove", "render", "renew", "rent", "reopen", "repair", "repeat", "replace", "report", "require", "rescue", "resemble", "resist", "resource", "response", "result", "retire", "retreat", "return", "reunion", "reveal", "review", "reward", "rhythm", "rib", "ribbon", "rice", "rich", "ride", "ridge", "rifle", "right", "rigid", "ring", "riot", "ripple", "risk", "ritual", "rival", "river", "road", "roast", "robot", "robust", "rocket", "romance", "roof", "rookie", "room", "rose", "rotate", "rough", "round", "route", "royal", "rubber", "rude", "rug", "rule", "run", "runway", "rural", "sad", "saddle", "sadness", "safe", "sail", "salad", "salmon", "salon", "salt", "salute", "same", "sample", "sand", "satisfy", "satoshi", "sauce", "sausage", "save", "say", "scale", "scan", "scare", "scatter", "scene", "scheme", "school", "science", "scissors", "scorpion", "scout", "scrap", "screen", "script", "scrub", "sea", "search", "season", "seat", "second", "secret", "section", "security", "seed", "seek", "segment", "select", "sell", "seminar", "senior", "sense", "sentence", "series", "service", "session", "settle", "setup", "seven", "shadow", "shaft", "shallow", "share", "shed", "shell", "sheriff", "shield", "shift", "shine", "ship", "shiver", "shock", "shoe", "shoot", "shop", "short", "shoulder", "shove", "shrimp", "shrug", "shuffle", "shy", "sibling", "sick", "side", "siege", "sight", "sign", "silent", "silk", "silly", "silver", "similar", "simple", "since", "sing", "siren", "sister", "situate", "six", "size", "skate", "sketch", "ski", "skill", "skin", "skirt", "skull", "slab", "slam", "sleep", "slender", "slice", "slide", "slight", "slim", "slogan", "slot", "slow", "slush", "small", "smart", "smile", "smoke", "smooth", "snack", "snake", "snap", "sniff", "snow", "soap", "soccer", "social", "sock", "soda", "soft", "solar", "soldier", "solid", "solution", "solve", "someone", "song", "soon", "sorry", "sort", "soul", "sound", "soup", "source", "south", "space", "spare", "spatial", "spawn", "speak", "special", "speed", "spell", "spend", "sphere", "spice", "spider", "spike", "spin", "spirit", "split", "spoil", "sponsor", "spoon", "sport", "spot", "spray", "spread", "spring", "spy", "square", "squeeze", "squirrel", "stable", "stadium", "staff", "stage", "stairs", "stamp", "stand", "start", "state", "stay", "steak", "steel", "stem", "step", "stereo", "stick", "still", "sting", "stock", "stomach", "stone", "stool", "story", "stove", "strategy", "street", "strike", "strong", "struggle", "student", "stuff", "stumble", "style", "subject", "submit", "subway", "success", "such", "sudden", "suffer", "sugar", "suggest", "suit", "summer", "sun", "sunny", "sunset", "super", "supply", "supreme", "sure", "surface", "surge", "surprise", "surround", "survey", "suspect", "sustain", "swallow", "swamp", "swap", "swarm", "swear", "sweet", "swift", "swim", "swing", "switch", "sword", "symbol", "symptom", "syrup", "system", "table", "tackle", "tag", "tail", "talent", "talk", "tank", "tape", "target", "task", "taste", "tattoo", "taxi", "teach", "team", "tell", "ten", "tenant", "tennis", "tent", "term", "test", "text", "thank", "that", "theme", "then", "theory", "there", "they", "thing", "this", "thought", "three", "thrive", "throw", "thumb", "thunder", "ticket", "tide", "tiger", "tilt", "timber", "time", "tiny", "tip", "tired", "tissue", "title", "toast", "tobacco",
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
true
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/src/BIP39/BIP39WordList.php
src/BIP39/BIP39WordList.php
<?php namespace BitWasp\BitcoinLib\BIP39; abstract class BIP39WordList { /** * get a list of all the words * * @return array */ abstract public function getWords(); /** * get a word by it's index * * should throw an exception if the index does not exist * * @param int $idx * @return string */ abstract public function getWord($idx); /** * get the index for a word * * should throw an exception if the word does not exist * * @param string $word * @return int */ abstract public function getIndex($word); }
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/src/BIP39/BIP39.php
src/BIP39/BIP39.php
<?php namespace BitWasp\BitcoinLib\BIP39; class BIP39 { protected static $defaultWordList; /** * generate random entropy using \MCRYPT_DEV_URANDOM * * @param int $size desired strength, must be multiple of 32, recommended 128-256 * @throws \Exception * @return string hex Entropy */ public static function generateEntropy($size = 256) { if ($size % 32 !== 0) { throw new \InvalidArgumentException("Entropy must be in a multiple of 32"); } return bin2hex(mcrypt_create_iv($size / 8, \MCRYPT_DEV_URANDOM)); } /** * create Mnemonic from Entropy * * @param string $entropyHex hex Entropy * @param BIP39WordList $wordList defaults to BIP39 english word list * @return string hex Mnemonic * @throws \Exception */ public static function entropyToMnemonic($entropyHex, BIP39WordList $wordList = null) { // calculate entropy, /2 because PHP can't do bytes $ENT = (strlen($entropyHex) / 2) * 8; // calculate how long the checksum should be $CS = $ENT / 32; // get the checksum $checksum = self::entropyChecksum($entropyHex); // create the string of bits to use $bits = str_pad(gmp_strval(gmp_init($entropyHex, 16), 2) . $checksum, $ENT + $CS, "0", STR_PAD_LEFT); // PHP trims off 0s // use provided wordList or default $wordList = $wordList ?: self::defaultWordList(); // build word list $result = array(); foreach (str_split($bits, 11) as $bit) { $idx = gmp_strval(gmp_init($bit, 2), 10); $result[] = $wordList->getWord($idx); } // implode and enjoy $result = implode(" ", $result); return $result; } /** * create Checksum from Entropy * * @param string $entropyHex hex Entropy * @return string bits checksum */ protected static function entropyChecksum($entropyHex) { // calculate entropy, /2 because PHP can't do bytes $ENT = (strlen($entropyHex) / 2) * 8; // calculate how long the checksum should be $CS = $ENT / 32; $hashHex = hash("sha256", hex2bin($entropyHex)); // create full checksum $hashBits = gmp_strval(gmp_init($hashHex, 16), 2); $hashBits = str_pad($hashBits, 256, "0", STR_PAD_LEFT); // PHP trims off 0s // take only the bits we need $checksum = substr($hashBits, 0, $CS); return $checksum; } /** * create Entropy from Mnemonic * * @param string $mnemonic hex Mnemonic * @param BIP39WordList $wordList defaults to BIP39 english word list * @return string hex Entropy * @throws \Exception */ public static function mnemonicToEntropy($mnemonic, BIP39WordList $wordList = null) { $words = explode(" ", $mnemonic); if (count($words) % 3 !== 0) { throw new \InvalidArgumentException("Invalid mnemonic"); } // wordList or default $wordList = $wordList ?: self::defaultWordList(); // convert the words back into bit strings $bits = array(); foreach ($words as $word) { $idx = $wordList->getIndex($word); $bits[] = str_pad(gmp_strval(gmp_init($idx, 10), 2), 11, "0", STR_PAD_LEFT); // PHP trims off 0s } // implode the bitstring to it's original form $bits = implode("", $bits); // calculate how long the checksum should be $CS = strlen($bits) / 33; // calculate how long the original entropy should be $ENT = strlen($bits) - $CS; // get the checksum and the original entropy $checksum = substr($bits, -1 * $CS); $entropyBits = substr($bits, 0, -1 * $CS); // recreate the hex for the entropy $entropyHex = str_pad(gmp_strval(gmp_init($entropyBits, 2), 16), ($ENT * 2) / 8, "0", STR_PAD_LEFT); // PHP trims off 0s // validate if ($checksum !== self::entropyChecksum($entropyHex)) { throw new \InvalidArgumentException("Checksum does not match!"); } return $entropyHex; } /** * create Seed from Mnemonic and Passphrase * * @param string $mnemonic hex Mnemonic * @param string $passphrase * @return mixed * @throws \Exception */ public static function mnemonicToSeedHex($mnemonic, $passphrase) { $passphrase = self::normalizePassphrase($passphrase); $salt = "mnemonic" . $passphrase; return hash_pbkdf2("sha512", $mnemonic, $salt, 2048, 64 * 2, false); } /** * normalize Passphrase if it's UTF-8 * * requires the Normalizer class from the PECL intl extension * so if the Passphrase is UTF-8 and the class isn't there we throw an error! * * @param string $passphrase * @return string * @throws \Exception */ public static function normalizePassphrase($passphrase) { if (!class_exists('Normalizer')) { if (mb_detect_encoding($passphrase) == "UTF-8") { throw new \Exception("UTF-8 passphrase is not supported without the PECL intl extension installed."); } else { return $passphrase; } } return \Normalizer::normalize($passphrase, \Normalizer::FORM_KD); } /** * get the default (english BIP39) word list * * @return BIP39EnglishWordList */ public static function defaultWordList() { if (self::$defaultWordList === null) { self::$defaultWordList = new BIP39EnglishWordList(); } return self::$defaultWordList; } }
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/tests/BIP32Test.php
tests/BIP32Test.php
<?php use BitWasp\BitcoinLib\BIP32; use BitWasp\BitcoinLib\BitcoinLib; /** * test vectors generated/verified using http://bip32.org/ * * Class BIP32Test */ class BIP32Test extends PHPUnit_Framework_TestCase { public function __construct() { } public function setup() { // ensure we're set to bitcoin and not bitcoin-testnet BitcoinLib::setMagicByteDefaults('bitcoin'); } public function tearDown() { } public function testDefinitionTuple() { $masterKey = BIP32::master_key("000102030405060708090a0b0c0d0e0f", "bitcoin", false); $this->assertEquals("00000003", BIP32::calc_address_bytes("3", false)); $this->assertEquals("80000003", BIP32::calc_address_bytes("3", true)); $this->assertEquals("00000003", BIP32::calc_address_bytes("3'", false)); $this->assertEquals("80000003", BIP32::calc_address_bytes("3'", true)); $this->assertEquals( [ "00000003", "00000003", "00000003", "00000000", ], BIP32::get_definition_tuple($masterKey[0], "m/3/3/3") ); $this->assertEquals( [ "00000003", "80000003", "00000003", "00000000", ], BIP32::get_definition_tuple($masterKey[0], "m/3/3'/3") ); } public function testCKD() { // create master key $masterKey = BIP32::master_key("000102030405060708090a0b0c0d0e0f", "bitcoin", false); $this->assertEquals("m", $masterKey[1]); $this->assertEquals("xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi", $masterKey[0]); // get the "m" derivation, should be equal to the master key, by absolute path $sameMasterKey = BIP32::build_key($masterKey, "m"); $this->assertEquals("m", $sameMasterKey[1]); $this->assertEquals("xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi", $sameMasterKey[0]); // get the "m/0" derivation, should be the first child, by absolute path $firstChildKey = BIP32::build_key($masterKey, "m/0"); $this->assertEquals("m/0", $firstChildKey[1]); $this->assertEquals("xprv9uHRZZhbkedL37eZEnyrNsQPFZYRAvjy5rt6M1nbEkLSo378x1CQQLo2xxBvREwiK6kqf7GRNvsNEchwibzXaV6i5GcsgyjBeRguXhKsi4R", $firstChildKey[0]); // get the "m/0" derivation, should be the first child, by relative path $firstChildKey = BIP32::build_key($masterKey, "0"); $this->assertEquals("m/0", $firstChildKey[1]); $this->assertEquals("xprv9uHRZZhbkedL37eZEnyrNsQPFZYRAvjy5rt6M1nbEkLSo378x1CQQLo2xxBvREwiK6kqf7GRNvsNEchwibzXaV6i5GcsgyjBeRguXhKsi4R", $firstChildKey[0]); // get the "m/0" derivation, should be the first child, by relative path, by only providing the key and not the original path $firstChildKey = BIP32::build_key($masterKey[0], "0"); $this->assertEquals("m/0", $firstChildKey[1]); $this->assertEquals("xprv9uHRZZhbkedL37eZEnyrNsQPFZYRAvjy5rt6M1nbEkLSo378x1CQQLo2xxBvREwiK6kqf7GRNvsNEchwibzXaV6i5GcsgyjBeRguXhKsi4R", $firstChildKey[0]); // get the "m/0" derivation, should be the first child, by absolute path, by only providing the key and not the original path $firstChildKey = BIP32::build_key($masterKey[0], "m/0"); $this->assertEquals("m/0", $firstChildKey[1]); $this->assertEquals("xprv9uHRZZhbkedL37eZEnyrNsQPFZYRAvjy5rt6M1nbEkLSo378x1CQQLo2xxBvREwiK6kqf7GRNvsNEchwibzXaV6i5GcsgyjBeRguXhKsi4R", $firstChildKey[0]); // get the "m/44'/0'/0'/0/0" derivation, by absolute path $bip44ChildKey = BIP32::build_key($masterKey, "m/44'/0'/0'/0/0"); $this->assertEquals("m/44'/0'/0'/0/0", $bip44ChildKey[1]); $this->assertEquals("xprvA4A9CuBXhdBtCaLxwrw64Jaran4n1rgzeS5mjH47Ds8V67uZS8tTkG8jV3BZi83QqYXPcN4v8EjK2Aof4YcEeqLt688mV57gF4j6QZWdP9U", $bip44ChildKey[0]); // get the "m/44'/0'/0'/0/0" derivation, by relative path, in 2 steps $bip44ChildKey = BIP32::build_key($masterKey, "44'/0'"); $bip44ChildKey = BIP32::build_key($bip44ChildKey, "0'/0/0"); $this->assertEquals("m/44'/0'/0'/0/0", $bip44ChildKey[1]); $this->assertEquals("xprvA4A9CuBXhdBtCaLxwrw64Jaran4n1rgzeS5mjH47Ds8V67uZS8tTkG8jV3BZi83QqYXPcN4v8EjK2Aof4YcEeqLt688mV57gF4j6QZWdP9U", $bip44ChildKey[0]); // get the "m/44'/0'/0'/0/0" derivation, by relative path, in 2 steps $bip44ChildKey = BIP32::build_key($masterKey, "44'/0'/0'"); $bip44ChildKey = BIP32::build_key($bip44ChildKey, "0/0"); $this->assertEquals("m/44'/0'/0'/0/0", $bip44ChildKey[1]); $this->assertEquals("xprvA4A9CuBXhdBtCaLxwrw64Jaran4n1rgzeS5mjH47Ds8V67uZS8tTkG8jV3BZi83QqYXPcN4v8EjK2Aof4YcEeqLt688mV57gF4j6QZWdP9U", $bip44ChildKey[0]); // get the "m/44'/0'/0'/0/0" derivation, by relative path, in 2 steps $bip44ChildKey = BIP32::build_key($masterKey, "44'/0'/0'/0"); $bip44ChildKey = BIP32::build_key($bip44ChildKey, "0"); $this->assertEquals("m/44'/0'/0'/0/0", $bip44ChildKey[1]); $this->assertEquals("xprvA4A9CuBXhdBtCaLxwrw64Jaran4n1rgzeS5mjH47Ds8V67uZS8tTkG8jV3BZi83QqYXPcN4v8EjK2Aof4YcEeqLt688mV57gF4j6QZWdP9U", $bip44ChildKey[0]); // get the "m/44'/0'/0'/0/0" derivation, by relative path, in single steps $bip44ChildKey = BIP32::build_key($masterKey, "44'"); $bip44ChildKey = BIP32::build_key($bip44ChildKey, "0'"); $bip44ChildKey = BIP32::build_key($bip44ChildKey, "0'"); $bip44ChildKey = BIP32::build_key($bip44ChildKey, "0"); $bip44ChildKey = BIP32::build_key($bip44ChildKey, "0"); $this->assertEquals("m/44'/0'/0'/0/0", $bip44ChildKey[1]); $this->assertEquals("xprvA4A9CuBXhdBtCaLxwrw64Jaran4n1rgzeS5mjH47Ds8V67uZS8tTkG8jV3BZi83QqYXPcN4v8EjK2Aof4YcEeqLt688mV57gF4j6QZWdP9U", $bip44ChildKey[0]); // we're expecting an exception $e = null; try { $bip44ChildKey = BIP32::build_key($masterKey, "m/44'/0'/0'/0/0"); BIP32::build_key($bip44ChildKey, "m/44'/1'/0'/0/0"); } catch (\Exception $e) { } $this->assertTrue(!!$e, "build_key should throw exception with bad path"); } public function testCKDPrivateToPublic() { // create master key $masterKey = BIP32::master_key("000102030405060708090a0b0c0d0e0f", "bitcoin", false); $this->assertEquals("m", $masterKey[1]); $this->assertEquals("xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi", $masterKey[0]); // get the "m" derivation, should be equal to the master key, by absolute path $pubMasterKey = BIP32::build_key($masterKey, "M"); $this->assertEquals("M", $pubMasterKey[1]); $this->assertEquals("xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8", $pubMasterKey[0]); // get the "M/0" derivation, should be the first child, by absolute path $firstChildKey = BIP32::build_key($masterKey, "M/0"); $this->assertEquals("M/0", $firstChildKey[1]); $this->assertEquals("xpub68Gmy5EVb2BdFbj2LpWrk1M7obNuaPTpT5oh9QCCo5sRfqSHVYWex97WpDZzszdzHzxXDAzPLVSwybe4uPYkSk4G3gnrPqqkV9RyNzAcNJ1", $firstChildKey[0]); // get the "m/0" derivation, should be the first child, by absolute path, by only providing the key and not the original path $firstChildKey = BIP32::build_key($masterKey[0], "M/0"); $this->assertEquals("M/0", $firstChildKey[1]); $this->assertEquals("xpub68Gmy5EVb2BdFbj2LpWrk1M7obNuaPTpT5oh9QCCo5sRfqSHVYWex97WpDZzszdzHzxXDAzPLVSwybe4uPYkSk4G3gnrPqqkV9RyNzAcNJ1", $firstChildKey[0]); // get the "M/44'/0'/0'/0/0" derivation, by absolute path $bip44ChildKey = BIP32::build_key($masterKey, "M/44'/0'/0'/0/0"); $this->assertEquals("M/44'/0'/0'/0/0", $bip44ChildKey[1]); $this->assertEquals("xpub6H9VcQiRXzkBR4RS3tU6RSXb8ouGRKQr1f1NXfTinCfTxvEhygCiJ4TDLHz1dyQ6d2Vz8Ne7eezkrViwaPo2ZMsNjVtFwvzsQXCDV6HJ3cV", $bip44ChildKey[0]); // get the "M/44'/0'/0'/0/0" derivation, by relative path, in 2 steps $bip44ChildKey = BIP32::build_key($masterKey, "M/44'/0'/0'"); $bip44ChildKey = BIP32::build_key($bip44ChildKey, "0/0"); $this->assertEquals("M/44'/0'/0'/0/0", $bip44ChildKey[1]); $this->assertEquals("xpub6H9VcQiRXzkBR4RS3tU6RSXb8ouGRKQr1f1NXfTinCfTxvEhygCiJ4TDLHz1dyQ6d2Vz8Ne7eezkrViwaPo2ZMsNjVtFwvzsQXCDV6HJ3cV", $bip44ChildKey[0]); // get the "M/44'/0'/0'/0/0" derivation, by relative path, in 2 steps $bip44ChildKey = BIP32::build_key($masterKey, "M/44'/0'/0'/0"); $bip44ChildKey = BIP32::build_key($bip44ChildKey, "0"); $this->assertEquals("M/44'/0'/0'/0/0", $bip44ChildKey[1]); $this->assertEquals("xpub6H9VcQiRXzkBR4RS3tU6RSXb8ouGRKQr1f1NXfTinCfTxvEhygCiJ4TDLHz1dyQ6d2Vz8Ne7eezkrViwaPo2ZMsNjVtFwvzsQXCDV6HJ3cV", $bip44ChildKey[0]); // get the "M/44'/0'/0'/0/0" derivation, by relative path, in single steps $bip44ChildKey = BIP32::build_key($masterKey, "m/44'"); $bip44ChildKey = BIP32::build_key($bip44ChildKey, "0'"); $bip44ChildKey = BIP32::build_key($bip44ChildKey, "0'"); $bip44ChildKey = BIP32::build_key($bip44ChildKey, "0"); $bip44ChildKey = BIP32::build_key($bip44ChildKey, "0"); $bip44ChildKey = BIP32::extended_private_to_public($bip44ChildKey); $this->assertEquals("M/44'/0'/0'/0/0", $bip44ChildKey[1]); $this->assertEquals("xpub6H9VcQiRXzkBR4RS3tU6RSXb8ouGRKQr1f1NXfTinCfTxvEhygCiJ4TDLHz1dyQ6d2Vz8Ne7eezkrViwaPo2ZMsNjVtFwvzsQXCDV6HJ3cV", $bip44ChildKey[0]); // we're expecting an exception $e = null; try { $bip44ChildKey = BIP32::build_key($masterKey, "M/44'/0'"); $bip44ChildKey = BIP32::build_key($bip44ChildKey, "0'"); } catch (\Exception $e) { } $this->assertTrue(!!$e, "build_key should throw exception with bad path"); } public function testMasterKeyFromSeed() { $intended_pub = 'xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8'; $intended_priv = 'xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi'; $master = BIP32::master_key('000102030405060708090a0b0c0d0e0f'); $this->assertEquals($master[0], $intended_priv); $public = BIP32::extended_private_to_public($master); $this->assertEquals($public[0], $intended_pub); } public function __helpTestChildKeyDerivation() { } public function testChildKeyDerivationOne() { $test_vectors = [ 0 => [ 'master' => '000102030405060708090a0b0c0d0e0f', 'ckd' => [ 0 => [ 'child' => "0'", 'priv' => 'xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7', 'pub' => 'xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw' ], 1 => [ 'child' => '1', 'priv' => 'xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs', 'pub' => 'xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ' ], 2 => [ 'child' => "2'", 'priv' => 'xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM', 'pub' => 'xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5' ], 3 => [ 'child' => '2', 'priv' => 'xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334', 'pub' => 'xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV' ], 4 => [ 'child' => '1000000000', 'priv' => 'xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76', 'pub' => 'xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy' ] ] ], 1 => [ 'master' => 'fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542', 'ckd' => [ 0 => [ 'child' => "0", 'priv' => 'xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt', 'pub' => 'xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH' ], 1 => [ 'child' => "2147483647'", 'priv' => 'xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9', 'pub' => 'xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a' ], 2 => [ 'child' => "1", 'priv' => 'xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef', 'pub' => 'xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon' ], 3 => [ 'child' => "2147483646'", 'priv' => 'xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc', 'pub' => 'xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL' ], 4 => [ 'child' => '2', 'priv' => 'xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j', 'pub' => 'xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt' ] ] ] ]; foreach ($test_vectors as $test => $vector) { $master = BIP32::master_key($vector['master']); $key = $master; foreach ($vector['ckd'] as $test_array) { $key = BIP32::build_key($key, $test_array['child']); $this->assertEquals($key[0], $test_array['priv']); $pub = BIP32::extended_private_to_public($key); $this->assertEquals($pub[0], $test_array['pub']); } } } } ;
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/tests/AgainstRPCTest.php
tests/AgainstRPCTest.php
<?php use BitWasp\BitcoinLib\BitcoinLib; use BitWasp\BitcoinLib\Jsonrpcclient; use BitWasp\BitcoinLib\RawTransaction; use BitWasp\BitcoinLib\Electrum; class testAgainstRPC extends PHPUnit_Framework_TestCase { /** * @var Jsonrpcclient */ private $client; public function __construct() { } public function setup() { if (!getenv('BITCOINLIB_TEST_AGAINST_RPC')) { return $this->markTestSkipped("Not testing against RPC"); } $rpcHost = getenv('BITCOINLIB_RPC_HOST') ?: '127.0.0.1'; $rpcUser = getenv('BITCOINLIB_RPC_USER') ?: 'bitcoinrpc'; $rpcPassword = getenv('BITCOINLIB_RPC_PASSWORD') ?: '6Wk1SYL7JmPYoUeWjYRSdqij4xrM5rGBvC4kbJipLVJK'; $this->client = new Jsonrpcclient(['url' => "http://{$rpcUser}:{$rpcPassword}@{$rpcHost}:8332"]); if ($this->client->getinfo() == null) { $this->fail("Can't connect to bitcoind"); } } public function tearDown() { } public function testValidateAddresses() { for ($i = 0; $i < 5; $i++) { $set = BitcoinLib::get_new_key_set(null, (bool)($i % 2)); $validate = $this->client->validateaddress($set['pubAdd']); // Ensure that the Bitcoind believes the address is valid, and that this matches what we think $this->assertTrue($validate['isvalid']); $this->assertEquals($validate['isvalid'], BitcoinLib::validate_address($set['pubAdd'], null, null)); } } public function testP2SHMultisig() { $j = 0; for ($i = 0; $i < 5; $i++) { $n = rand(1, 20); $m = rand(1, $n); $k = []; $pk_list = []; for ($i = 0; $i < $n; $i++) { $k[$i] = BitcoinLib::get_new_key_set(null, (bool)($j++ % 2)); $pk_list[] = $k[$i]['pubKey']; } $multisig = RawTransaction::create_multisig($m, $pk_list); $real = $this->client->createmultisig($m, $pk_list); $this->assertEquals($real['address'], $multisig['address']); $this->assertEquals($real['redeemScript'], $multisig['redeemScript']); } } public function testdecoderawtransaction() { $arr = [ "010000000869c2997e9dd8ce50f9481a33971f0308e8d525ef8bf079f455fc7936d13f375a1f0000008a47304402202de0d834112506ed10549f751ce142094243390f3e035444f105b4764056314302205dfddc421b377c8b089182ddb3928ce02e73c86e5dfb9e66ca6a98810d7a2ac5014104b3d8c8c5896b0ed9537ccbdcfdf3f05cd4299988c72d078b841e0491bab198702c4befaa3da367c117c7c6217cd478c54b572e13de6ddd22c948f4b66c1562b5ffffffffab9aae4a00230f30795cd928225e9f69f7c0e6146c535b641541cb81aa09b5297b0000008a47304402205604456b1ed6dcae5e5f370568dd71c8bfb44823d583e3fa781ae8117ed831a30220154ee1c49bfca8bd1970953255498cb6bc347de1df267ed1b0f70385bca29184014104b3d8c8c5896b0ed9537ccbdcfdf3f05cd4299988c72d078b841e0491bab198702c4befaa3da367c117c7c6217cd478c54b572e13de6ddd22c948f4b66c1562b5ffffffffc036184c5aa93f74530359251e6ff63ab9e17ce7eb6f5d467c42675e318696e5010000008a47304402206c756a38757443794196d16e887c95b9b769b11c608b425e7580e4fcd8456642022040613fbff5e5412c8aa0c3a91b651a6fe6fcf793596a5e29bbc7bc5d73fc683a014104b3d8c8c5896b0ed9537ccbdcfdf3f05cd4299988c72d078b841e0491bab198702c4befaa3da367c117c7c6217cd478c54b572e13de6ddd22c948f4b66c1562b5ffffffff727107bfb37c254f12b4dfdda9ded7544ea6e44298a657ecb1863e00f88e0700110000008c493046022100c24b9c50820d19457fc5842a124500bf2371397144fc6166bdaa4a94275e9dda022100fc6c59286cfdc2fca4cca62d0a1b4e7dd8125a18aee59e630877f85101aa441a014104b3d8c8c5896b0ed9537ccbdcfdf3f05cd4299988c72d078b841e0491bab198702c4befaa3da367c117c7c6217cd478c54b572e13de6ddd22c948f4b66c1562b5fffffffffb862000126a61dba547524f7302bc68ea177cf00f7a49c5b834c0fd397c4dfe390000008b483045022100c837ec9105ddaa75250a38e9942a624754ecacb025feb024adfa8a77914e6eff0220538a1407d7ed8b7417421113ee29c3d9699f87780907b4121068740f1eb31d68014104b3d8c8c5896b0ed9537ccbdcfdf3f05cd4299988c72d078b841e0491bab198702c4befaa3da367c117c7c6217cd478c54b572e13de6ddd22c948f4b66c1562b5ffffffffdb35b57c65cf0fcdea54bfdebda43942d728001a06a9df0404a07801c87ccd8a090000008b483045022100b00faaa1b6a7c1cbe4c47791e302bbcbf1d4fee54cb3d1195d82ef05df0f8f0702207382b68bb44e8fadb0ae7b44f22a18df93e8e8e000d28c88f4fdff78d92a8316014104b3d8c8c5896b0ed9537ccbdcfdf3f05cd4299988c72d078b841e0491bab198702c4befaa3da367c117c7c6217cd478c54b572e13de6ddd22c948f4b66c1562b5ffffffff539ff8e14dab98db92dbbaff03dda50136470bb30bf9fb5b844eb356bc31362d1f0000008b48304502205e41d2112c190396173562d7957b16e0bba64a40adbe466cfe98778d30d91fa20221009f62ac2e345dbd16639b4269c86f156c050e5747013d2a452cdd8c25b8c9aeb9014104b3d8c8c5896b0ed9537ccbdcfdf3f05cd4299988c72d078b841e0491bab198702c4befaa3da367c117c7c6217cd478c54b572e13de6ddd22c948f4b66c1562b5ffffffffbc0dabbf27d0a58f0e2f5a36c11e7f270737ddc92ef0d8d1baacdeff24f39ed7110000008a473044021f3cfe420bd8a5baca342a3df2501f03165e8b8b76fea6fbc82dd05047c99fcd022100bfa829bce78d4f463abefbba943ea54dbbd931b5d7712e263eaf76d2779cf053014104b3d8c8c5896b0ed9537ccbdcfdf3f05cd4299988c72d078b841e0491bab198702c4befaa3da367c117c7c6217cd478c54b572e13de6ddd22c948f4b66c1562b5ffffffff023011e100000000001976a91431b07b8df3c19573388bb688b4fd89f6233f5d7988acf4f31400000000001976a914d17e062579b71bfe199a80991a253d929f8bd35b88ac00000000", "01000000074829be5251cac2c2f6bc5bb71b37a7cd57504408d42010b4a924dc4dd60dabba000000006b483045022100921b883c6a42e14a3718fa2b0b9cc72225c761121710fd380e8ffc25766b3f8302200c436640eeeb6dded3950d9782bb101ca6ebd6f3a7371a4f94f4d769d0e09292012103417cff182cd9886e693868f474d26af984e9af82b3d83116eb5bb591bbb87e0effffffff7841ac6b34686946bff2996ee7a8c347efc4906f565ca15dec507faa085ed8a9000000006a47304402207499620cb0e7db680df261b10beca91988746389b51664f0906f30a8e96a7db60220410ca07f12a3edfb1521bd5c9b18c83f6ccc2ced62ff1fb910b4d2a4ad73ef16012103417cff182cd9886e693868f474d26af984e9af82b3d83116eb5bb591bbb87e0effffffff7806bbe4b6e2b43c677f86845cee3e43d43e4e6da2f387cd15b3fcbafde436fb000000006a47304402201200e9c0a2a452f59ce94fff83128b1795cb2d241a79cd49ea90e56972e70d320220403640d7d103366a2b2f1e0782c3bbb5166c7947b500303b448e8fde27c02987012103417cff182cd9886e693868f474d26af984e9af82b3d83116eb5bb591bbb87e0effffffff129ef9ae1bf2382bd123005102723eaeab4cd9a2287286c1286db74a836c68d6000000006a47304402206392c220d6cd142e9423d559791cc318f3be87d91049d6ee76fdeddec69ceb0d02201240b24be64041ef6a3b0ae94935b23d357a8dbcb1e379ee7d2a58e33b66e72a012103417cff182cd9886e693868f474d26af984e9af82b3d83116eb5bb591bbb87e0effffffff2d918344bedaabd0a8406368518e2ba0ac0f48edd5733ef17909dfab6146789d000000006b483045022100bbdd6943c2233340de453f44f17641846df5d0e319782af48965eee9a2f40de80220304f7b200086b519b4f9b583c598e949f63df96539706391b813f0262a94beb4012103417cff182cd9886e693868f474d26af984e9af82b3d83116eb5bb591bbb87e0efffffffffa83a3af885f23269b4fe583d38510a9902924399816ede03a95160c3cb87b3f000000006a4730440220397bfa4185f41910f80d18bc9ef29cb9583299b668175cf1fd01c0f62176ffc302206d11ba8807a7de0033553a44ef5535f100e62158f04e2cff7140506afef761de012103417cff182cd9886e693868f474d26af984e9af82b3d83116eb5bb591bbb87e0effffffff3a0645bd4adcd0094d1e3c06104dd5037f53f14b7f533dacf5c3c02ffdd41a90000000006b4830450221009accebcf34cda23a9ded8dacaa6f80c87eaa734c2bc80b8aeaab4fe9b7ef9a1502202ce314930e89cee1a527daed448a52fe11bb77867aa5a8e33b07e24a2246ae96012103417cff182cd9886e693868f474d26af984e9af82b3d83116eb5bb591bbb87e0effffffff02676df004000000001976a9141713a60c250ad7e1b909baf09c3291257eef381188acbbde2500000000001976a914e3cf40e4218cdf11d9f3f339035a4b0937ba0a5888ac00000000", "01000000049c90b31e3ea1b3f157b64c6c12832292b3da372c23458fab097f660728f8d72b010000006a473044022008cc581b5a99c35683beb551770ffbebad6605f84a35118c25cc1d7685b5aeb402207b158c110b72cd635213eed7305ca762922ec464583c2d5dfb0f4e43562250b10121022235905741eb82e063b9736a3ced9e3686c0ca4fb14c9bb6e0c8cbdf308cf41dffffffffdb16fbc52a0b77fa466f4501b7dc8af2d9218e32d852f0a6a77e3d0063acb8f9000000006a47304402206c441ed1020c8a36ad6edd1f0c7296ee3d2f390cfca8893973c0714073a9c9cc022023ac27df5e8017c1933847dcbcb471e1349941a81bc83e98b358eea54f01d20a012103829a75e07a0c490f413455798cc7f4a6330f9a403491e063b44862f542b622caffffffff9e65c29ac0ae80db55c72915ecef387f2d2c4ad066694e6b6e3ea5868cb788b6010000006b483045022100a7544728bf36ad8e80927caae7fe6d8d74129f03ba37a841edf8984cc467fd2602203e2603ecf5fdd56e4ed5cde8034ee731535e980e4b84e2759471f7df76cda164012103d8959922eba9a927dec4d742f940e9421c705ae661c15b1a47e3e0baafbc0547ffffffffacffa835a861226cfc63f9b491fc1d5f782b0a9d82f9ee62c99a65eac8ff90a5000000006b483045022100b3aadc533e6de0fe5d9b14861526feddc988cf9e7d7c80eee9ccbd8b2883276502206bf589498a08b44e82b6e5f398d95820ad1e766844189dea202b8b390954176b0121037d14b11915f8f58ba90e6f219abbdb4bc48fdf412094dda6d5790f0edf084cf2ffffffff0aab3ccc10000000001976a9149a305f166390604123d628af06c8897324ae1b6688ac20965904000000001976a9140c0850e3da96e15fc722545f28bced12b46ff5bb88ac66409005000000001976a9149191be4fd37c3391e918a641626cfaf39594923a88ac107c5a00000000001976a914b46a76ad1f35e26f41251a79f68e65fb873d361688acc1b90f00000000001976a9143d0119812e60b1d71e42867dbc6ec09507d618d188ace0e76d01000000001976a914bdd386cd9deeace2557eabc489dcf2a699b82cb388ac7f420f00000000001976a9147c554abe9bf802a53b0cfd70c95c3860fdfefd3588ac4b765509000000001976a914f33c0d7be35d6d146d4618f665d4118b622d200d88acc4d55d0a000000001976a914396da404b5d95fa2261928de51157cc1052ccce188acec314100000000001976a914f09c529f3ebd2097ab81fc50145ba104058c938f88ac00000000", "0100000004bf3ff395d579649914060b71487e466e6fd09604eb62f57ffb63ce702b0c60ab000000008c493046022100896c3dcdaf7c01cf86d9a8105bc54b9065bc26a8a9ea478a491d244b466bf64c0221009377176af0277c45b9c81433d9983d34bb1cdbc37a7479d4a8bbdde4a5d192a0014104a5ed97469860bbe8f05b9964dbc83bb17e5d14383a54fc4395e1e698d01011f6827632c50871df697d46faab766a267cd3b12a17244db5af311133953b440e31ffffffff7010eb5de98223f6048c4e048b4c47b9078b5e6ea679f7d5a4e78d88def33002000000008b48304502206773a142ab11bd4bcac34f55f64ffd488dbdc8dc2a9197d75b1f3bf1da5c00ff022100c4c65d5ea66b00162a3744a9ff3ae60aeb19507e9c30a5ea9ea27fc26306007b014104a5ed97469860bbe8f05b9964dbc83bb17e5d14383a54fc4395e1e698d01011f6827632c50871df697d46faab766a267cd3b12a17244db5af311133953b440e31ffffffff705d8a483f532355a9a3cc4c2f8e9604ec5da99df9689319f0eb75378fd2b5a5000000008b48304502202e5299ab19138468421b4c48c5a78d7ed9e4783a266dd827b915dc27051755a002210093b4377bf0a0bf1ff0a40a996255463bc706ca49a7b23f45999125774c0b7d75014104a5ed97469860bbe8f05b9964dbc83bb17e5d14383a54fc4395e1e698d01011f6827632c50871df697d46faab766a267cd3b12a17244db5af311133953b440e31ffffffff8a0dfdaa0b30c5af535a1791ce3f0f158e197f311d6696b20b6ff56f89f27602000000008b4830450220472537228e29b49a06a9255b86323c2cf5a230fce789ef3b0a308aa58f9dafd4022100a14cfbafbbc682759d5491a2c4dfa1f8287649fafa88c0166fb7b9ef9e77d999014104a5ed97469860bbe8f05b9964dbc83bb17e5d14383a54fc4395e1e698d01011f6827632c50871df697d46faab766a267cd3b12a17244db5af311133953b440e31ffffffff0234b13c00000000001976a914794e3a3f5f542ebb3f2e640ea9417e3c7d41e40b88acfc4d2a00000000001976a914b526df90f2bb0c5830b469b8b8f96d25e127de5d88ac00000000", "01000000011aaebeeb686e02c3471f0cf9f12eb6d69e45c3dd89cc0fa135e26ca72ec8d2c1020000006b483045022100f119173e52f8950dc0f369c64546746b900d621633f7a1d9b386232b5c21d6430220197f389584d087f34d250ffc8e5908a6ec9651fd02f64f200d3a60abe0df4287012102a1c5150347aa359ad363b7ccaf8602e7538de37935ebb2bb1656e20bfc6cd111ffffffff02b421e428000000001976a91443d6d50fb700dc1d98494942f8c378b8cbbb0def88ac80969800000000001976a9148e10169967933a59a77260277bb6f4d2869ed53088ac00000000" ]; foreach ($arr as $tx) { $real = $this->client->decoderawtransaction($tx); $decode = RawTransaction::decode($tx); $count = count($real['vin']); for ($i = 0; $i < $count; $i++) { $this->assertEquals($real['vin'][$i]['scriptSig']['hex'], $decode['vin'][$i]['scriptSig']['hex']); } $count = count($real['vout']); for ($i = 0; $i < $count; $i++) { $this->assertEquals($real['vout'][$i]['scriptPubKey']['hex'], $decode['vout'][$i]['scriptPubKey']['hex']); } } } } ;
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/tests/BIP32CoreTest.php
tests/BIP32CoreTest.php
<?php class BIP32CoreTest extends PHPUnit_Framework_TestCase { public function __construct() { } public function setup() { } public function tearDown() { } public function testGMP() { $math = \Mdanter\Ecc\EccFactory::getAdapter(); $I_l = "e97a4d6be13f8f5804c0a76080428fc6d51260f74801678c4127045d2640af14"; $private_key = "142018c66b43a95de58c1cf603446fc0da322bc15fb4df068b844b57c706dd05"; $n = "115792089237316195423570985008687907852837564279074904382605163141518161494337"; $gmp_I_l = gmp_init($I_l, 16); $gmp_private_key = gmp_init($private_key, 16); $gmp_add = gmp_add($gmp_I_l, $gmp_private_key); $gmp_add_res = gmp_strval($gmp_add, 10); $this->assertEquals("105604983404708440304568772161069255144976878830542744455590282065741265022740", gmp_strval($gmp_I_l)); $this->assertEquals("9102967069016248707169900673545386030247334423973996501079368232055584775429", gmp_strval($gmp_private_key)); $this->assertEquals("114707950473724689011738672834614641175224213254516740956669650297796849798169", gmp_strval($gmp_add)); $this->assertEquals("114707950473724689011738672834614641175224213254516740956669650297796849798169", gmp_strval(gmp_div_r($gmp_add, gmp_init($n)))); $this->assertEquals("-4", gmp_strval(gmp_cmp(0, gmp_div_r($gmp_add, $n)))); $this->assertEquals("230500039711040884435309657843302549028061777533591645339274813439315011292506", gmp_strval(gmp_add(gmp_init($n), gmp_div_r($gmp_add, gmp_init($n))))); $gmp_mod2 = $math->mod($gmp_add_res, $n); $this->assertTrue(is_string($gmp_mod2)); $this->assertEquals("114707950473724689011738672834614641175224213254516740956669650297796849798169", $gmp_mod2); $this->assertEquals("114707950473724689011738672834614641175224213254516740956669650297796849798169", $gmp_mod2); // when no base is provided both a resource and string work $this->assertEquals("114707950473724689011738672834614641175224213254516740956669650297796849798169", gmp_strval(gmp_init($gmp_mod2))); $this->assertEquals("114707950473724689011738672834614641175224213254516740956669650297796849798169", gmp_strval($gmp_mod2)); // when base is provided it fails on HHVM when inputting a string $this->assertEquals("fd9a66324c8338b5ea4cc4568386ff87af448cb8a7b64692ccab4fb4ed478c19", gmp_strval(gmp_init($gmp_mod2), 16)); // $this->assertEquals("fd9a66324c8338b5ea4cc4568386ff87af448cb8a7b64692ccab4fb4ed478c19", gmp_strval($gmp_mod2, 16)); $this->assertEquals("fd9a66324c8338b5ea4cc4568386ff87af448cb8a7b64692ccab4fb4ed478c19", str_pad(gmp_strval(gmp_init($gmp_mod2), 16), 64, '0', STR_PAD_LEFT)); } }
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/tests/SignVerifyMessageTest.php
tests/SignVerifyMessageTest.php
<?php use BitWasp\BitcoinLib\BitcoinLib; use BitWasp\BitcoinLib\Jsonrpcclient; class SignVerifyMessageTest extends PHPUnit_Framework_TestCase { public function setup() { // ensure we're set to bitcoin and not bitcoin-testnet BitcoinLib::setMagicByteDefaults('bitcoin'); } public function testSignMessage() { $k = "40830342147156906673307227534819286677883886097095155210766904187107130350230"; // fixed K value for testing $WIF = "KxuKf1nB3nZ5eYVFVuCgvH5EFM8iUSWqmqJ9bAQukekYgPbju4FL"; $privKey = BitcoinLib::WIF_to_private_key($WIF); $sig = BitcoinLib::signMessage('12XJYLMM9ZoDZjmBZ1SeFANhgCVjwNYgVm', $privKey, $k); $this->assertEquals("H2LFY1Qm5w7xSlnluYovpPYgiFT8kqot/SJOho5f7R8CWtpkLMGAFac/S4kDzah76y2tjfirGNpKhxWw6Ki5RpU=", $sig); $this->assertTrue(BitcoinLib::verifyMessage('12XJYLMM9ZoDZjmBZ1SeFANhgCVjwNYgVm', $sig, '12XJYLMM9ZoDZjmBZ1SeFANhgCVjwNYgVm')); $sig = BitcoinLib::signMessage('12XJYLMM9ZoDZjmBZ1SeFANhgCVjwNYgVm', $privKey); $this->assertTrue(!!$sig); $this->assertTrue(BitcoinLib::verifyMessage('12XJYLMM9ZoDZjmBZ1SeFANhgCVjwNYgVm', $sig, '12XJYLMM9ZoDZjmBZ1SeFANhgCVjwNYgVm')); $this->assertTrue(BitcoinLib::verifyMessage("12XJYLMM9ZoDZjmBZ1SeFANhgCVjwNYgVm", "IHDCaEP3MZQcOOn1hp/nAbYFf9KOSoLi+TCWNFDV2+j+SkVSFYZHHJjfwwYP02Xlf7aIOZdI5ZzJZetLpnDp9H8=", "12XJYLMM9ZoDZjmBZ1SeFANhgCVjwNYgVm")); } public function testSignMessageFailure() { $e = null; try { BitcoinLib::verifyMessage("mkiPAxhzUMo8mAwW3q95q7aNuXt6HzbbUA", "IND22TSMS2uuWyIn2Be49ajaGwNmiQtiCXrozev00cPFXpACe8LQYU/t6xp8YXb5SIVAnqEn/DailZw+OM85TM0=", "mkiPAxhzUMo8mAwW3q95q7aNuXt6HzbbUA"); } catch (\Exception $e) { $this->assertEquals("invalid Bitcoin address", $e->getMessage()); } $this->assertTrue(!!$e, "verifyMessage should throw exception when address is invalid"); $this->assertFalse(BitcoinLib::verifyMessage("12XJYLMM9ZoDZjmBZ1SeFANhgCVjwNYgVm", "IHDCaEP3MZQcOOn1hp/nAbYFf9KOSoLi+TCWNFDV2+j+SkVSFYZHHJjfwwYP02Xlf7aIOZdI5ZzJZetLpnDp9H7=", "12XJYLMM9ZoDZjmBZ1SeFANhgCVjwNYgVm")); $e = null; try { $this->assertFalse(BitcoinLib::verifyMessage("12XJYLMM9ZoDZjmBZ1SeFANhgCVjwNYgVm", "I22CEEP3MZQcOOn1hp/nAbYFf9KOSoLi+TCWNFDV2+j+SkVSFYZHHJjfwwYP02Xlf7aIOZdI5ZzJZetLpnDp9H8=", "12XJYLMM9ZoDZjmBZ1SeFANhgCVjwNYgVm")); } catch (\Exception $e) { $this->assertEquals("invalid signature type", $e->getMessage()); } $this->assertTrue(!!$e, "verifyMessage should throw exception when signature is invalid"); $e = null; try { $this->assertFalse(BitcoinLib::verifyMessage("12XJYLMM9ZoDZjmBZ1SeFANhgCVjwNYgVm", "IH2CEEP3MZQcOOn1hp/nAbYFf9KOSoLi+TCWNFDV2+j+SkVSFYZHHJjfwwYP02Xlf7aIOZdI5ZzJZetLpnDp9H8=", "12XJYLMM9ZoDZjmBZ1SeFANhgCVjwNYgVm")); } catch (\Exception $e) { $this->assertEquals("unable to recover key", $e->getMessage()); } $this->assertTrue(!!$e, "verifyMessage should throw exception when signature is invalid"); } public function testSignMessageTestnet() { BitcoinLib::setMagicByteDefaults('bitcoin-testnet'); $this->assertTrue(BitcoinLib::verifyMessage("mkiPAxhzUMo8mAwW3q95q7aNuXt6HzbbUA", "IND22TSMS2uuWyIn2Be49ajaGwNmiQtiCXrozev00cPFXpACe8LQYU/t6xp8YXb5SIVAnqEn/DailZw+OM85TM0=", "mkiPAxhzUMo8mAwW3q95q7aNuXt6HzbbUA")); BitcoinLib::setMagicByteDefaults('bitcoin'); } public function testVerifyMessageDataSet() { $cnt = (getenv('BITCOINLIB_EXTENSIVE_TESTING') ?: 1) * 10; $data = json_decode(file_get_contents(__DIR__ . "/data/signverify.json"), true); $data = array_map(function ($k) use ($data) { return $data[$k]; }, array_rand($data, $cnt)); foreach ($data as $row) { $this->assertTrue(BitcoinLib::verifyMessage($row['address'], $row['signature'], $row['address'])); } } public function testSignMessageDataSet() { // special case, when undefined we do 1, otherwise we do ENV * 5 (50 on travis) $cnt = getenv('BITCOINLIB_EXTENSIVE_TESTING') ? (getenv('BITCOINLIB_EXTENSIVE_TESTING') * 5) : 1; $data = json_decode(file_get_contents(__DIR__ . "/data/signverify.json"), true); $data = array_map(function ($k) use ($data) { return $data[$k]; }, (array)array_rand($data, $cnt)); foreach ($data as $row) { $privKey = BitcoinLib::WIF_to_private_key($row['wif']); $signature = BitcoinLib::signMessage($row['address'], $privKey); $this->assertTrue(!!$signature); $this->assertTrue(BitcoinLib::verifyMessage($row['address'], $signature, $row['address'])); } } public function testSignMessageDataSetAgainstRPC() { if (!getenv('BITCOINLIB_TEST_AGAINST_RPC')) { return $this->markTestSkipped("Not testing against RPC"); } // special case, when undefined we do 1, otherwise we do ENV * 5 (50 on travis) $cnt = getenv('BITCOINLIB_EXTENSIVE_TESTING') ? (getenv('BITCOINLIB_EXTENSIVE_TESTING') * 5) : 1; $rpcHost = getenv('BITCOINLIB_RPC_HOST') ?: '127.0.0.1'; $rpcUser = getenv('BITCOINLIB_RPC_USER') ?: 'bitcoinrpc'; $rpcPassword = getenv('BITCOINLIB_RPC_PASSWORD') ?: '6Wk1SYL7JmPYoUeWjYRSdqij4xrM5rGBvC4kbJipLVJK'; $rpc = new Jsonrpcclient(['url' => "http://{$rpcUser}:{$rpcPassword}@{$rpcHost}:8332"]); if ($rpc->getinfo() == null) { $this->fail("Can't connect to bitcoind"); } $data = json_decode(file_get_contents(__DIR__ . "/data/signverify.json"), true); $data = array_map(function ($k) use ($data) { return $data[$k]; }, (array)array_rand($data, $cnt)); foreach ($data as $row) { $privKey = BitcoinLib::WIF_to_private_key($row['wif']); $signature = BitcoinLib::signMessage($row['address'], $privKey); $this->assertTrue(!!$signature); $this->assertTrue(BitcoinLib::verifyMessage($row['address'], $signature, $row['address'])); $this->assertTrue($rpc->verifymessage($row['address'], $signature, $row['address'])); } } public function testDeriveAddressFromSignature() { $k = "40830342147156906673307227534819286677883886097095155210766904187107130350230"; // fixed K value for testing $WIF = "KxuKf1nB3nZ5eYVFVuCgvH5EFM8iUSWqmqJ9bAQukekYgPbju4FL"; $privKey = BitcoinLib::WIF_to_private_key($WIF); $test_message = 'this is a test'; $true_address = '12XJYLMM9ZoDZjmBZ1SeFANhgCVjwNYgVm'; $test_sig = BitcoinLib::signMessage($test_message, $privKey, $k); $derived = BitcoinLib::deriveAddressFromSignature($test_sig, $test_message); $this->assertEquals($true_address, $derived); } }
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/tests/RawTransactionTest.php
tests/RawTransactionTest.php
<?php use BitWasp\BitcoinLib\BitcoinLib; use BitWasp\BitcoinLib\RawTransaction; use Mdanter\Ecc\EccFactory; class RawTransactionTest extends PHPUnit_Framework_TestCase { public function setup() { // ensure we're set to bitcoin and not bitcoin-testnet BitcoinLib::setMagicByteDefaults('bitcoin'); } public function tearDown() { } public function testDecodeRedeemScript() { // Random samples from txs in the blockchain $samples = [ "5221032c6aa78662cc43a3bb0f8f850d0c45e18d0a49c61ec69db87e072c88d7a9b6e9210353581fd2fc745d17264af8cb8cd507d82c9658962567218965e750590e41c41e21024fe45dd4749347d281fd5348f56e883ee3a00903af899301ac47ba90f904854f53ae", "5141048ff228400b3056084121fa83658c43858e3826d59ddc6cfd033df80565f8cc96e09e26e6a2320958a999cb82030d781698176a591424cf4f66b5644e7c8e690a41040f63d3a4b5d797b8ceb443ae54a45b7bb0465a792844e104e31eda18f8a0b0b8f42adaac0002bac7aae6a5cd4106be45172463e9caf44aa567da486455063d1152ae", "524104664547a29ffc51db8d46377c1c6611914e11a9c36a83992e642b6c3aa1f0017eee1d77d6d0e4f3b82be92067b39d7f62fe2da7b680e3e306402bf53f8dd5ef04410496cb89ca7f8f244808b4a50ee80e9acd12f801d33646aa9a50eb4a6b550f6520b4204a79f0192a30fc8c7b0eef18d49b3b720373f6b2b928023ae4b463c2c4eb52ae", "522102c33586c016c66158f921c54e30628d682627839d0297f800050b981ab298b58a2102bd4d0115f28b4ac3122e89ebab628f1de2db0a3947721f2fe9b17f9b96e2204052ae", "524104192944fe1ecf2bb78174a282a3b7d3a457bb40993a6785853cfcedf5bb6f67fd453db59b4e2cfd864480c86d816b383b0be51f82444f7bca0cdaa12e002b25da4104738bcb941b0ca59dad113393c212be91b4bb648efce44567bd372ffac64c6f373d2d928a34c6d1d98fced6a6b03852fc592eef7534d23b801a714e11f1a061ac410491ccd85240d31e84e40586d0bf10a1f1e9d309bffac8e179534be2a28310e92c486d9c7e47ee76e23f6b6f390075e16cf08b6ce9c3d2383c5a3a20b6598d224e53ae", "52410453e1bb5aa30c3711ac64ca03a38d7f248db3b31a2559efa8a4cb6fa63b5356e9d2cb8c26b722d7f984cc51ba6bfceb2e5306249f6ba626e73de1d412f2e8d4594104be2c03fe4f9aa55dea54812822a563138b4c12651ce3d1161b246c47379838ae1f7a0df55e6b475c2cddd278bcd130898a21e319e1bc02da86876efb9fcb621c4104cf5189fa8b6457a5e06f652ef8666499574632bc5c75f51fb049dcc93638309f493594e4bd6b1d6ac92f6d77cc52db255b92f20749b237927fb2a60d7c887a1053ae", "5241048c1bbabfd38a9d462443e9bd99e133f512efa9548743ffb3f544dcc83b9b0356780796678519987ba04a054445e0cea2a60f1cafc1dbcc97c412338771b094374104bf5d3c29bad79db8f541b0d1095ef1f8ba4e8eda75936dcec81ac72599121b561f2b4ce9a2947cf0a5498888ee8e2a918c7e595da8fa1ae5b28df607e5fc29bb4104d79d37c0f322442bea954bb3fda3a97b24b113152a638316a1fbd44673e28967cefca7c3ed366ed41bbc0978dc308efab89f6e9010912d1e6c3fed0d4dc2b63d53ae", "5121031b9abc9a11a4a078509969f12de3129bf81060b001742e05cd8041a7e7402bcb51ae", "5241043a0f00454bdcd92698bebd22de0785c8dd190144115b3eced47f26796e24c3050faa3cb3b46a5a868a8f77f7f08ddda7c90952ca07bc18fc9765b8f0bc28cdd941044d7e454064678f032c6a845a986a41e20ae224a7843eb397637e7d1df2c80762b0a14d348cb2a4261cf83fba77d1e025a9eaaf251e1a23f9caabb4c9c5fba5314104ba5b7a9ce88ee36d8689e6a70e847b88d2ddcd12a008195f5b841f88485e14d6a3abc4120e721a50655ce3ba63606ba7ac927254f89ec3d0dea3bfe1d7b2797653ae", "5241046bcd91262b52419bdb0a88cc628e6eeed8ca7c60857a04be80c9cef320a775881d01b439cefc6e814f713c753be596fb65b5575f9e99583cd50776474e80adc14104b730f446201772dbc67d39f72fe9ef2e966066718070a4248874fb237a325dfa43073a893f95ae713d40194bac5d6cb23d25616e0966286c9c7416afe7214ac84104b31a45c0362e0c56e868bb7563334b3b35eb0f4af810648e45e365c46eaf983a155b6ec834db5143a7df47780fbf7e9f6ac5c3d45837b6c76b0c9c4c864feee453ae", "524104f10d42e5a5dc24dabe524dc305f9deab2c5b58c42aa83833d1d2ad38c9b796b4756a99e60bfee19e92424f3aa919fb63377b6d8d35d091d6a5de62b58b8c8d7721025563ee4b549f5a7d3dfb046a088815c69ebd44b389a78342ccb01e77d89465a752ae", "522102c48bf0c25bf78fbe98988ef8f27ee05284f79c550e987a88e1237872c030ab8021026f6020210361586f02c93cfb926fed3d240b7f11b1a5694b36c826561abd3932210352057bbf5c024edd3630606689956c52104150d1c494b1d92ca6c7243d5eeb7453ae", "522102d7297e56bc410c2d1671cd2694686400f59061bef1bbb6f7e3269dacbbdce53e2102421a4efafabd2534116deb6c00a01831de71c62c53a5e718b852ccd81a7ff98c52ae", "522102d7297e56bc410c2d1671cd2694686400f59061bef1bbb6f7e3269dacbbdce53e2102421a4efafabd2534116deb6c00a01831de71c62c53a5e718b852ccd81a7ff98c52ae", "52210374763369da3dca422b64e13ae1cf81a5f68dd09a1efcd463b5511fe7a436207a21021d7e25870057383faad795f651b3f5844c4d3ebb1e3a31e444e6a21d9af371642102c5463df6e77f7f659d123ca19e079ef9ec08e1ddfa4a1bcb4814902b2b1ad41c53ae", "5241046dae34916bec595e73b3fabfd1aad2158994fee1a5bc19216654dc49b47f1976a26d7a6d3c7b713f8650121812253a206c4cd7f1e7b453e8e700c720e99c60564104fcb3a8fd045eb2c77a45fdfed73317c22b4ab40de5950c944ff8b1cf45eb83aaafc8d987fe1706d10febc6277223569e0df10881b8cea2435b4fa3bdabf41ad021036c06d0a475646980d4ede31b6b4864946fe7fb54fa15102b03ac16a56c4300f053ae", "524104d403a9ec23cb289734645337a079c636ecc47b6015ebd88e972741948ddd65a708f8238f1da4b8f70945ae57288a4bc406e3811a0b83b4e610565cc83a5faff741046c82c6671ada6c430d8ea81b27ecae04fa9f0b4ab14bcceb89c589ea0d7b1919565221ef6c2004a6204f1d6d616eb770c13dbda3cdf271f2ae6fe5a654b5a42e2102e3929380fccb603649a8dd775ec2b1e81748b2749503e039530330f1a5b448bf53ae", "5221039bf1c1ec550815dee677d1b391a03f5f501abe6fd9817b2486bc03aa7ae038d8410437d0fd54cbbe8d4e6bd12d19b1c863d3cfbce71c4b31541546685c090d9572a2d2f5f30c58d45c7141cf29b7fe83002f29abccc9c290b7dba6eed9e9d773d1bc2102521e92a6b26db346cb8e2a27ceb2ec83905f3f8d3f8d52634c82c3ad8d0f188a53ae" ]; foreach ($samples as $sample) { $raw = RawTransaction::decode_redeem_script($sample); $this->assertTrue(is_array($raw)); } } public function testSignP2SH() { BitcoinLib::setMagicByteDefaults('bitcoin-testnet'); $redeem_script = "522103c0b1fd07752ebdd43c75c0a60d67958eeac8d4f5245884477eae094c4361418d2102ab1fae8dacd465460ad8e0c08cb9c25871782aa539a58b65f9bf1264c355d0982102dc43b58ee5313d1969b939718d2c8104a3365d45f12f91753bfc950d16d3e82e53ae"; $inputs = array( array( "txid" => "83c5c88e94d9c518f314e30ca0529ab3f8e5e4f14a8936db4a32070005e3b61f", "vout" => 0, "scriptPubKey" => "a9145fe34588f475c5251ff994eafb691a5ce197d18b87", // only needed for RawTransaction::sign "redeemScript" => $redeem_script, // only for debugging "value" => 0.00010000 ) ); $outputs = array( "n3P94USXs7LzfF4BKJVyGv2uCfBQRbvMZJ" => BitcoinLib::toSatoshi(0.00010000) ); $raw_transaction = RawTransaction::create($inputs, $outputs); /* * sign with first key */ $wallet = array(); RawTransaction::private_keys_to_wallet($wallet, array("cV2BRcdtWoZMSovYCpoY9gyvjiVK5xufpAwdAFk1jdonhGZq1cCm")); RawTransaction::redeem_scripts_to_wallet($wallet, array($redeem_script)); $sign = RawTransaction::sign($wallet, $raw_transaction, json_encode($inputs)); $this->assertFalse(RawTransaction::validate_signed_transaction($sign['hex'], json_encode($inputs))); $this->assertEquals(2, $sign['req_sigs']); $this->assertEquals(1, $sign['sign_count']); $this->assertEquals('false', $sign['complete']); /* * sign with second key */ $wallet = array(); RawTransaction::private_keys_to_wallet($wallet, array("cMps8Dg4Z1ThcwvPiPpshR6cbosYoTrgUwgLcFasBSxsdLHwzoUK")); RawTransaction::redeem_scripts_to_wallet($wallet, array($redeem_script)); $sign = RawTransaction::sign($wallet, $sign['hex'], json_encode($inputs)); $this->assertEquals(2, $sign['req_sigs']); $this->assertEquals(2, $sign['sign_count']); $this->assertEquals('true', $sign['complete']); $this->assertTrue(RawTransaction::validate_signed_transaction($sign['hex'], json_encode($inputs))); BitcoinLib::setMagicByteDefaults('bitcoin'); } public function testCreateRaw() { /*$arr = [ "010000000869c2997e9dd8ce50f9481a33971f0308e8d525ef8bf079f455fc7936d13f375a1f0000008a47304402202de0d834112506ed10549f751ce142094243390f3e035444f105b4764056314302205dfddc421b377c8b089182ddb3928ce02e73c86e5dfb9e66ca6a98810d7a2ac5014104b3d8c8c5896b0ed9537ccbdcfdf3f05cd4299988c72d078b841e0491bab198702c4befaa3da367c117c7c6217cd478c54b572e13de6ddd22c948f4b66c1562b5ffffffffab9aae4a00230f30795cd928225e9f69f7c0e6146c535b641541cb81aa09b5297b0000008a47304402205604456b1ed6dcae5e5f370568dd71c8bfb44823d583e3fa781ae8117ed831a30220154ee1c49bfca8bd1970953255498cb6bc347de1df267ed1b0f70385bca29184014104b3d8c8c5896b0ed9537ccbdcfdf3f05cd4299988c72d078b841e0491bab198702c4befaa3da367c117c7c6217cd478c54b572e13de6ddd22c948f4b66c1562b5ffffffffc036184c5aa93f74530359251e6ff63ab9e17ce7eb6f5d467c42675e318696e5010000008a47304402206c756a38757443794196d16e887c95b9b769b11c608b425e7580e4fcd8456642022040613fbff5e5412c8aa0c3a91b651a6fe6fcf793596a5e29bbc7bc5d73fc683a014104b3d8c8c5896b0ed9537ccbdcfdf3f05cd4299988c72d078b841e0491bab198702c4befaa3da367c117c7c6217cd478c54b572e13de6ddd22c948f4b66c1562b5ffffffff727107bfb37c254f12b4dfdda9ded7544ea6e44298a657ecb1863e00f88e0700110000008c493046022100c24b9c50820d19457fc5842a124500bf2371397144fc6166bdaa4a94275e9dda022100fc6c59286cfdc2fca4cca62d0a1b4e7dd8125a18aee59e630877f85101aa441a014104b3d8c8c5896b0ed9537ccbdcfdf3f05cd4299988c72d078b841e0491bab198702c4befaa3da367c117c7c6217cd478c54b572e13de6ddd22c948f4b66c1562b5fffffffffb862000126a61dba547524f7302bc68ea177cf00f7a49c5b834c0fd397c4dfe390000008b483045022100c837ec9105ddaa75250a38e9942a624754ecacb025feb024adfa8a77914e6eff0220538a1407d7ed8b7417421113ee29c3d9699f87780907b4121068740f1eb31d68014104b3d8c8c5896b0ed9537ccbdcfdf3f05cd4299988c72d078b841e0491bab198702c4befaa3da367c117c7c6217cd478c54b572e13de6ddd22c948f4b66c1562b5ffffffffdb35b57c65cf0fcdea54bfdebda43942d728001a06a9df0404a07801c87ccd8a090000008b483045022100b00faaa1b6a7c1cbe4c47791e302bbcbf1d4fee54cb3d1195d82ef05df0f8f0702207382b68bb44e8fadb0ae7b44f22a18df93e8e8e000d28c88f4fdff78d92a8316014104b3d8c8c5896b0ed9537ccbdcfdf3f05cd4299988c72d078b841e0491bab198702c4befaa3da367c117c7c6217cd478c54b572e13de6ddd22c948f4b66c1562b5ffffffff539ff8e14dab98db92dbbaff03dda50136470bb30bf9fb5b844eb356bc31362d1f0000008b48304502205e41d2112c190396173562d7957b16e0bba64a40adbe466cfe98778d30d91fa20221009f62ac2e345dbd16639b4269c86f156c050e5747013d2a452cdd8c25b8c9aeb9014104b3d8c8c5896b0ed9537ccbdcfdf3f05cd4299988c72d078b841e0491bab198702c4befaa3da367c117c7c6217cd478c54b572e13de6ddd22c948f4b66c1562b5ffffffffbc0dabbf27d0a58f0e2f5a36c11e7f270737ddc92ef0d8d1baacdeff24f39ed7110000008a473044021f3cfe420bd8a5baca342a3df2501f03165e8b8b76fea6fbc82dd05047c99fcd022100bfa829bce78d4f463abefbba943ea54dbbd931b5d7712e263eaf76d2779cf053014104b3d8c8c5896b0ed9537ccbdcfdf3f05cd4299988c72d078b841e0491bab198702c4befaa3da367c117c7c6217cd478c54b572e13de6ddd22c948f4b66c1562b5ffffffff023011e100000000001976a91431b07b8df3c19573388bb688b4fd89f6233f5d7988acf4f31400000000001976a914d17e062579b71bfe199a80991a253d929f8bd35b88ac00000000", "01000000074829be5251cac2c2f6bc5bb71b37a7cd57504408d42010b4a924dc4dd60dabba000000006b483045022100921b883c6a42e14a3718fa2b0b9cc72225c761121710fd380e8ffc25766b3f8302200c436640eeeb6dded3950d9782bb101ca6ebd6f3a7371a4f94f4d769d0e09292012103417cff182cd9886e693868f474d26af984e9af82b3d83116eb5bb591bbb87e0effffffff7841ac6b34686946bff2996ee7a8c347efc4906f565ca15dec507faa085ed8a9000000006a47304402207499620cb0e7db680df261b10beca91988746389b51664f0906f30a8e96a7db60220410ca07f12a3edfb1521bd5c9b18c83f6ccc2ced62ff1fb910b4d2a4ad73ef16012103417cff182cd9886e693868f474d26af984e9af82b3d83116eb5bb591bbb87e0effffffff7806bbe4b6e2b43c677f86845cee3e43d43e4e6da2f387cd15b3fcbafde436fb000000006a47304402201200e9c0a2a452f59ce94fff83128b1795cb2d241a79cd49ea90e56972e70d320220403640d7d103366a2b2f1e0782c3bbb5166c7947b500303b448e8fde27c02987012103417cff182cd9886e693868f474d26af984e9af82b3d83116eb5bb591bbb87e0effffffff129ef9ae1bf2382bd123005102723eaeab4cd9a2287286c1286db74a836c68d6000000006a47304402206392c220d6cd142e9423d559791cc318f3be87d91049d6ee76fdeddec69ceb0d02201240b24be64041ef6a3b0ae94935b23d357a8dbcb1e379ee7d2a58e33b66e72a012103417cff182cd9886e693868f474d26af984e9af82b3d83116eb5bb591bbb87e0effffffff2d918344bedaabd0a8406368518e2ba0ac0f48edd5733ef17909dfab6146789d000000006b483045022100bbdd6943c2233340de453f44f17641846df5d0e319782af48965eee9a2f40de80220304f7b200086b519b4f9b583c598e949f63df96539706391b813f0262a94beb4012103417cff182cd9886e693868f474d26af984e9af82b3d83116eb5bb591bbb87e0efffffffffa83a3af885f23269b4fe583d38510a9902924399816ede03a95160c3cb87b3f000000006a4730440220397bfa4185f41910f80d18bc9ef29cb9583299b668175cf1fd01c0f62176ffc302206d11ba8807a7de0033553a44ef5535f100e62158f04e2cff7140506afef761de012103417cff182cd9886e693868f474d26af984e9af82b3d83116eb5bb591bbb87e0effffffff3a0645bd4adcd0094d1e3c06104dd5037f53f14b7f533dacf5c3c02ffdd41a90000000006b4830450221009accebcf34cda23a9ded8dacaa6f80c87eaa734c2bc80b8aeaab4fe9b7ef9a1502202ce314930e89cee1a527daed448a52fe11bb77867aa5a8e33b07e24a2246ae96012103417cff182cd9886e693868f474d26af984e9af82b3d83116eb5bb591bbb87e0effffffff02676df004000000001976a9141713a60c250ad7e1b909baf09c3291257eef381188acbbde2500000000001976a914e3cf40e4218cdf11d9f3f339035a4b0937ba0a5888ac00000000", "01000000049c90b31e3ea1b3f157b64c6c12832292b3da372c23458fab097f660728f8d72b010000006a473044022008cc581b5a99c35683beb551770ffbebad6605f84a35118c25cc1d7685b5aeb402207b158c110b72cd635213eed7305ca762922ec464583c2d5dfb0f4e43562250b10121022235905741eb82e063b9736a3ced9e3686c0ca4fb14c9bb6e0c8cbdf308cf41dffffffffdb16fbc52a0b77fa466f4501b7dc8af2d9218e32d852f0a6a77e3d0063acb8f9000000006a47304402206c441ed1020c8a36ad6edd1f0c7296ee3d2f390cfca8893973c0714073a9c9cc022023ac27df5e8017c1933847dcbcb471e1349941a81bc83e98b358eea54f01d20a012103829a75e07a0c490f413455798cc7f4a6330f9a403491e063b44862f542b622caffffffff9e65c29ac0ae80db55c72915ecef387f2d2c4ad066694e6b6e3ea5868cb788b6010000006b483045022100a7544728bf36ad8e80927caae7fe6d8d74129f03ba37a841edf8984cc467fd2602203e2603ecf5fdd56e4ed5cde8034ee731535e980e4b84e2759471f7df76cda164012103d8959922eba9a927dec4d742f940e9421c705ae661c15b1a47e3e0baafbc0547ffffffffacffa835a861226cfc63f9b491fc1d5f782b0a9d82f9ee62c99a65eac8ff90a5000000006b483045022100b3aadc533e6de0fe5d9b14861526feddc988cf9e7d7c80eee9ccbd8b2883276502206bf589498a08b44e82b6e5f398d95820ad1e766844189dea202b8b390954176b0121037d14b11915f8f58ba90e6f219abbdb4bc48fdf412094dda6d5790f0edf084cf2ffffffff0aab3ccc10000000001976a9149a305f166390604123d628af06c8897324ae1b6688ac20965904000000001976a9140c0850e3da96e15fc722545f28bced12b46ff5bb88ac66409005000000001976a9149191be4fd37c3391e918a641626cfaf39594923a88ac107c5a00000000001976a914b46a76ad1f35e26f41251a79f68e65fb873d361688acc1b90f00000000001976a9143d0119812e60b1d71e42867dbc6ec09507d618d188ace0e76d01000000001976a914bdd386cd9deeace2557eabc489dcf2a699b82cb388ac7f420f00000000001976a9147c554abe9bf802a53b0cfd70c95c3860fdfefd3588ac4b765509000000001976a914f33c0d7be35d6d146d4618f665d4118b622d200d88acc4d55d0a000000001976a914396da404b5d95fa2261928de51157cc1052ccce188acec314100000000001976a914f09c529f3ebd2097ab81fc50145ba104058c938f88ac00000000", "0100000004bf3ff395d579649914060b71487e466e6fd09604eb62f57ffb63ce702b0c60ab000000008c493046022100896c3dcdaf7c01cf86d9a8105bc54b9065bc26a8a9ea478a491d244b466bf64c0221009377176af0277c45b9c81433d9983d34bb1cdbc37a7479d4a8bbdde4a5d192a0014104a5ed97469860bbe8f05b9964dbc83bb17e5d14383a54fc4395e1e698d01011f6827632c50871df697d46faab766a267cd3b12a17244db5af311133953b440e31ffffffff7010eb5de98223f6048c4e048b4c47b9078b5e6ea679f7d5a4e78d88def33002000000008b48304502206773a142ab11bd4bcac34f55f64ffd488dbdc8dc2a9197d75b1f3bf1da5c00ff022100c4c65d5ea66b00162a3744a9ff3ae60aeb19507e9c30a5ea9ea27fc26306007b014104a5ed97469860bbe8f05b9964dbc83bb17e5d14383a54fc4395e1e698d01011f6827632c50871df697d46faab766a267cd3b12a17244db5af311133953b440e31ffffffff705d8a483f532355a9a3cc4c2f8e9604ec5da99df9689319f0eb75378fd2b5a5000000008b48304502202e5299ab19138468421b4c48c5a78d7ed9e4783a266dd827b915dc27051755a002210093b4377bf0a0bf1ff0a40a996255463bc706ca49a7b23f45999125774c0b7d75014104a5ed97469860bbe8f05b9964dbc83bb17e5d14383a54fc4395e1e698d01011f6827632c50871df697d46faab766a267cd3b12a17244db5af311133953b440e31ffffffff8a0dfdaa0b30c5af535a1791ce3f0f158e197f311d6696b20b6ff56f89f27602000000008b4830450220472537228e29b49a06a9255b86323c2cf5a230fce789ef3b0a308aa58f9dafd4022100a14cfbafbbc682759d5491a2c4dfa1f8287649fafa88c0166fb7b9ef9e77d999014104a5ed97469860bbe8f05b9964dbc83bb17e5d14383a54fc4395e1e698d01011f6827632c50871df697d46faab766a267cd3b12a17244db5af311133953b440e31ffffffff0234b13c00000000001976a914794e3a3f5f542ebb3f2e640ea9417e3c7d41e40b88acfc4d2a00000000001976a914b526df90f2bb0c5830b469b8b8f96d25e127de5d88ac00000000", "01000000011aaebeeb686e02c3471f0cf9f12eb6d69e45c3dd89cc0fa135e26ca72ec8d2c1020000006b483045022100f119173e52f8950dc0f369c64546746b900d621633f7a1d9b386232b5c21d6430220197f389584d087f34d250ffc8e5908a6ec9651fd02f64f200d3a60abe0df4287012102a1c5150347aa359ad363b7ccaf8602e7538de37935ebb2bb1656e20bfc6cd111ffffffff02b421e428000000001976a91443d6d50fb700dc1d98494942f8c378b8cbbb0def88ac80969800000000001976a9148e10169967933a59a77260277bb6f4d2869ed53088ac00000000" ];*/ $data = [ 1 => [ 'inputs' => [ [ "txid" => "5a373fd13679fc55f479f08bef25d5e808031f97331a48f950ced89d7e99c269", "vout" => 31, "scriptPubKey" => "76a914d17e062579b71bfe199a80991a253d929f8bd35b88ac" ], [ "txid" => "29b509aa81cb4115645b536c14e6c0f7699f5e2228d95c79300f23004aae9aab", "vout" => 123, "scriptPubKey" => "76a914d17e062579b71bfe199a80991a253d929f8bd35b88ac" ], [ "txid" => "e59686315e67427c465d6febe77ce1b93af66f1e25590353743fa95a4c1836c0", "vout" => 1, "scriptPubKey" => "76a914d17e062579b71bfe199a80991a253d929f8bd35b88ac" ], [ "txid" => "00078ef8003e86b1ec57a69842e4a64e54d7dea9dddfb4124f257cb3bf077172", "vout" => 17, "scriptPubKey" => "76a914d17e062579b71bfe199a80991a253d929f8bd35b88ac" ], [ "txid" => "fe4d7c39fdc034b8c5497a0ff07c17ea68bc02734f5247a5db616a12002086fb", "vout" => 57, "scriptPubKey" => "76a914d17e062579b71bfe199a80991a253d929f8bd35b88ac" ], [ "txid" => "8acd7cc80178a00404dfa9061a0028d74239a4bddebf54eacd0fcf657cb535db", "vout" => 9, "scriptPubKey" => "76a914d17e062579b71bfe199a80991a253d929f8bd35b88ac" ], [ "txid" => "2d3631bc56b34e845bfbf90bb30b473601a5dd03ffbadb92db98ab4de1f89f53", "vout" => 31, "scriptPubKey" => "76a914d17e062579b71bfe199a80991a253d929f8bd35b88ac" ], [ "txid" => "d79ef324ffdeacbad1d8f02ec9dd3707277f1ec1365a2f0e8fa5d027bfab0dbc", "vout" => 17, "scriptPubKey" => "76a914d17e062579b71bfe199a80991a253d929f8bd35b88ac" ] ], 'outputs' => [ "15XjXdS1qTBy3i8vCCriWSAbm1qx5JgJVz" => BitcoinLib::toSatoshi(0.14750000), "1L6hCPsCq7C5rNzq7wSyu4eaQCq8LeipmG" => BitcoinLib::toSatoshi(0.01373172) ] ], ]; foreach ($data as $test) { $create = RawTransaction::create($test['inputs'], $test['outputs'], '00'); $this->assertTrue(is_string($create)); } } public function testCreateRawOutputStructs() { /* * struct 1: * [address => value, ] */ $inputs = [ [ "txid" => "5a373fd13679fc55f479f08bef25d5e808031f97331a48f950ced89d7e99c269", "vout" => 31, "scriptPubKey" => "76a914d17e062579b71bfe199a80991a253d929f8bd35b88ac" ], ]; $outputs = [ "15XjXdS1qTBy3i8vCCriWSAbm1qx5JgJVz" => BitcoinLib::toSatoshi(0.14750000), "1L6hCPsCq7C5rNzq7wSyu4eaQCq8LeipmG" => BitcoinLib::toSatoshi(0.01373172) ]; $raw = RawTransaction::create($inputs, $outputs); $tx = RawTransaction::decode($raw); $this->assertEquals("15XjXdS1qTBy3i8vCCriWSAbm1qx5JgJVz", $tx['vout'][0]['scriptPubKey']['addresses'][0]); $this->assertEquals(BitcoinLib::toSatoshi(0.14750000), $tx['vout'][0]['value']); $this->assertEquals("1L6hCPsCq7C5rNzq7wSyu4eaQCq8LeipmG", $tx['vout'][1]['scriptPubKey']['addresses'][0]); $this->assertEquals(BitcoinLib::toSatoshi(0.01373172), $tx['vout'][1]['value']); /* * struct 2: * [['address' => address, 'value' => value], ] */ $inputs = [ [ "txid" => "5a373fd13679fc55f479f08bef25d5e808031f97331a48f950ced89d7e99c269", "vout" => 31, "scriptPubKey" => "76a914d17e062579b71bfe199a80991a253d929f8bd35b88ac" ], ]; $outputs = [ ['address' => "15XjXdS1qTBy3i8vCCriWSAbm1qx5JgJVz", 'value' => BitcoinLib::toSatoshi(0.14750000)], ['address' => "1L6hCPsCq7C5rNzq7wSyu4eaQCq8LeipmG", 'value' => BitcoinLib::toSatoshi(0.01373172)] ]; $raw = RawTransaction::create($inputs, $outputs); $tx = RawTransaction::decode($raw); $this->assertEquals("15XjXdS1qTBy3i8vCCriWSAbm1qx5JgJVz", $tx['vout'][0]['scriptPubKey']['addresses'][0]); $this->assertEquals(BitcoinLib::toSatoshi(0.14750000), $tx['vout'][0]['value']); $this->assertEquals("1L6hCPsCq7C5rNzq7wSyu4eaQCq8LeipmG", $tx['vout'][1]['scriptPubKey']['addresses'][0]); $this->assertEquals(BitcoinLib::toSatoshi(0.01373172), $tx['vout'][1]['value']); /* * struct 3: * [[address, value], ] */ $inputs = [ [ "txid" => "5a373fd13679fc55f479f08bef25d5e808031f97331a48f950ced89d7e99c269", "vout" => 31, "scriptPubKey" => "76a914d17e062579b71bfe199a80991a253d929f8bd35b88ac" ], ]; $outputs = [ ["15XjXdS1qTBy3i8vCCriWSAbm1qx5JgJVz", BitcoinLib::toSatoshi(0.14750000)], ["1L6hCPsCq7C5rNzq7wSyu4eaQCq8LeipmG", BitcoinLib::toSatoshi(0.01373172)] ]; $raw = RawTransaction::create($inputs, $outputs); $tx = RawTransaction::decode($raw); $this->assertEquals("15XjXdS1qTBy3i8vCCriWSAbm1qx5JgJVz", $tx['vout'][0]['scriptPubKey']['addresses'][0]); $this->assertEquals(BitcoinLib::toSatoshi(0.14750000), $tx['vout'][0]['value']); $this->assertEquals("1L6hCPsCq7C5rNzq7wSyu4eaQCq8LeipmG", $tx['vout'][1]['scriptPubKey']['addresses'][0]); $this->assertEquals(BitcoinLib::toSatoshi(0.01373172), $tx['vout'][1]['value']); } public function testCreateRawOpReturn() { /* * struct 2: * [['address' => address, 'value' => value], ] */ $inputs = [ [ "txid" => "5a373fd13679fc55f479f08bef25d5e808031f97331a48f950ced89d7e99c269", "vout" => 31, "scriptPubKey" => "76a914d17e062579b71bfe199a80991a253d929f8bd35b88ac" ], ]; $outputs = [ ['address' => "15XjXdS1qTBy3i8vCCriWSAbm1qx5JgJVz", 'value' => BitcoinLib::toSatoshi(0.14750000)], ['scriptPubKey' => "6a" /* OP_RETURN */ . "04" /* PUSH4 */ . bin2hex("TEST"), 'value' => 0] ]; $raw = RawTransaction::create($inputs, $outputs); $tx = RawTransaction::decode($raw); $this->assertEquals("010000000169c2997e9dd8ce50f9481a33971f0308e8d525ef8bf079f455fc7936d13f375a1f00000000ffffffff023011e100000000001976a91431b07b8df3c19573388bb688b4fd89f6233f5d7988ac0000000000000000066a045445535400000000", $raw); $this->assertEquals("15XjXdS1qTBy3i8vCCriWSAbm1qx5JgJVz", $tx['vout'][0]['scriptPubKey']['addresses'][0]); $this->assertEquals(BitcoinLib::toSatoshi(0.14750000), $tx['vout'][0]['value']); $script = explode(" ", $tx['vout'][1]['scriptPubKey']['asm']); $this->assertEquals(2, count($script)); $this->assertEquals("OP_RETURN", $script[0]); $this->assertEquals("TEST", hex2bin($script[1])); } public function testCreateRawMultipleOutputsSameAddress() { /* * struct 2: * [['address' => address, 'value' => value], ] */ $inputs = [ [ "txid" => "5a373fd13679fc55f479f08bef25d5e808031f97331a48f950ced89d7e99c269", "vout" => 31, "scriptPubKey" => "76a914d17e062579b71bfe199a80991a253d929f8bd35b88ac" ], ]; $outputs = [ ['address' => "15XjXdS1qTBy3i8vCCriWSAbm1qx5JgJVz", 'value' => BitcoinLib::toSatoshi(0.14750000)], ['address' => "15XjXdS1qTBy3i8vCCriWSAbm1qx5JgJVz", 'value' => BitcoinLib::toSatoshi(0.01373172)] ]; $raw = RawTransaction::create($inputs, $outputs); $tx = RawTransaction::decode($raw); $this->assertEquals("15XjXdS1qTBy3i8vCCriWSAbm1qx5JgJVz", $tx['vout'][0]['scriptPubKey']['addresses'][0]); $this->assertEquals(BitcoinLib::toSatoshi(0.14750000), $tx['vout'][0]['value']); $this->assertEquals("15XjXdS1qTBy3i8vCCriWSAbm1qx5JgJVz", $tx['vout'][1]['scriptPubKey']['addresses'][0]); $this->assertEquals(BitcoinLib::toSatoshi(0.01373172), $tx['vout'][1]['value']); /* * struct 3: * [[address, value], ] */ $inputs = [ [ "txid" => "5a373fd13679fc55f479f08bef25d5e808031f97331a48f950ced89d7e99c269", "vout" => 31, "scriptPubKey" => "76a914d17e062579b71bfe199a80991a253d929f8bd35b88ac" ], ]; $outputs = [ ["15XjXdS1qTBy3i8vCCriWSAbm1qx5JgJVz", BitcoinLib::toSatoshi(0.14750000)], ["15XjXdS1qTBy3i8vCCriWSAbm1qx5JgJVz", BitcoinLib::toSatoshi(0.01373172)] ]; $raw = RawTransaction::create($inputs, $outputs); $tx = RawTransaction::decode($raw); $this->assertEquals("15XjXdS1qTBy3i8vCCriWSAbm1qx5JgJVz", $tx['vout'][0]['scriptPubKey']['addresses'][0]); $this->assertEquals(BitcoinLib::toSatoshi(0.14750000), $tx['vout'][0]['value']); $this->assertEquals("15XjXdS1qTBy3i8vCCriWSAbm1qx5JgJVz", $tx['vout'][1]['scriptPubKey']['addresses'][0]); $this->assertEquals(BitcoinLib::toSatoshi(0.01373172), $tx['vout'][1]['value']); } public function testSign() { // 1 loop takes ~0.22s $cnt = (getenv('BITCOINLIB_EXTENSIVE_TESTING') ?: 1) * 5; $inputs = array( array( 'txid' => '6737e1355be0566c583eecd48bf8a5e1fcdf2d9f51cc7be82d4393ac9555611c', 'vout' => 0 ) ); $outputs = array('1PGa6cMAzzrBpTtfvQTzX5PmUxsDiFzKyW' => BitcoinLib::toSatoshi(0.00015)); $json_inputs = json_encode( array( array( 'txid' => '6737e1355be0566c583eecd48bf8a5e1fcdf2d9f51cc7be82d4393ac9555611c', 'vout' => 0, // OP_DUP OP_HASH160 push14bytes PkHash OP_EQUALVERIFY OP_CHECKSIG 'scriptPubKey' => '76a914' . '7e3f939e8ded8c0d93695310d6d481ae5da39616' . '88ac' ) ) ); $wallet = array(); RawTransaction::private_keys_to_wallet($wallet, array('L2V4QgXVUyWVoMGejTj7PrRUUCEi9D9Y1AhUM8E6f5yJm7gemgN6'), '00'); $raw_transaction = RawTransaction::create($inputs, $outputs); for ($i = 0; $i < $cnt; $i++) { $sign = RawTransaction::sign($wallet, $raw_transaction, $json_inputs); $this->assertTrue(RawTransaction::validate_signed_transaction($sign['hex'], $json_inputs, null, null, /* allowHighS */ false)); } } public function testPayToScriptHashSignedTransaction() { $data = [ 0 => [ 'tx' => '01000000012228bfe4d2ddd0818d39a81c9e0d41472790eab9c7409749c3b4c65061e1956300000000fd1e0100483045022100900883802edd7db97447182f69c49bc04c7eacc977bed53bc15e9ba648799fde02205146c913b5cdd8ebe03b9babde8631184ac8b6d7735ba8c2ac8da96d891632f601483045022100d57786b2b5f5cdf9211d355f75b87e3049ed9b4bd8ecd95cbb12c76f06bd5fc9022059dbbe08fc8d203fe54acef7163e53d59e8ffd1b4e202d7a53612114d9521897014c89522103386ad259758077336d6301323a8c1ee61ebf819e272e52353a0af76f2d495aee21022d1f8dde5155dee03cf8586f57d06df9100455c6942d7e1fec8892a2499e5a474104fc97d46d5c117eb3c631af52dade567d6ecce84935f3f0ce5df869fe120760f2ee4ecdec9f9efccbe05fb1debca6da055198cfe8adab8795e271916edae9ebc253aeffffffff02d8270000000000001976a9148dde681a2482740d5022bfd61a00c5c9ecc6b7fe88ac584d0000000000001976a9146c2bab1726f4582fbdfb4cd31549b05679cd97c688ac00000000', 'inputs' => [ [ "txid" => "6395e16150c6b4c3499740c7b9ea902747410d9e1ca8398d81d0ddd2e4bf2822", "vout" => 0, "scriptPubKey" => "a914a1e64962519b43be719392eab45eed5cf1198f4087", "redeemScript" => "522103386ad259758077336d6301323a8c1ee61ebf819e272e52353a0af76f2d495aee21022d1f8dde5155dee03cf8586f57d06df9100455c6942d7e1fec8892a2499e5a474104fc97d46d5c117eb3c631af52dade567d6ecce84935f3f0ce5df869fe120760f2ee4ecdec9f9efccbe05fb1debca6da055198cfe8adab8795e271916edae9ebc253ae" ] ], 'outputs' => [ "3GT4b2TDowpMnvn5xSpPhxCGvFfgNg3gfo" => 0.00040000, "1PtY9BWxhGJRM3G4J1bQUXABNUhUsecdpE" => 0.05040048 ] ]]; foreach ($data as $test) { $this->assertTrue(RawTransaction::validate_signed_transaction($test['tx'], json_encode($test['inputs']), '00')); } } public function testPayToPubKeyHashSignedTransaction() { $data = [ 1 => [ // Tx : c58ebf5e342191dc9a1797b308ea5c707aa8ea762543184931246b48689a2761
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
true
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/tests/BIP39Test.php
tests/BIP39Test.php
<?php use BitWasp\BitcoinLib\BIP32; use BitWasp\BitcoinLib\BIP39\BIP39; use BitWasp\BitcoinLib\BitcoinLib; class BIP39Test extends PHPUnit_Framework_TestCase { /** * test vectors as defined here: https://github.com/trezor/python-mnemonic/blob/master/vectors.json * * @var array */ private $vectors = array( "english" => array( array( "00000000000000000000000000000000", "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", "c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04" ), array( "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", "legal winner thank year wave sausage worth useful legal winner thank yellow", "2e8905819b8723fe2c1d161860e5ee1830318dbf49a83bd451cfb8440c28bd6fa457fe1296106559a3c80937a1c1069be3a3a5bd381ee6260e8d9739fce1f607" ), array( "80808080808080808080808080808080", "letter advice cage absurd amount doctor acoustic avoid letter advice cage above", "d71de856f81a8acc65e6fc851a38d4d7ec216fd0796d0a6827a3ad6ed5511a30fa280f12eb2e47ed2ac03b5c462a0358d18d69fe4f985ec81778c1b370b652a8" ), array( "ffffffffffffffffffffffffffffffff", "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong", "ac27495480225222079d7be181583751e86f571027b0497b5b5d11218e0a8a13332572917f0f8e5a589620c6f15b11c61dee327651a14c34e18231052e48c069" ), array( "000000000000000000000000000000000000000000000000", "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon agent", "035895f2f481b1b0f01fcf8c289c794660b289981a78f8106447707fdd9666ca06da5a9a565181599b79f53b844d8a71dd9f439c52a3d7b3e8a79c906ac845fa" ), array( "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal will", "f2b94508732bcbacbcc020faefecfc89feafa6649a5491b8c952cede496c214a0c7b3c392d168748f2d4a612bada0753b52a1c7ac53c1e93abd5c6320b9e95dd" ), array( "808080808080808080808080808080808080808080808080", "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter always", "107d7c02a5aa6f38c58083ff74f04c607c2d2c0ecc55501dadd72d025b751bc27fe913ffb796f841c49b1d33b610cf0e91d3aa239027f5e99fe4ce9e5088cd65" ), array( "ffffffffffffffffffffffffffffffffffffffffffffffff", "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo when", "0cd6e5d827bb62eb8fc1e262254223817fd068a74b5b449cc2f667c3f1f985a76379b43348d952e2265b4cd129090758b3e3c2c49103b5051aac2eaeb890a528" ), array( "0000000000000000000000000000000000000000000000000000000000000000", "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art", "bda85446c68413707090a52022edd26a1c9462295029f2e60cd7c4f2bbd3097170af7a4d73245cafa9c3cca8d561a7c3de6f5d4a10be8ed2a5e608d68f92fcc8" ), array( "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth title", "bc09fca1804f7e69da93c2f2028eb238c227f2e9dda30cd63699232578480a4021b146ad717fbb7e451ce9eb835f43620bf5c514db0f8add49f5d121449d3e87" ), array( "8080808080808080808080808080808080808080808080808080808080808080", "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic bless", "c0c519bd0e91a2ed54357d9d1ebef6f5af218a153624cf4f2da911a0ed8f7a09e2ef61af0aca007096df430022f7a2b6fb91661a9589097069720d015e4e982f" ), array( "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo vote", "dd48c104698c30cfe2b6142103248622fb7bb0ff692eebb00089b32d22484e1613912f0a5b694407be899ffd31ed3992c456cdf60f5d4564b8ba3f05a69890ad" ), array( "77c2b00716cec7213839159e404db50d", "jelly better achieve collect unaware mountain thought cargo oxygen act hood bridge", "b5b6d0127db1a9d2226af0c3346031d77af31e918dba64287a1b44b8ebf63cdd52676f672a290aae502472cf2d602c051f3e6f18055e84e4c43897fc4e51a6ff" ), array( "b63a9c59a6e641f288ebc103017f1da9f8290b3da6bdef7b", "renew stay biology evidence goat welcome casual join adapt armor shuffle fault little machine walk stumble urge swap", "9248d83e06f4cd98debf5b6f010542760df925ce46cf38a1bdb4e4de7d21f5c39366941c69e1bdbf2966e0f6e6dbece898a0e2f0a4c2b3e640953dfe8b7bbdc5" ), array( "3e141609b97933b66a060dcddc71fad1d91677db872031e85f4c015c5e7e8982", "dignity pass list indicate nasty swamp pool script soccer toe leaf photo multiply desk host tomato cradle drill spread actor shine dismiss champion exotic", "ff7f3184df8696d8bef94b6c03114dbee0ef89ff938712301d27ed8336ca89ef9635da20af07d4175f2bf5f3de130f39c9d9e8dd0472489c19b1a020a940da67" ), array( "0460ef47585604c5660618db2e6a7e7f", "afford alter spike radar gate glance object seek swamp infant panel yellow", "65f93a9f36b6c85cbe634ffc1f99f2b82cbb10b31edc7f087b4f6cb9e976e9faf76ff41f8f27c99afdf38f7a303ba1136ee48a4c1e7fcd3dba7aa876113a36e4" ), array( "72f60ebac5dd8add8d2a25a797102c3ce21bc029c200076f", "indicate race push merry suffer human cruise dwarf pole review arch keep canvas theme poem divorce alter left", "3bbf9daa0dfad8229786ace5ddb4e00fa98a044ae4c4975ffd5e094dba9e0bb289349dbe2091761f30f382d4e35c4a670ee8ab50758d2c55881be69e327117ba" ), array( "2c85efc7f24ee4573d2b81a6ec66cee209b2dcbd09d8eddc51e0215b0b68e416", "clutch control vehicle tonight unusual clog visa ice plunge glimpse recipe series open hour vintage deposit universe tip job dress radar refuse motion taste", "fe908f96f46668b2d5b37d82f558c77ed0d69dd0e7e043a5b0511c48c2f1064694a956f86360c93dd04052a8899497ce9e985ebe0c8c52b955e6ae86d4ff4449" ), array( "eaebabb2383351fd31d703840b32e9e2", "turtle front uncle idea crush write shrug there lottery flower risk shell", "bdfb76a0759f301b0b899a1e3985227e53b3f51e67e3f2a65363caedf3e32fde42a66c404f18d7b05818c95ef3ca1e5146646856c461c073169467511680876c" ), array( "7ac45cfe7722ee6c7ba84fbc2d5bd61b45cb2fe5eb65aa78", "kiss carry display unusual confirm curtain upgrade antique rotate hello void custom frequent obey nut hole price segment", "ed56ff6c833c07982eb7119a8f48fd363c4a9b1601cd2de736b01045c5eb8ab4f57b079403485d1c4924f0790dc10a971763337cb9f9c62226f64fff26397c79" ), array( "4fa1a8bc3e6d80ee1316050e862c1812031493212b7ec3f3bb1b08f168cabeef", "exile ask congress lamp submit jacket era scheme attend cousin alcohol catch course end lucky hurt sentence oven short ball bird grab wing top", "095ee6f817b4c2cb30a5a797360a81a40ab0f9a4e25ecd672a3f58a0b5ba0687c096a6b14d2c0deb3bdefce4f61d01ae07417d502429352e27695163f7447a8c" ), array( "18ab19a9f54a9274f03e5209a2ac8a91", "board flee heavy tunnel powder denial science ski answer betray cargo cat", "6eff1bb21562918509c73cb990260db07c0ce34ff0e3cc4a8cb3276129fbcb300bddfe005831350efd633909f476c45c88253276d9fd0df6ef48609e8bb7dca8" ), array( "18a2e1d81b8ecfb2a333adcb0c17a5b9eb76cc5d05db91a4", "board blade invite damage undo sun mimic interest slam gaze truly inherit resist great inject rocket museum chief", "f84521c777a13b61564234bf8f8b62b3afce27fc4062b51bb5e62bdfecb23864ee6ecf07c1d5a97c0834307c5c852d8ceb88e7c97923c0a3b496bedd4e5f88a9" ), array( "15da872c95a13dd738fbf50e427583ad61f18fd99f628c417a61cf8343c90419", "beyond stage sleep clip because twist token leaf atom beauty genius food business side grid unable middle armed observe pair crouch tonight away coconut", "b15509eaa2d09d3efd3e006ef42151b30367dc6e3aa5e44caba3fe4d3e352e65101fbdb86a96776b91946ff06f8eac594dc6ee1d3e82a42dfe1b40fef6bcc3fd" ), array( "38fe1937dd2135d7ca5e472565c41ded449d8cea2e70e1c93571c21831c82f0f466c3d94f29bff1d0cce3e85a22b93364627af716ee91a477d6e2e55abf4e761", "decline valid evil ripple battle typical city similar century comfort alter surround endorse shoe post sock tide endless fragile loud loan tomato rotate trip history uncover device dawn vault major decline spawn peasant frame snow middle kit reward roof cash electric twin merit prize satisfy inhale lyrics lucky", "d9a9b65c54df4104349d5ce6f9275f249160ddf378deff6e540f5492e449e0378ee20b1622bef982f6dddb003568e449fee66335cb45cbe3f8a41050b251238a" ), ), "japanese" => array( array( "00000000000000000000000000000000", "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", "ba553eedefe76e67e2602dc20184c564010859faada929a090dd2c57aacb204ceefd15404ab50ef3e8dbeae5195aeae64b0def4d2eead1cdc728a33ced520ffd" ) ), ); public function setup() { // ensure we're set to bitcoin and not bitcoin-testnet BitcoinLib::setMagicByteDefaults('bitcoin'); } public function testPBKDF2() { $mnemonic = "legal winner thank year wave sausage worth useful legal winner thank yellow"; $passphrase = "TREZOR"; $salt = "mnemonic{$passphrase}"; $result = "2e8905819b8723fe2c1d161860e5ee1830318dbf49a83bd451cfb8440c28bd6fa457fe1296106559a3c80937a1c1069be3a3a5bd381ee6260e8d9739fce1f607"; $this->assertEquals($result, hash_pbkdf2("sha512", $mnemonic, $salt, 2048, 64 * 2, false)); } public function testEntropyToMnemonicVectors() { foreach ($this->vectors["english"] as $vector) { $this->assertEquals($vector[1], BIP39::entropyToMnemonic($vector[0])); } } public function testMnemonicToEntropyVectors() { foreach ($this->vectors["english"] as $vector) { $this->assertEquals($vector[0], BIP39::mnemonicToEntropy($vector[1])); } } public function testMnemonicToSeedHexVectors() { foreach ($this->vectors["english"] as $vector) { $this->assertEquals($vector[2], BIP39::mnemonicToSeedHex($vector[1], 'TREZOR')); } } public function testMnemonicWrongLength() { $e = null; try { BIP39::mnemonicToEntropy("sleep kitten"); } catch (\Exception $e) { } $this->assertTrue(!!$e, "No exception was thrown for invalid mnemonic"); } public function testMnemonicUnknownWords() { $e = null; try { BIP39::mnemonicToEntropy("turtle front uncle idea crush write shrug there lottery flower risky shell"); } catch (\Exception $e) { } $this->assertTrue(!!$e, "No exception was thrown for unknown words"); } public function testInvalidChecksum() { $e = null; try { BIP39::mnemonicToEntropy("sleep kitten sleep kitten sleep kitten sleep kitten sleep kitten sleep kitten"); } catch (\Exception $e) { } $this->assertTrue(!!$e, "No exception was thrown for checksum mismatch"); } public function testUTF8Passwords() { // UTF-8 passphrase $this->assertEquals($this->vectors["japanese"][0][2], BIP39::mnemonicToSeedHex($this->vectors["japanese"][0][1], "㍍ガバヴァぱばぐゞちぢ十人十色")); // Already normalized UTF-8 passphrase $this->assertEquals($this->vectors["japanese"][0][2], BIP39::mnemonicToSeedHex($this->vectors["japanese"][0][1], "メートルガバヴァぱばぐゞちぢ十人十色")); } public function testValidChars() { $letters = array_flip(str_split("abcdefghijklmnopqrstuvwxyz")); foreach (BIP39::defaultWordList()->getWords() as $word) { foreach (str_split($word) as $letter) { $this->assertTrue(isset($letters[$letter]), "{$word} is not a valid word"); } } } public function testGenerate() { for ($i = 0; $i < 100; $i++) { $entropy = BIP39::generateEntropy(128); $this->assertTrue(!!$entropy); $mnemonic = BIP39::entropyToMnemonic($entropy); $this->assertTrue(!!$entropy); $entropy2 = BIP39::mnemonicToEntropy($mnemonic); $this->assertTrue(!!$entropy2); $this->assertEquals($entropy, $entropy2); $bip32 = BIP32::master_key(BIP39::mnemonicToSeedHex($mnemonic, 'PASSWORD')); $this->assertTrue(!!$bip32); } for ($i = 0; $i < 100; $i++) { $entropy = BIP39::generateEntropy(256); $this->assertTrue(!!$entropy); $mnemonic = BIP39::entropyToMnemonic($entropy); $this->assertTrue(!!$entropy); $entropy2 = BIP39::mnemonicToEntropy($mnemonic); $this->assertTrue(!!$entropy2); $this->assertEquals($entropy, $entropy2); $bip32 = BIP32::master_key(BIP39::mnemonicToSeedHex($mnemonic, 'PASSWORD')); $this->assertTrue(!!$bip32); } for ($i = 0; $i < 100; $i++) { $entropy = BIP39::generateEntropy(512); $this->assertTrue(!!$entropy); $mnemonic = BIP39::entropyToMnemonic($entropy); $this->assertTrue(!!$entropy); $entropy2 = BIP39::mnemonicToEntropy($mnemonic); $this->assertTrue(!!$entropy2); $this->assertEquals($entropy, $entropy2); $bip32 = BIP32::master_key(BIP39::mnemonicToSeedHex($mnemonic, 'PASSWORD')); $this->assertTrue(!!$bip32); } } }
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/tests/BitcoinLibTest.php
tests/BitcoinLibTest.php
<?php use BitWasp\BitcoinLib\BitcoinLib; class BitcoinLibTest extends PHPUnit_Framework_TestCase { protected $testHexEncode_i; protected $addressVersion; protected $WIFVersion; protected $keyConversionData = array(); public function __construct() { $this->addressVersion = '00'; $this->p2shAddressVersion = '05'; $this->WIFVersion = '80'; $this->keyConversionData = array( "5HxWvvfubhXpYYpS3tJkw6fq9jE9j18THftkZjHHfmFiWtmAbrj" => "1QFqqMUD55ZV3PJEJZtaKCsQmjLT6JkjvJ", "5KC4ejrDjv152FGwP386VD1i2NYc5KkfSMyv1nGy1VGDxGHqVY3" => "1F5y5E5FMc5YzdJtB9hLaUe43GDxEKXENJ", "Kwr371tjA9u2rFSMZjTNun2PXXP3WPZu2afRHTcta6KxEUdm1vEw" => "1NoJrossxPBKfCHuJXT4HadJrXRE9Fxiqs" ); } public function setup() { // ensure we're set to bitcoin and not bitcoin-testnet BitcoinLib::setMagicByteDefaults('bitcoin'); } public function tearDown() { } public function testPrivateKeyVersion() { $this->assertEquals($this->WIFVersion, BitcoinLib::get_private_key_address_version($this->addressVersion)); } ////////////////////////////////////////////////////// // hex_encode() test functions // public function _testHexEncode_result($hex) { $this->assertEquals($this->testHexEncode_i, hexdec($hex)); } public function _testHexEncode_length($hex) { $this->assertTrue(strlen($hex) % 2 == 0); } public function testHexEncode() { $cnt = (getenv('BITCOINLIB_EXTENSIVE_TESTING') ?: 1) * 50; for ($this->testHexEncode_i = 0; $this->testHexEncode_i < $cnt; ($this->testHexEncode_i++)) { $hex = BitcoinLib::hex_encode((string)$this->testHexEncode_i); $this->_testHexEncode_result($hex); $this->_testHexEncode_length($hex); } } /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// // bin2hex() test function public function testBin2Hex() { $cnt = (getenv('BITCOINLIB_EXTENSIVE_TESTING') ?: 1) * 50; for ($i = 0; $i < $cnt; $i++) { $length = mt_rand(1, 32); $hex = (string)bin2hex(mcrypt_create_iv($length, \MCRYPT_DEV_URANDOM)); $this->assertTrue(ctype_xdigit($hex)); } } /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// // hex_decode() test functions public function _testHexDecode_result($dec, $real_val) { $this->assertEquals($dec, $real_val); } public function testHexDecodeBaseConvert() { $cnt = (getenv('BITCOINLIB_EXTENSIVE_TESTING') ?: 1) * 100; // Base_Convert handles UP TO 8 bytes. for ($i = 0; $i < $cnt; $i++) { $length = mt_rand(1, 7); // Generate a random length hex string. $hex = (string)bin2hex(mcrypt_create_iv($length, \MCRYPT_DEV_URANDOM)); // Get real decimal result. $dec = base_convert($hex, 16, 10); // handles big ints better than hexdec. $this->assertEquals(BitcoinLib::hex_decode($hex), $dec); } } public function testHexDecodeGMP() { $cnt = (getenv('BITCOINLIB_EXTENSIVE_TESTING') ?: 1) * 100; // GMP has no real upper limit on the number of bytes! for ($i = 0; $i < $cnt; $i++) { $length = mt_rand(1, 5000); // Generate a random length hex string. $hex = (string)bin2hex(mcrypt_create_iv($length, \MCRYPT_DEV_URANDOM)); // Get real decimal result. $dec = gmp_strval(gmp_init($hex, 16), 10); $this->assertEquals(BitcoinLib::hex_decode($hex), $dec); } } /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// // base58_encode() & base58_decode() tests for consistency public function testBase58FunctionsForConsistency() { $cnt = (getenv('BITCOINLIB_EXTENSIVE_TESTING') ?: 1) * 50; for ($i = 0; $i < $cnt; $i++) { // Generate a random length hex string. $hex = (string)bin2hex(mcrypt_create_iv(20, \MCRYPT_DEV_URANDOM)); $encode = BitcoinLib::base58_encode($hex); $decode = BitcoinLib::base58_decode($encode); $this->assertTrue($hex == $decode); } } /* public function _testBase58EncodeValues($data, $equals) { $this->assertEquals($data, $equals); }*/ public function testBase58EncodeValues() { // Taken from Bitcoin Core's ./src/tests/data/base58_encode_decode.json file $tests = ["" => "", "61" => "2g", "626262" => "a3gV", "636363" => "aPEr", "73696d706c792061206c6f6e6720737472696e67" => "2cFupjhnEsSn59qHXstmK2ffpLv2", "00eb15231dfceb60925886b67d065299925915aeb172c06647" => "1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L", "516b6fcd0f" => "ABnLTmg", "bf4f89001e670274dd" => "3SEo3LWLoPntC", "572e4794" => "3EFU7m", "ecac89cad93923c02321" => "EJDM8drfXA6uyA", "10c8511e" => "Rt5zm", "00000000000000000000" => "1111111111"]; foreach ($tests as $data => $equals) { $res = BitcoinLib::base58_encode(trim($data)); $this->assertEquals($res, $equals); } } /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// // base58_check testing public function testBase58CheckEncode() { $cnt = (getenv('BITCOINLIB_EXTENSIVE_TESTING') ?: 1) * 50; for ($i = 0; $i < $cnt; $i++) { // random, 20-byte string. $hex = (string)bin2hex(mcrypt_create_iv(20, \MCRYPT_DEV_URANDOM)); // 'manually' create address $encode = BitcoinLib::base58_encode_checksum($this->addressVersion . $hex); $decode = BitcoinLib::base58_decode_checksum($encode); // validate 'manually' created address $this->assertTrue(BitcoinLib::validate_address($encode, $this->addressVersion, $this->p2shAddressVersion)); // validate 'manually' created address without specifying the address version // relying on the defaults $this->assertTrue(BitcoinLib::validate_address($encode)); // validate 'manually' created address // disable address version and P2S address version specifically $this->assertFalse(BitcoinLib::validate_address($encode, false, null)); $this->assertTrue(BitcoinLib::validate_address($encode, null, false)); // validate 'manually' $this->assertTrue($hex == $decode); // create address $check2 = BitcoinLib::hash160_to_address($hex, $this->addressVersion); // validate created address $this->assertTrue(BitcoinLib::validate_address($check2, $this->addressVersion, $this->p2shAddressVersion)); // validate created address without specifying the address version // relying on the defaults $this->assertTrue(BitcoinLib::validate_address($check2)); // validate created address // disable address version and P2S address version specifically $this->assertFalse(BitcoinLib::validate_address($check2, false, null)); $this->assertTrue(BitcoinLib::validate_address($check2, null, false)); // validate 'manually' $this->assertTrue($check2 == $encode); // create address, without specifying the address version // relying on the defaults $check3 = BitcoinLib::hash160_to_address($hex); // validate created address $this->assertTrue(BitcoinLib::validate_address($check3, $this->addressVersion, $this->p2shAddressVersion)); // validate created address without specifying the address version // relying on the defaults $this->assertTrue(BitcoinLib::validate_address($check3)); // validate created address // disable address version and P2S address version specifically $this->assertFalse(BitcoinLib::validate_address($check3, false, null)); $this->assertTrue(BitcoinLib::validate_address($check3, null, false)); // validate 'manually' $this->assertTrue($check3 == $encode); } } public function testBase58CheckEncodeP2SH() { $cnt = (getenv('BITCOINLIB_EXTENSIVE_TESTING') ?: 1) * 50; for ($i = 0; $i < $cnt; $i++) { // random, 20-byte string. $hex = (string)bin2hex(mcrypt_create_iv(20, \MCRYPT_DEV_URANDOM)); // 'manually' create address $encode = BitcoinLib::base58_encode_checksum($this->p2shAddressVersion . $hex); $decode = BitcoinLib::base58_decode_checksum($encode); // validate 'manually' created address $this->assertTrue(BitcoinLib::validate_address($encode, $this->addressVersion, $this->p2shAddressVersion)); // validate 'manually' created address without specifying the address version // relying on the defaults $this->assertTrue(BitcoinLib::validate_address($encode)); // validate 'manually' created address // disable address version and P2S address version specifically $this->assertTrue(BitcoinLib::validate_address($encode, false, null)); $this->assertFalse(BitcoinLib::validate_address($encode, null, false)); // validate 'manually' $this->assertTrue($hex == $decode); // create address $check2 = BitcoinLib::hash160_to_address($hex, $this->p2shAddressVersion); // validate created address $this->assertTrue(BitcoinLib::validate_address($check2, $this->addressVersion, $this->p2shAddressVersion)); // validate created address without specifying the address version // relying on the defaults $this->assertTrue(BitcoinLib::validate_address($check2)); // validate created address // disable address version and P2S address version specifically $this->assertTrue(BitcoinLib::validate_address($check2, false, null)); $this->assertFalse(BitcoinLib::validate_address($check2, null, false)); // validate 'manually' $this->assertTrue($check2 == $encode); // create address, without specifying the address version // relying on the defaults $check3 = BitcoinLib::hash160_to_address($hex, 'p2sh'); // validate created address $this->assertTrue(BitcoinLib::validate_address($check3, $this->addressVersion, $this->p2shAddressVersion)); // validate created address without specifying the address version // relying on the defaults $this->assertTrue(BitcoinLib::validate_address($check3)); // validate created address // disable address version and P2S address version specifically $this->assertTrue(BitcoinLib::validate_address($check3, false, null)); $this->assertFalse(BitcoinLib::validate_address($check3, null, false)); // validate 'manually' $this->assertTrue($check3 == $encode); } } public function testKeyConversion() { $tests = $this->keyConversionData; foreach ($tests as $priv_key => $true_address) { $priv_key = trim($priv_key); $priv_key_info = BitcoinLib::WIF_to_private_key($priv_key); $pubkey = BitcoinLib::private_key_to_public_key($priv_key_info['key'], $priv_key_info['is_compressed']); // validate public key to address $this->assertEquals(BitcoinLib::public_key_to_address($pubkey, $this->addressVersion), $true_address); // validate public key to address, without specifying address version $this->assertEquals(BitcoinLib::public_key_to_address($pubkey), $true_address); } } /////////////////////////////////////////////////////// public function testGetPrivKeyWif() { $cnt = (getenv('BITCOINLIB_EXTENSIVE_TESTING') ?: 1) * 5; for ($i = 0; $i < $cnt; $i++) { $hex = (string)str_pad(bin2hex(mcrypt_create_iv(32, \MCRYPT_DEV_URANDOM)), 64, '0', STR_PAD_LEFT); // create private key and WIF $wif = BitcoinLib::private_key_to_WIF($hex, FALSE, $this->addressVersion); $key = BitcoinLib::WIF_to_private_key($wif); $this->assertTrue($key['key'] == $hex); // create private key and WIF, without specifying address version $wif = BitcoinLib::private_key_to_WIF($hex, FALSE); $key = BitcoinLib::WIF_to_private_key($wif); $this->assertTrue($key['key'] == $hex); } } public function testImportPublicKey() { $cnt = (getenv('BITCOINLIB_EXTENSIVE_TESTING') ?: 1) * 1; for ($i = 0; $i < $cnt; $i++) { $hex = (string)str_pad(bin2hex(mcrypt_create_iv(32, \MCRYPT_DEV_URANDOM)), 64, '0', STR_PAD_LEFT); $public = BitcoinLib::private_key_to_public_key($hex, FALSE); $import = BitcoinLib::import_public_key($public); $this->assertTrue($import !== FALSE); } } public function testPublicKeyCompressionFaultKeys() { $cnt = (getenv('BITCOINLIB_EXTENSIVE_TESTING') ?: 1) * 2; for ($i = 0; $i < $cnt; $i++) { $hex = (string)str_pad(bin2hex(mcrypt_create_iv(32, \MCRYPT_DEV_URANDOM)), 64, '0', STR_PAD_LEFT); $public = BitcoinLib::private_key_to_public_key($hex, FALSE); $compress = BitcoinLib::compress_public_key($public); $decompress = BitcoinLib::decompress_public_key($compress); $this->assertTrue($decompress['public_key'] == $public); } } public function testPublicKeyCompression() { $cnt = (getenv('BITCOINLIB_EXTENSIVE_TESTING') ?: 1) * 2; for ($i = 0; $i < $cnt; $i++) { $key = BitcoinLib::get_new_private_key(); $public = BitcoinLib::private_key_to_public_key($key, FALSE); $compress = BitcoinLib::compress_public_key($public); $decompress = BitcoinLib::decompress_public_key($compress); $this->assertTrue($decompress['public_key'] == $public); } } public function testValidatePublicKey() { $cnt = (getenv('BITCOINLIB_EXTENSIVE_TESTING') ?: 1) * 2; for ($i = 0; $i < $cnt; $i++) { $set = BitcoinLib::get_new_key_set($this->addressVersion); $this->assertTrue(BitcoinLib::validate_public_key($set['pubKey'])); } } public function testPrivateKeyValidation() { $cnt = (getenv('BITCOINLIB_EXTENSIVE_TESTING') ?: 1) * 5; $val = FALSE; for ($i = 0; $i < $cnt; $i++) { $key = BitcoinLib::get_new_key_set($this->addressVersion, $val); $val = ($val == FALSE) ? TRUE : FALSE; $this->assertTrue(BitcoinLib::validate_WIF($key['privWIF'], $this->WIFVersion)); } } public function testImportUncompOrCompPublicKey() { $cnt = (getenv('BITCOINLIB_EXTENSIVE_TESTING') ?: 1) * 5; $val = FALSE; for ($i = 0; $i < $cnt; $i++) { $key = BitcoinLib::get_new_private_key(); $unc = BitcoinLib::private_key_to_public_key($key, FALSE); $pubkey = BitcoinLib::private_key_to_public_key($key, $val); $val = ($val == FALSE) ? TRUE : FALSE; $this->assertTrue($unc == BitcoinLib::import_public_key($pubkey)); } } public function testSatoshiConversion() { $toSatoshi = [ ["0.00000001", "1", 1], [0.00000001, "1", 1], ["0.29560000", "29560000", 29560000], [0.29560000, "29560000", 29560000], ["1.0000009", "100000090", 100000090], [1.0000009, "100000090", 100000090], ["1.00000009", "100000009", 100000009], [1.00000009, "100000009", 100000009], ["21000000.00000001", "2100000000000001", 2100000000000001], [21000000.00000001, "2100000000000001", 2100000000000001], ["21000000.0000009", "2100000000000090", 2100000000000090], [21000000.0000009, "2100000000000090", 2100000000000090], ["21000000.00000009", "2100000000000009", 2100000000000009], [21000000.00000009, "2100000000000009", 2100000000000009], // this is the max possible amount of BTC (atm) ["210000000.00000009", "21000000000000009", 21000000000000009], [210000000.00000009, "21000000000000009", 21000000000000009], // thee fail because when the BTC value is converted to a float it looses precision // ["2100000000.00000009", "210000000000000009", 210000000000000009], // [2100000000.00000009, "210000000000000009", 210000000000000009], ]; $toBTC = [ ["1", "0.00000001"], [1, "0.00000001"], ["29560000", "0.29560000"], [29560000, "0.29560000"], ["100000090", "1.00000090"], [100000090, "1.00000090"], ["100000009", "1.00000009"], [100000009, "1.00000009"], ["2100000000000001", "21000000.00000001"], [2100000000000001, "21000000.00000001"], ["2100000000000090", "21000000.00000090"], [2100000000000090, "21000000.00000090"], ["2100000000000009", "21000000.00000009"], // this is the max possible amount of BTC (atm) [2100000000000009, "21000000.00000009"], ["21000000000000009", "210000000.00000009"], [21000000000000009, "210000000.00000009"], ["210000000000000009", "2100000000.00000009"], [210000000000000009, "2100000000.00000009"], ["2100000000000000009", "21000000000.00000009"], [2100000000000000009, "21000000000.00000009"], // these fail because they're > PHP_INT_MAX // ["21000000000000000009", "210000000000.00000009"], // [21000000000000000009, "210000000000.00000009"], ]; foreach ($toSatoshi as $i => $test) { $btc = $test[0]; $satoshiString = $test[1]; $satoshiInt = $test[2]; $string = BitcoinLib::toSatoshiString($btc); $this->assertEquals($satoshiString, $string, "[{$i}] {$btc} => {$satoshiString} =? {$string}"); $this->assertTrue($satoshiString === $string, "[{$i}] {$btc} => {$satoshiString} ==? {$string}"); $int = BitcoinLib::toSatoshi($btc); $this->assertEquals($satoshiInt, $int, "[{$i}] {$btc} => {$satoshiInt} =? {$int}"); $this->assertTrue($satoshiInt === $int, "[{$i}] {$btc} => {$satoshiInt} ==? {$int}"); } foreach ($toBTC as $i => $test) { $satoshi = $test[0]; $btc = $test[1]; $this->assertEquals($btc, BitcoinLib::toBTC($satoshi), "[{$i}] {$satoshi} => {$btc}"); $this->assertTrue($btc === BitcoinLib::toBTC($satoshi), "[{$i}] {$satoshi} => {$btc}"); } } }
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/tests/ElectrumTest.php
tests/ElectrumTest.php
<?php use BitWasp\BitcoinLib\BitcoinLib; use BitWasp\BitcoinLib\Electrum; class ElectrumTest extends PHPUnit_Framework_TestCase { public function __construct() { $this->magic_byte = '00'; } public function setup() { // ensure we're set to bitcoin and not bitcoin-testnet BitcoinLib::setMagicByteDefaults('bitcoin'); } public function tearDown() { } public function testMnemonicDecode() { $mnemonic = trim('teach start paradise collect blade chill gay childhood creek picture creator branch'); $known_seed = 'dcb85458ec2fcaaac54b71fba90bd4a5'; $known_secexp = '74b1f6c0caae485b4aeb2f26bab3cabdec4f0b432751bd454fe11b2d2907cbda'; $known_mpk = '819519e966729f31e1855eb75133d9e7f0c31abaadd8f184870d62771c62c2e759406ace1dee933095d15e4c719617e252f32dc0465393055f867aee9357cd52'; $known_addresses = ["", "", "", "", ""]; $seed = Electrum::decode_mnemonic($mnemonic); $this->assertEquals($seed, $known_seed); $mpk = Electrum::generate_mpk($seed); $this->assertEquals($mpk, $known_mpk); $secexp = Electrum::stretch_seed($seed); $secexp = $secexp['seed']; $this->assertEquals($secexp, $known_secexp); $count_known_addresses = count($known_addresses); for ($i = 0; $i < $count_known_addresses; $i++) { $privkey = Electrum::generate_private_key($secexp, $i, 0); $address_private_deriv = BitcoinLib::private_key_to_address($privkey, $this->magic_byte); $public_deriv = Electrum::public_key_from_mpk($mpk, $i); $address_private_deriv = BitcoinLib::public_key_to_address($public_deriv, $this->magic_byte); } } } ;
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/tests/BitcoinLibTestNetTest.php
tests/BitcoinLibTestNetTest.php
<?php use BitWasp\BitcoinLib\BitcoinLib; require_once(__DIR__ . '/BitcoinLibTest.php'); class BitcoinLibTestNetTest extends BitcoinLibTest { public function __construct() { parent::__construct(); $this->addressVersion = '6f'; $this->p2shAddressVersion = 'c4'; $this->WIFVersion = 'ef'; $this->keyConversionData = array( "5HxWvvfubhXpYYpS3tJkw6fq9jE9j18THftkZjHHfmFiWtmAbrj" => "n4mo8QZBt6zjpVmr28rx985jdiw9zwfcvS", "5KC4ejrDjv152FGwP386VD1i2NYc5KkfSMyv1nGy1VGDxGHqVY3" => "mubvNHAEAdWomjnVtifiQPrNuFpf6cT8ie", "Kwr371tjA9u2rFSMZjTNun2PXXP3WPZu2afRHTcta6KxEUdm1vEw" => "n3KG9rxrmQcaSJmX26RS7VqdiX1w3iSB5t" ); } public function setup() { parent::setup(); // ensure we're set to bitcoin-testnet and not bitcoin BitcoinLib::setMagicByteDefaults('bitcoin-testnet'); } }
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/tests/ScriptTest.php
tests/ScriptTest.php
<?php use BitWasp\BitcoinLib\RawTransaction; class ScriptTest extends PHPUnit_Framework_TestCase { public function testPushData() { $data = json_decode(file_get_contents(__DIR__ . "/data/pushdata.json"), true); foreach ($data as $row) { $script = ''; array_map( function ($value) use (&$script) { $script .= RawTransaction::pushdata($value); }, $row['pushes'] ); $this->assertSame($row['script'], $script); } } public function testPushDataOps() { $data = json_decode(file_get_contents(__DIR__ . "/data/pushdataops.json"), true); foreach ($data as $row) { $script = RawTransaction::pushdata($row['string']); $op = substr($script, 0, 2); $this->assertSame($row['op'], $op); } } }
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/examples/full_transaction.php
examples/full_transaction.php
<?php use BitWasp\BitcoinLib\BitcoinLib; use BitWasp\BitcoinLib\RawTransaction; require_once(__DIR__. '/../vendor/autoload.php'); // spending from transaction 6737e1355be0566c583eecd48bf8a5e1fcdf2d9f51cc7be82d4393ac9555611c 1st output (vout=0) // value of output is 0.0002 $inputs = array( array( 'txid' => '6737e1355be0566c583eecd48bf8a5e1fcdf2d9f51cc7be82d4393ac9555611c', 'vout' => 0, 'value' => 0.0002, 'scriptPubKey' => '76a9147e3f939e8ded8c0d93695310d6d481ae5da3961688ac', ) ); // sum up the total amount of coins we're spending $inputsTotal = 0; foreach ($inputs as $input) { $inputsTotal += $input['value']; } // fixed fee $fee = 0.0001; // information of who we're sending coins to and how much $to = '1PGa6cMAzzrBpTtfvQTzX5PmUxsDiFzKyW'; $send = 0.00005; // calculate change $change = $inputsTotal - $send - $fee; // this is our own address $changeAddress = "1CWYJZ4vSoemSCrfBvXreqEtojEeCUeKw3"; // create ouputs, one to recipient and one to change $outputs = array( $to => BitcoinLib::toSatoshi($send), $changeAddress => BitcoinLib::toSatoshi($change), ); // import private key $wallet = array(); RawTransaction::private_keys_to_wallet($wallet, array('L2V4QgXVUyWVoMGejTj7PrRUUCEi9D9Y1AhUM8E6f5yJm7gemgN6'), '00'); // crate unsigned raw transaction $raw_transaction = RawTransaction::create($inputs, $outputs); // sign the transaction // to broadcast transaction take this value and `bitcoin-cli sendrawtransaction <hex>` $sign = RawTransaction::sign($wallet, $raw_transaction, json_encode($inputs)); print_r($sign); echo "\n"; // set the transaction hash from the raw transaction $txid = RawTransaction::txid_from_raw($sign['hex']); print_r($txid); echo "\n";
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/examples/bip32_preparing_multisig.php
examples/bip32_preparing_multisig.php
<?php use BitWasp\BitcoinLib\BIP32; use BitWasp\BitcoinLib\RawTransaction; require_once(__DIR__. '/../vendor/autoload.php'); echo "Lets start off by generating a wallet for each of the 'users'.\n"; echo "This will be stored on their machine.\n"; $wallet[0] = BIP32::master_key('b861e093a58718e145b9791af35fb111'); $wallet[1] = BIP32::master_key('b861e093a58718e145b9791af35fb222'); $wallet[2] = BIP32::master_key('b861e093a58718e145b9791af35fb333'); print_r($wallet); echo "Now we will generate a m/0' extended key. These will yield a private key\n"; $user[0] = BIP32::build_key($wallet[0][0], "3'"); $user[1] = BIP32::build_key($wallet[1][0], "23'"); $user[2] = BIP32::build_key($wallet[2][0], "9'"); print_r($user); // As the previous is a private key, we should convert to the corresponding // public key: M/0' echo "As the previous is a private key, we should convert it to the corresponding\n"; echo "public key: M/0' \n"; $pub[0] = BIP32::extended_private_to_public($user[0]); $pub[1] = BIP32::extended_private_to_public($user[1]); $pub[2] = BIP32::extended_private_to_public($user[2]); print_r($pub); echo "This is the key you will ask your users for. For repeated transactions\n"; echo "BIP32 allows you to deterministically generate public keys, meaning less\n"; echo "effort for everyone involved\n\n"; echo "Now we can generate many multisignature addresses from what we have here: \n"; for($i = 0; $i < 3; $i++) { $bip32key[0] = BIP32::build_key($pub[0], "0/{$i}"); $bip32key[1] = BIP32::build_key($pub[1], "0/{$i}"); $bip32key[2] = BIP32::build_key($pub[2], "0/{$i}"); print_r($bip32key); $pubkey[0] = BIP32::extract_public_key($bip32key[0]); $pubkey[1] = BIP32::extract_public_key($bip32key[1]); $pubkey[2] = BIP32::extract_public_key($bip32key[2]); print_r($pubkey); print_r(RawTransaction::create_multisig(2, $pubkey)); }
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/examples/multisig.php
examples/multisig.php
<?php use BitWasp\BitcoinLib\BitcoinLib; use BitWasp\BitcoinLib\RawTransaction; require_once(__DIR__ . '/../vendor/autoload.php'); $m = 2; $publicKeys = [ '0379ddc228d8c44a85ae30c877a6b037ec3d627e0507f223a0412790a83a46cd5f', '024d1cf2ca917f4d679fc02df2a39c0a8110a1b6935b27ae6762a0ceeec7752801', '0258f70f6400aa6f60ff0d21c3aaf1ca236d177877d2b9ad9d2c55280e375ab2d2' ]; // It's recommended that you sort the public keys before creating multisig // Someday this might be standardized in BIP67; https://github.com/bitcoin/bips/pull/146 // Many other libraries already do this too! RawTransaction::sort_multisig_keys($publicKeys); // Create redeem script $redeemScript = RawTransaction::create_multisig($m, $public_keys); // Display data echo "Public Keys: \n"; foreach ($publicKeys as $i => $publicKey) { echo "{$i} : {$publicKey} \n"; } echo "\n"; echo "Redeem Script: \n"; echo "{$redeemScript['redeem_script']} \n\n"; echo "Address: \n"; echo "{$redeemScript['address']} \n\n";
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/examples/bip39.php
examples/bip39.php
<?php use BitWasp\BitcoinLib\BIP32; use BitWasp\BitcoinLib\BIP39\BIP39; require_once(__DIR__. '/../vendor/autoload.php'); $password = "my-oh-so-secret-password"; $entropy = BIP39::generateEntropy(256); $mnemonic = BIP39::entropyToMnemonic($entropy); $seed = BIP39::mnemonicToSeedHex($mnemonic, $password); unset($entropy); // ignore, forget about this, don't use it! var_dump($mnemonic); // this is what you print on a piece of paper, etc var_dump($password); // this is secret of course var_dump($seed); // this is what you use to generate a key $key = BIP32::master_key($seed); // enjoy
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/examples/test_bip32.php
examples/test_bip32.php
<?php use BitWasp\BitcoinLib\BIP32; require_once(__DIR__. '/../vendor/autoload.php'); echo "bip32 tests - https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Test_Vectors \n\n"; echo "test one\n"; $master = BIP32::master_key('000102030405060708090a0b0c0d0e0f'); echo "Chain m\n"; echo " ext priv:\n ".$master[0]."\n"; $public = BIP32::extended_private_to_public($master); echo " ext pub:\n ".$public[0]."\n"; echo "Chain m/0h\n"; $key = BIP32::build_key($master, "0'"); echo " ext priv:\n ".$key[0]."\n"; $public = BIP32::extended_private_to_public($key); echo " ext pub: \n ".$public[0]."\n"; echo "Chain m/0h/1\n"; $key = BIP32::build_key($key, '1'); echo " ext priv:\n ".$key[0]."\n"; $public = BIP32::extended_private_to_public($key); echo " ext pub: \n ".$public[0]."\n"; echo "Chain m/0h/1/2h\n"; $key = BIP32::build_key($key, "2'"); echo " ext priv:\n ".$key[0]."\n"; $public = BIP32::extended_private_to_public($key); echo " ext pub: \n ".$public[0]."\n"; echo "Chain m/0h/1/2h/2\n"; $key = BIP32::build_key($key, "2"); echo " ext priv:\n ".$key[0]."\n"; $public = BIP32::extended_private_to_public($key); echo " ext pub: \n ".$public[0]."\n"; echo "Chain m/0h/1/2h/2/1000000000\n"; $key = BIP32::build_key($key, "1000000000"); echo " ext priv:\n ".$key[0]."\n"; $public = BIP32::extended_private_to_public($key); echo " ext pub: \n ".$public[0]."\n\n\n\n"; echo "test two\n"; $master = BIP32::master_key('fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542'); echo "Chain m\n"; echo " ext priv:\n ".$master[0]."\n"; $public = BIP32::extended_private_to_public($master); echo " ext pub:\n ".$public[0]."\n"; echo "Chain m/0\n"; $key = BIP32::build_key($master, '0'); echo " ext priv:\n ".$key[0]."\n"; $public = BIP32::extended_private_to_public($key); echo " ext pub: \n ".$public[0]."\n"; echo "Chain m/0/2147483647'\n"; $key = BIP32::build_key($key, "2147483647'"); echo " ext priv:\n ".$key[0]."\n"; $public = BIP32::extended_private_to_public($key); echo " ext pub: \n ".$public[0]."\n"; echo "Chain m/0/2147483647'/1\n"; $key = BIP32::build_key($key, "1"); echo " ext priv:\n ".$key[0]."\n"; $public = BIP32::extended_private_to_public($key); echo " ext pub: \n ".$public[0]."\n"; echo "Chain m/0/2147483647'/1/2147483646'\n"; $key = BIP32::build_key($key, "2147483646'"); echo " ext priv:\n ".$key[0]."\n"; $public = BIP32::extended_private_to_public($key); echo " ext pub: \n ".$public[0]."\n"; echo "Chain m/0/2147483647'/1/2147483646'/2\n"; $key = BIP32::build_key($key, "2"); echo " ext priv:\n ".$key[0]."\n"; $public = BIP32::extended_private_to_public($key); echo " ext pub: \n ".$public[0]."\n";
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/examples/bitcoin.php
examples/bitcoin.php
<?php use BitWasp\BitcoinLib\BitcoinLib; require_once(__DIR__. '/../vendor/autoload.php');; $magic_byte = '00'; $keypair = BitcoinLib::get_new_key_set($magic_byte); echo "Key pair: \n";print_r($keypair); echo "\n"; $compress = BitcoinLib::compress_public_key($keypair['pubKey']); echo "Compressed public key: $compress \n"; $decompress = BitcoinLib::decompress_public_key($compress); echo "Decompressed key info: \n"; print_r($decompress); echo "\n"; $address = BitcoinLib::public_key_to_address($compress, $magic_byte); echo "decoding $address\n"; echo BitcoinLib::base58_decode($address); echo "\n\n"; $sc = '5357'; $ad = BitcoinLib::public_key_to_address($sc, '05'); echo $ad."\n";
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/examples/electrum.php
examples/electrum.php
<?php use BitWasp\BitcoinLib\BitcoinLib; use BitWasp\BitcoinLib\Electrum; require_once(__DIR__. '/../vendor/autoload.php'); $magic_byte = '00'; $string = trim('teach start paradise collect blade chill gay childhood creek picture creator branch'); $seed = Electrum::decode_mnemonic($string); echo "Words: $string\n"; echo "Seed: $seed\n"; $secexp = Electrum::stretch_seed($seed); $secexp = $secexp['seed']; echo "Secret Exponent: $secexp\n"; $mpk = Electrum::generate_mpk($seed); echo "MPK: $mpk\n"; for($i = 0; $i < 5; $i++) { $privkey = Electrum::generate_private_key($secexp, $i, 0); echo "Private key: $privkey\n"; echo "Private WIF: ".BitcoinLib::private_key_to_WIF($privkey, FALSE, $magic_byte)."\n"; $public_key = Electrum::public_key_from_mpk($mpk, $i); echo "Public Key: $public_key\n"; $address = BitcoinLib::public_key_to_address($public_key, $magic_byte); echo "Public derivation: $address.\n"; $address = BitcoinLib::private_key_to_address($privkey, $magic_byte); echo "Private derivation: $address.\n"; echo "-----------\n"; }
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/examples/raw_transaction.php
examples/raw_transaction.php
<?php use BitWasp\BitcoinLib\BitcoinLib; use BitWasp\BitcoinLib\RawTransaction; require_once(__DIR__. '/../vendor/autoload.php'); ///////////////////////////// // Parameters for creation.. // Set up inputs here $inputs = array( array( 'txid' => '6737e1355be0566c583eecd48bf8a5e1fcdf2d9f51cc7be82d4393ac9555611c', 'vout' => 0 ) ); // Set up outputs here. $outputs = array('1PGa6cMAzzrBpTtfvQTzX5PmUxsDiFzKyW' => BitcoinLib::toSatoshi(0.00015)); //////////////////////////// // Parameters for signing. // Create JSON inputs parameter // - These can come from bitcoind, or just knowledge of the txid/vout/scriptPubKey, // and redeemScript if needed. $json_inputs = json_encode( array( array('txid' => '6737e1355be0566c583eecd48bf8a5e1fcdf2d9f51cc7be82d4393ac9555611c', 'vout' => 0, // OP_DUP OP_HASH160 push14bytes PkHash OP_EQUALVERIFY OP_CHECKSIG 'scriptPubKey' => '76a914' . '7e3f939e8ded8c0d93695310d6d481ae5da39616' . '88ac') ) ); // Private Key $wallet = array(); RawTransaction::private_keys_to_wallet($wallet, array('L2V4QgXVUyWVoMGejTj7PrRUUCEi9D9Y1AhUM8E6f5yJm7gemgN6'), '00'); // Create raw transaction $raw_transaction = RawTransaction::create($inputs, $outputs); // Sign the transaction // To broadcast you would send the $sign['hex'] on to the network // eg; with `bitcoind sendrawtransaction <hex>` $sign = RawTransaction::sign($wallet, $raw_transaction, $json_inputs); print_r($sign); echo "\n"; // Get the transaction hash from the raw transaction $txid = RawTransaction::txid_from_raw($sign['hex']); print_r($txid); echo "\n";
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/examples/sign_p2sh_stepbystep.php
examples/sign_p2sh_stepbystep.php
<?php use BitWasp\BitcoinLib\BitcoinLib; use BitWasp\BitcoinLib\RawTransaction; require_once(__DIR__. '/../vendor/autoload.php'); /* * !! TESTNET !! */ BitcoinLib::setMagicByteDefaults("bitcoin-testnet"); /* * address: n3P94USXs7LzfF4BKJVyGv2uCfBQRbvMZJ * priv: cV2BRcdtWoZMSovYCpoY9gyvjiVK5xufpAwdAFk1jdonhGZq1cCm * pub: 03c0b1fd07752ebdd43c75c0a60d67958eeac8d4f5245884477eae094c4361418d * * address: mhsywR248h21gCB8oSwse5tmFSPvo9d5ML * priv: cMps8Dg4Z1ThcwvPiPpshR6cbosYoTrgUwgLcFasBSxsdLHwzoUK * pub: 02ab1fae8dacd465460ad8e0c08cb9c25871782aa539a58b65f9bf1264c355d098 * * address: mh7gsCxi4pcuNyHU9aWD9pGogHNJJZcCta * priv: cNn72iUvQhuzZCWg3TC31fvyNDYttL8emHgMcFJzhF4xnFo8LYCk * pub: 02dc43b58ee5313d1969b939718d2c8104a3365d45f12f91753bfc950d16d3e82e * * 2of3 address: 2N1zEScjXeBDX2Gy4c6ojLTfqjRjSvf7iEC * 2of3 redeem: 522103c0b1fd07752ebdd43c75c0a60d67958eeac8d4f5245884477eae094c4361418d2102ab1fae8dacd465460ad8e0c08cb9c25871782aa539a58b65f9bf1264c355d0982102dc43b58ee5313d1969b939718d2c8104a3365d45f12f91753bfc950d16d3e82e53ae * * funded in TX: 83c5c88e94d9c518f314e30ca0529ab3f8e5e4f14a8936db4a32070005e3b61f */ $redeem_script = "522103c0b1fd07752ebdd43c75c0a60d67958eeac8d4f5245884477eae094c4361418d2102ab1fae8dacd465460ad8e0c08cb9c25871782aa539a58b65f9bf1264c355d0982102dc43b58ee5313d1969b939718d2c8104a3365d45f12f91753bfc950d16d3e82e53ae"; $inputs = array( array( "txid" => "83c5c88e94d9c518f314e30ca0529ab3f8e5e4f14a8936db4a32070005e3b61f", "vout" => 0, "scriptPubKey" => "a9145fe34588f475c5251ff994eafb691a5ce197d18b87", // only needed for RawTransaction::sign "redeemScript" => $redeem_script ) ); $outputs = array( "n3P94USXs7LzfF4BKJVyGv2uCfBQRbvMZJ" => BitcoinLib::toSatoshi(0.00010000) ); $raw_transaction = RawTransaction::create($inputs, $outputs); /* * sign with first key */ $wallet = array(); RawTransaction::private_keys_to_wallet($wallet, array("cV2BRcdtWoZMSovYCpoY9gyvjiVK5xufpAwdAFk1jdonhGZq1cCm")); RawTransaction::redeem_scripts_to_wallet($wallet, array($redeem_script)); $sign = RawTransaction::sign($wallet, $raw_transaction, json_encode($inputs)); print_r($sign); var_dump(2 == $sign['req_sigs'], 1 == $sign['sign_count'], 'false' === $sign['complete']); /* * sign with second key */ $wallet = array(); RawTransaction::private_keys_to_wallet($wallet, array("cMps8Dg4Z1ThcwvPiPpshR6cbosYoTrgUwgLcFasBSxsdLHwzoUK")); RawTransaction::redeem_scripts_to_wallet($wallet, array($redeem_script)); $sign = RawTransaction::sign($wallet, $sign['hex'], json_encode($inputs)); print_r($sign); var_dump(2 == $sign['req_sigs'], 2 == $sign['sign_count'], 'true' === $sign['complete']); /* * sign with third key */ $wallet = array(); RawTransaction::private_keys_to_wallet($wallet, array("cNn72iUvQhuzZCWg3TC31fvyNDYttL8emHgMcFJzhF4xnFo8LYCk")); RawTransaction::redeem_scripts_to_wallet($wallet, array($redeem_script)); $sign = RawTransaction::sign($wallet, $sign['hex'], json_encode($inputs)); print_r($sign); var_dump(2 == $sign['req_sigs'], 3 == $sign['sign_count'], 'true' === $sign['complete']);
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/examples/electrum_address.php
examples/electrum_address.php
<?php use BitWasp\BitcoinLib\Electrum; require_once __DIR__.'/vendor/autoload.php'; $mpk = 'eee6754303a65aa693a459269c8deb55e02e2d03ed427ae4ac498d7ab18f30844e53c10cd84faf2d1cac68da135279a6076c5770934e20651624db6bd72f1670'; echo "Uncompressed Keys: \n"; for($i = 0; $i < 40; $i++){ echo "- ".Electrum::address_from_mpk($mpk, $i, '00', 0, FALSE)."\n"; } echo "\n"; echo "Compressed Keys: \n"; for($i = 0; $i < 40; $i++){ echo "- ".Electrum::address_from_mpk($mpk, $i, '00', 0, TRUE)."\n"; }
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/examples/electrum_sign_multisig.php
examples/electrum_sign_multisig.php
<?php use BitWasp\BitcoinLib\BitcoinLib; use BitWasp\BitcoinLib\RawTransaction; use BitWasp\BitcoinLib\Electrum; require_once(__DIR__. '/../vendor/autoload.php'); // Prompt for the redeem script which created the address. // Sets $decode_redeem_script, $redeem_script, $address, and $script_hash //$redeem_script = '522103793882c7025f32d2bbdd07f145fbf16fea83df6352ef42e38d4137f5a24975cc2102e67b93adc52dfdfa181311610244d98811ecd0a26be65a10b720f417cb8997904104492368cd25892f3a6a618ce750e28f4f1c3c9fec4abd67287cb6450356abc0cfef3358cd39b5390c7ea7e053358c97463741d22d1e9cd2c2d3a528d137fb6bf553ae'; //$decode_redeem_script = RawTransaction::decode_redeem_script($redeem_script); //$script_hash = BitcoinLib::hash160($redeem_script); //$address = BitcoinLib::hash160_to_address($script_hash, '05'); //$raw_transaction = '0100000001c723ef78f22d8563b2d1d61aee1904ef12e28524b87122db87c00d6ebc057c9600000000d40047304402203432bff2b897fe10291ec8a66449cd09d850729434d75207de6b4be843a6596b02201aeeb571d03165974215e50f8fca0dc05d35febbbc95d312cab3cf5ebc337085014c8952210217e9f0793d77e4af65e7b3c158459d51edc54011d24b3d57b9945ac4a3d377852103f868e850aed9be2513b7194cf14421ad8b6ec98f65dbdb8264d8be63d8f6ff17410400a0702140404c2e90b3a50bdcb47efb80afa8f4f3a5ae3226bf9027c3c644ce839aaad770ca287615d123e962afd1a7266974cb8da5c5468ffe3aa41c41f03453aeffffffff02d8270000000000001976a914b24490dbbd5e0f02e7891786991aadd869b5e75b88ac584d0000000000001976a914163f9c401b613a2bc7d1e331972788da0d66f6cc88ac00000000'; //$decoded_transaction = RawTransaction::decode($raw_transaction); //$json_str = ''; //$seed = '6f45ad7f901d7421a6d20d9e797bb73b'; while ( ! isset($redeem_script)) { echo "Enter redeem script: "; $line = trim(fgets(STDIN)); $decode_redeem_script = RawTransaction::decode_redeem_script($line); if ($decode_redeem_script == FALSE) { echo "Not a valid script!\n\n"; unset($decode_redeem_script); } else { $redeem_script = $line; $script_hash = BitcoinLib::hash160($redeem_script); $address = BitcoinLib::hash160_to_address($script_hash,'05'); echo "Learned about {$decode_redeem_script['m']} of {$decode_redeem_script['n']} address: ".$address."\n\n"; } } // Prompt for raw transaction. // Sets $raw_transaction, and $decoded_transaction while ( ! isset($raw_transaction) ) { echo "Enter a raw transaction to sign: "; $line = trim(fgets(STDIN)); $multi = explode(" ", $line); $decoded_transaction = RawTransaction::decode($multi[0]); if($decoded_transaction !== FALSE) { $raw_transaction = $multi[0]; } else { echo "Not a valid raw transaction, or unable to decode.\n\n"; unset($decoded_transaction); } // Try to set the JSON inputs from the given transaction. if (isset($multi[1])) { $dec = json_decode(str_replace("'", "", $multi[1])); $test = TRUE; array_walk($dec, function($e) use (&$test) { if(!is_object($e)) $test = FALSE; }); if($test == TRUE) $json_maybe = str_replace("'", "", $multi[1]); } } // Prompt for JSON inputs // Sets $json_inputs. while ( ! isset($json_str) ) { if(isset($json_maybe)) { $try = json_decode($json_maybe); if ( is_array($try) ) { $to_check = count($try); $i = 0; foreach ($try as &$input) { if (isset($input->txid) AND $decoded_transaction['vin'][$i]['txid'] == $input->txid AND isset($input->vout) AND $decoded_transaction['vin'][$i]['vout'] == $input->vout AND isset($input->scriptPubKey)) { $tx_info = RawTransaction::_get_transaction_type(RawTransaction::_decode_scriptPubKey($input->scriptPubKey)); if ($tx_info['hash160'] == $script_hash) $input->redeemScript = $redeem_script; $to_check--; } $i++; } if ($to_check == 0) { $json_str = json_encode($try); break; } } } echo "\nEnter input data as JSON string (or 'x' to load this from webbtc.com): "; $line = trim(fgets(STDIN)); if ($line == 'x' ) { $inputs = array(); // Loop through inputs: foreach ($decoded_transaction['vin'] as $input) { $get = file_get_contents("http://webbtc.com/tx/{$input['txid']}.hex"); $dec = RawTransaction::decode($get); $pkScript = $dec['vout'][$input['vout']]['scriptPubKey']['hex']; $input = array('txid' => $input['txid'], 'vout' => $input['vout'], 'scriptPubKey' => $pkScript); $tx_info = RawTransaction::_get_transaction_type(RawTransaction::_decode_scriptPubKey($pkScript)); if ($tx_info['hash160'] == $script_hash){ $input['redeemScript'] = $redeem_script; } $inputs[] = $input; } unset($input); unset($tx_info); unset($dec); unset($get); $json_str = json_encode($inputs); } else { $try = @json_decode($line); if ( is_object($try) AND count($try) == count($decoded_transaction['vin']) ) { $to_check = count($try); $i = 0; foreach ($try as &$input) { if (isset($input->txid) AND $decoded_transaction['vin'][$i]['txid'] == $input->txid AND isset($input->vout) AND $decoded_transaction['vin'][$i]['vout'] == $input->vout AND isset($input->scriptPubKey)) { $tx_info = RawTransaction::_get_transaction_type(RawTransaction::_decode_scriptPubKey($input->scriptPubKey)); if ($tx_info['hash160'] == $script_hash) $input->redeemScript = $redeem_script; $to_check--; } $i++; } if($to_check == 0) $json_str = json_encode($try); } } } while (!isset($seed)) { echo "\nEnter electrum seed or mnemonic: "; $line = trim(fgets(STDIN)); if ( ctype_xdigit($line) AND strlen($line) >= 32 ) { $seed = $line; continue; } $decode_mnemonic = Electrum::decode_mnemonic($line); if (strlen($decode_mnemonic) > 29) { $seed = $decode_mnemonic; continue; } echo "Not a valid seed, or too weak ( < 128 bit)\n\n"; } echo "Seed accepted.\n\n"; // Learn how many keys we put into the redeem script. $seed = Electrum::stretch_seed($seed); $seed = $seed['seed']; $master_public_key = Electrum::generate_mpk($seed); $private_keys = array(); $have_keys = 0; $done = FALSE; // Loop until the user is satisfied they have found all keys. $j = 0; $offset = 30; while ($done == FALSE) { $start = $offset*$j; echo "Trying keys {$start} to ".($start+$offset)."\n"; // Do public derivation to learn which private keys to derive. for ($i = $start; $i < ($start+$offset); $i++) { $pubkey = Electrum::public_key_from_mpk($master_public_key, $i); if (in_array($pubkey, $decode_redeem_script['keys'])) { $private_keys[] = BitcoinLib::private_key_to_WIF(Electrum::generate_private_key($seed, $i),FALSE,'00'); $have_keys++; } if ($have_keys == $decode_redeem_script['m']) { $done = TRUE; break; } } $j++; // See if we should continue searching. $ask = FALSE; if ($done == FALSE) { echo "Have ".count($private_keys)." private keys we can sign with. Look for more? (y/n) "; while ($ask == FALSE) { switch(trim(fgets(STDIN))) { case 'y': $ask = TRUE; break; case 'n': $ask = TRUE; $done = TRUE; break; default : echo "Please enter y or n :"; break; } } } } // Initialize wallet with known keys. $wallet = array(); RawTransaction::private_keys_to_wallet($wallet, $private_keys, '00'); RawTransaction::redeem_scripts_to_wallet($wallet, array($redeem_script), '05'); $sign = RawTransaction::sign($wallet, $raw_transaction, $json_str); print_r($sign);
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/examples/signature_verification.php
examples/signature_verification.php
<?php use BitWasp\BitcoinLib\RawTransaction; require_once(__DIR__. '/../vendor/autoload.php'); // Supply a raw transaction to verify $raw_tx = '01000000010a74a5750934ce563a9f18812b73dea945e3796d08be5e2c7e817197b4b0665b000000006a47304402203e2b56c1728f6cdcd531d006f7a17e6608513432113290229762de1d1bc0e76902205a9a41c196845d40dc98b67641fa2a1ae52f714094c9ad1e6b99514fd567d187012103161f0ec2a99876733c7b7f63bdb3cede0980e39f18abd50adad2774bd8fe0917ffffffff02426f0f00000000001976a91402a82b3afaff3c4113d86005f7029301c770c61188acbd0e3f0e010000001976a9146284bcf16e0507a35d28c1608ee1708ed26c839488ac00000000'; // Look up the TxIn transactions to learn about the scriptPubKey.. $json_string = '[{"txid":"5b66b0b49771817e2c5ebe086d79e345a9de732b81189f3a56ce340975a5740a","vout":0,"scriptPubKey":"76a91416489ece44cc457e14f4e882fd9a0ae082fdf6c688ac"}]'; // Perform signature validation! $verify = RawTransaction::validate_signed_transaction($raw_tx, $json_string); var_dump($verify);
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/examples/bip32.php
examples/bip32.php
<?php use BitWasp\BitcoinLib\BIP32; require_once(__DIR__. '/../vendor/autoload.php'); $master = BIP32::master_key(bin2hex(mcrypt_create_iv(64, \MCRYPT_DEV_URANDOM))); // Load a 128 bit key, and convert this to extended key format. //$master = BIP32::master_key('41414141414141414141414141414141414141'); $def = "0'/0"; echo "\nMaster key\n m : {$master[0]} \n"; $key = BIP32::build_key($master, $def); // Define what derivation you wish to calculate. // Display private extended key and the address that's derived from it. echo "Generated key: note that all depth=1 keys are hardened. \n {$key[1]} : {$key[0]}\n"; echo " : ".BIP32::key_to_address($key[0])."\n"; // Convert the extended private key to the public key, and display the // address that's derived from it. $pub = BIP32::extended_private_to_public($key); echo "Public key\n {$pub[1]} : {$pub[0]}\n"; echo " : ".BIP32::key_to_address($pub[0])."\n"; //$nextpub = BIP32::build_key($pub, '0'); //echo "Child key\n"; //echo " {$nextpub[1]} : {$nextpub[0]}\n";
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/examples/altcoin_offline_wallet.php
examples/altcoin_offline_wallet.php
<?php use BitWasp\BitcoinLib\BitcoinLib; require_once(__DIR__. '/../vendor/autoload.php'); $usage = "Usage: php {$argv[0]} <magic byte>\n\n"; $usage.= "Some sample bytes are on this list, but you can chose any 2 character byte.\n"; $usage.= "Bitcoin: 00\t\tTestnet: 6f \n"; $usage.= "Litecoin: 48 \n"; $usage.= "Namecoin: 52 \n"; $usage.= "Auroracoin: 17 \n"; if(count($argv) !== 2) die($usage); $magic_byte = $argv[1]; echo "Generated keypair: (this will not be saved, do not lose this data!)\n"; $keypair = BitcoinLib::get_new_key_set($magic_byte); echo "Key pair: \n";print_r($keypair); echo "\n"; echo "\n";
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/examples/sign_p2sh.php
examples/sign_p2sh.php
<?php use BitWasp\BitcoinLib\RawTransaction; require_once(__DIR__. '/../vendor/autoload.php'); // Transaction this created was spent in: 7f3bf55fdfd7c7858c6a9119ad13d2c2e10cd07186c0f6050bbb7c8b626c8642 // Private keys and redeem scripts $pks = array( '5KKNNaV63GB68zCJAF6CnJTx3Zp71vNDBXcjHTLr6wjd9c2ETmu', 'KynFytiTLa2x8keQQwoEVKvewL5z5D1Hti4FDMU1v8kC3pk5BBhr' ); $rs = array( '52210385fae44cb9f0cf858e0d404baecf78d026fae4cc9dd4343b8562059473c2af7b2102f34a1b64155db258d3a910625bd80fae6adf67d7e5b5f3de03265a4208b552d841040fa9a86f3237237423dd8331dc481c0a949fe11594c5dfa0b54bdc105daa319f9de6547d97c22296d4211073e7cffa71c8d6cd4da639607ca64fca2705e562a353ae' ); // Initialize wallet $wallet = array(); RawTransaction::private_keys_to_wallet($wallet, $pks, '00'); RawTransaction::redeem_scripts_to_wallet($wallet, $rs, '05'); $raw_transaction = '01000000018240b84b90a3ae326e13219dc8a2781661fa28e23129b26fea848dd8e01a0c520000000000ffffffff02d8270000000000001976a914b7119dfb9b5c8aa7157fec48fbe640ea347dc92b88ac584d0000000000001976a914592fb6dc8cf6cd561ec86fd5fbc2a140e5ac7bc988ac00000000'; $json = '[{"txid":"520c1ae0d88d84ea6fb22931e228fa611678a2c89d21136e32aea3904bb84082","vout":0,"scriptPubKey":"a914fb56f0d4845487cc9da00c3e91e63503245f151787","redeemScript":"52210385fae44cb9f0cf858e0d404baecf78d026fae4cc9dd4343b8562059473c2af7b2102f34a1b64155db258d3a910625bd80fae6adf67d7e5b5f3de03265a4208b552d841040fa9a86f3237237423dd8331dc481c0a949fe11594c5dfa0b54bdc105daa319f9de6547d97c22296d4211073e7cffa71c8d6cd4da639607ca64fca2705e562a353ae"}]'; $sign = RawTransaction::sign($wallet, $raw_transaction, $json); print_r($sign);
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false
Bit-Wasp/bitcoin-lib-php
https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/examples/prompt_sign_multisig.php
examples/prompt_sign_multisig.php
<?php use BitWasp\BitcoinLib\BitcoinLib; use BitWasp\BitcoinLib\RawTransaction; require_once(__DIR__. '/../vendor/autoload.php'); while(!isset($redeem_script)) { echo "Enter redeem script: "; $line = trim(fgets(STDIN)); $decode_redeem_script = RawTransaction::decode_redeem_script($line); if($decode_redeem_script == FALSE) { echo "[ERROR]- Not a valid script!\n"; unset($decode_redeem_script); } else { $redeem_script = $line; echo "Learned about {$decode_redeem_script['m']} of {$decode_redeem_script['n']} address: ".BitcoinLib::public_key_to_address($redeem_script, '05')."\n"; } } echo "Enter WIF encoded private keys: \n (1): "; $private_keys = array(); while ("\n" != ($line = fgets(STDIN))) { $line = trim($line); $t = BitcoinLib::validate_WIF($line,'80'); var_dump($t); if(BitcoinLib::validate_WIF($line,'80') == TRUE){ $private_keys[] = $line; } else { echo "Not a valid private key.\n"; } echo " (".(count($private_keys)+1)."): "; } // Initialize wallet $wallet = array(); RawTransaction::private_keys_to_wallet($wallet, $private_keys, '00'); RawTransaction::redeem_scripts_to_wallet($wallet, array($redeem_script), '05'); $raw_transaction = '01000000018240b84b90a3ae326e13219dc8a2781661fa28e23129b26fea848dd8e01a0c520000000000ffffffff02d8270000000000001976a914b7119dfb9b5c8aa7157fec48fbe640ea347dc92b88ac584d0000000000001976a914592fb6dc8cf6cd561ec86fd5fbc2a140e5ac7bc988ac00000000'; $json = '[{"txid":"520c1ae0d88d84ea6fb22931e228fa611678a2c89d21136e32aea3904bb84082","vout":0,"scriptPubKey":"a914fb56f0d4845487cc9da00c3e91e63503245f151787","redeemScript":"52210385fae44cb9f0cf858e0d404baecf78d026fae4cc9dd4343b8562059473c2af7b2102f34a1b64155db258d3a910625bd80fae6adf67d7e5b5f3de03265a4208b552d841040fa9a86f3237237423dd8331dc481c0a949fe11594c5dfa0b54bdc105daa319f9de6547d97c22296d4211073e7cffa71c8d6cd4da639607ca64fca2705e562a353ae"}]'; $sign = RawTransaction::sign($wallet, $raw_transaction, $json); print_r($sign);
php
Unlicense
d4e46fdd1edc29fae7b359d2bde952e37d143c45
2026-01-05T04:49:06.611442Z
false