reud
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # p2pkhを試した この記事は、[法政大学アドベントカレンダー2021](https://adventar.org/calendars/6528)の25日目の記事です。 ![](https://www.oreilly.co.jp/books/images/picture_large978-4-87311-902-1.jpeg) [O'Reilly Japan - プログラミング・ビットコイン](https://www.oreilly.co.jp/books/9784873119021/) ビットコインライブラリをpythonでプログラミングする本を買ったので、勉強のためRustで書きつつ読んでいます。 ちなみに一年位かけて1/3しか進んでいません。就活があったとはいえどうして・・・ アウトプットがしたいので何か書こうかと思います。 ※ ソースコードはRustで書いてますが、まっっっったくRustのお作法を知らないので良ければissueとかで優しく教えてください・・・ ※ 理解優先で話していたり、そもそも内容に自信は無かったりするので間違ってたらごめんなさい # 超ざっくりBitcoin ビットコインの論文は、 [ビザンチン将軍問題 - Wikipedia](https://ja.wikipedia.org/wiki/%E3%83%93%E3%82%B6%E3%83%B3%E3%83%81%E3%83%B3%E5%B0%86%E8%BB%8D%E5%95%8F%E9%A1%8C) これの現実的な解を示しました。 つまり、「**たくさんのコンピューターが相互に繋がっていて、全員が平等の時、何台かコンピューターが壊れていても残り全てのコンピューターは共通認識を保てるよ**」 ってことです。 これにより、管理者なしの全員が平等の状態で、順序付いたデータの保存が可能になりました。データベースでいうトランザクションを順序つけて共有できるようになりました。 ビットコインではトランザクションは以下のような情報を保存しています。 「AさんはBさんに20BTC送る」 「BさんはAさんに10BTC送る」 「BさんはCさんに10BTC送る」 ... 送信の情報さえ保存しておいて、トランザクションの最古から送信の情報を追えば、誰がいくら持ってるのか分かりますよね。ビットコインのウォレットはデータベースに誰がいくら持ってるのか保存しているのではなく、トランザクションの履歴から自分がいくら持っているのかを計算して出しています。 もう少し踏み込みます。 ビットコインを利用してBTCを送信する際、**自分が送る額以上のBTCを持っている**と証明する必要があります。 どう証明するかというと、**自分にBTCが送られているトランザクションを指定する**必要があります。 また、**指定したトランザクションは使用済みになり、お釣りとして自分から自分に送るトランザクションがつくられます** 流れで追いましょう。 1. 一番最初にAさんが1000BTC持っています。(アドレスaのトランザクションで受け取ったとしましょう) 2. AさんはBさんに200BTC送りたいです。 3. Aさんはアドレスaのトランザクションを指定して、 A -> B に 200BTC, A -> A に 800 BTC 送金します。 4. アドレスaのトランザクションは使用済みになりますが、 A -> A のトランザクションで 800 BTC 受け取ります。 受け取ったトランザクションは未使用なので使えます。 といった感じです。難しいね。 もちろん、適当なトランザクションを指定して、「これ受け取り先俺の!w」ってやられるとまずいので、トランザクションを指定する際に検証が必要となります。ここで出てくるのがScript(やっと本題に入った)です。 # BitcoinのScriptの話 トランザクションのoutputにScriptPubKeyと呼ばれるScriptが入ってます。 使用したいトランザクションに対して、outputに応じた、inputとしてScriptSigと呼ばれるScriptを入れることで証明を行います。 Bitcoinで使用されるScriptはスタックベースとなっていて、変数定義とかは無い代わりにスタックを操作していく形となります。 wikiがかなり詳しい: [Script - Bitcoin Wiki](https://en.bitcoin.it/wiki/Script) 上から命令を実行していくわけですが、大きく分けて二つの命令文があります。 - Operation - Element 命令分はバイト列ですが、特定の数字の場合はOperationとなり、数字に応じてスタックを操作したりします。そうで無い場合はスタックに値をプッシュします。 全部の命令終了後に、スタックが空でなくて、先頭要素が0でないならそのスクリプトは正しいとみなされます。 で、Scriptの中でも王道なのがそれが、p2pk(もう使われてないけど)だったり、p2pkhだったりです。 説明はプログラミング・ビットコイン買って、読もう! あとは仮想通貨取引市場超大手のバイナンスが滅茶苦茶分かりやすいGIFで解説していたので↓を読むといいかもしれません。 [ビットコインスクリプトの概要 | Binance Academy](https://academy.binance.com/ja/articles/an-introduction-to-bitcoin-script) # 実装した 色々な(ここに書かれていない)メソッドが絡み合っています [reud/pg-bitcoin](https://github.com/reud/pg-bitcoin) https://github.com/reud/pg-bitcoin/blob/master/src/scripts/script.rs#L259 ```rust= #[test] fn test_p2pkh_script() { // secret let e = new_secp256k1scalarelement_from_i32(12345); // 秘密鍵 let pk = new_secp_256k1privatekey(e); // 公開鍵の圧縮sec let compressed_public_sec = pk.clone().point.compressed_sec(); let compressed_public_sec_hashed = hash160(compressed_public_sec.clone()); // 署名先 let z = digest(Algorithm::SHA256, b"Programming Bitcoin!"); let z = hex_digest(Algorithm::SHA256, &*z); let z = new_secp256k1scalarelement_from_hex_str(&*z).unwrap(); let sig = pk.clone().sign(z.clone()); let mut sig = sig.der(); sig.push(1); // <signature>はDER署名+sighash(01) で表す let script_pub_key_cmds: Vec<Cmd> = vec![ OperationCode(118), // OP_DUP OperationCode(169), // OP_HASH160 Cmd::Element(compressed_public_sec_hashed), // <hash> OperationCode(136), // OP_EQUALVERIFY OperationCode(172), // OP_CHECKSIG ]; let script_sig_cmds: Vec<Cmd> = vec![ Cmd::Element(sig), Cmd::Element(compressed_public_sec.clone()), ]; let pubkey_script = new_script(script_pub_key_cmds); let sig_script = new_script(script_sig_cmds); let combined_script = sig_script + pubkey_script; assert_eq!(combined_script.evaluate(z.clone()), true); } ``` # 参考文献 - [O'Reilly Japan - プログラミング・ビットコイン](https://www.oreilly.co.jp/books/9784873119021/) - [jimmysong/programmingbitcoin: Repository for the book](https://github.com/jimmysong/programmingbitcoin)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully