<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by kkken.eth on Medium]]></title>
        <description><![CDATA[Stories by kkken.eth on Medium]]></description>
        <link>https://medium.com/@ken8989580?source=rss-23c193ee744c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qlW5CwQkzQhmYb5QTvEVZQ.jpeg</url>
            <title>Stories by kkken.eth on Medium</title>
            <link>https://medium.com/@ken8989580?source=rss-23c193ee744c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 18:39:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ken8989580/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[北漂三個月的紀錄]]></title>
            <link>https://ken8989580.medium.com/%E5%8C%97%E6%BC%82%E4%B8%89%E5%80%8B%E6%9C%88%E7%9A%84%E7%B4%80%E9%8C%84-89b0dbcb3b6f?source=rss-23c193ee744c------2</link>
            <guid isPermaLink="false">https://medium.com/p/89b0dbcb3b6f</guid>
            <category><![CDATA[self]]></category>
            <dc:creator><![CDATA[kkken.eth]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 17:47:24 GMT</pubDate>
            <atom:updated>2023-08-07T17:47:24.226Z</atom:updated>
            <content:encoded><![CDATA[<p>不知不覺已經畢業一年了，這一年過得很快，也過得很廢，大部分時間都浪費在軍中，最終來到了我一直想待的城市 — — <strong>台北</strong>，來台北也三個月了，差不多可以來記錄一下畢業這一年到現在的心路歷程，我想應該是個不錯的時間點吧！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NYFGkwdHBzAVQCzGbVa_Hw.jpeg" /><figcaption>下班隨手拍的 101</figcaption></figure><h4>當兵</h4><p>大家都說當兵是人生很重要的一個階段，以前的電影也都把當兵演得很熱血，一群兄弟同甘共苦共患難的感覺，但我這四個月只有一種感覺，「浪費時間」，有多浪費時間呢？大概就是我連花時間寫有多浪費時間都不想寫的程度吧！</p><h4>找工作</h4><p>剛當完兵的時候我就馬上開始找工作，可想而知是非常的不順利，因為我只想找區塊練相關的工作，而這樣的工作多數都要有經驗的即戰力，畢竟通常區塊鏈公司都是新創公司，最後只有拿到一家遊戲公司的 offer，薪水不高，而且還要每週上班六天，當時的我一度真的要去那家公司了。</p><p>而就在我已經沒有別的辦法時，我最後去詢問大學時實習的地方 — The Z Institute，而剛剛好他們有一個正在接的案子，我就加入了這個案子，這是一個 Defi 項目，我到現在還是很感謝他能夠給我這個機會，因為有了這個案子也才有現在的我。</p><p>而中間我也開始嘗試寫些技術部落格，案子大概做了兩三個月，結束之後我又開始了找工作的路，這一次我明顯感受到工作變好找了。</p><blockquote>我發現原來單有技術是不夠的，你還要有能把你的技術表達給別人懂的能力，這兩者缺一不可。</blockquote><p>這一次面試變多了，能夠練習的機會也增加了，我覺得每一次的面試其實都是一個學習機會，我並不把他們當成是在考試，通常面試官都是 Founder 或是 CTO，跟他們聊天的過程中會知道一些我平常不會知道的東西，也能夠了解他們的想法，他們都是怎麼看待一位面試者的，有一個很有趣的面試經驗是我們聊一聊發現我的技能不是這個職位要的，所以就開始很輕鬆地聊天，他非常詳細的跟我解釋了為甚麼矽谷銀行會倒閉，真的非常有趣，這些東西都不是看新聞或者網路文章可以得到的。</p><p>最後我進入了一家保險科技公司 — OneDegree，展開我的北漂生活了。</p><h4>找房地獄</h4><p>這大概比找工作還困難吧，台北的房東都超大牌的，完全不怕沒人租，只不過想要租到一個正常的房子，都是一萬三起跳的，更不用說到最後已經不是錢的問題了，而是那個房東要不要租你的問題，好的房子一出來就馬上一大堆人詢問，每個房東都會對你做身家調查，這大概是台北最大的問題了吧，我也不在這裡花太多篇幅抱怨，畢竟也沒有用。</p><p>最後我找到了一個很不錯的家庭式雅房，其實一開始我也在思考跟不認識的人一起住這樣好嗎，但是幸好運氣不錯，我有一群很好的室友，偶爾會一起去吃飯，互相照顧。</p><h4>現在</h4><p>很多人問我既然可以在家工作，為甚麼還要選擇來台北，經歷那樣的找房地獄，付那貴得要死的租金？這問題有點像為甚麼大家都要去美國留學，做所謂的「美國夢」，明明加拿大 CP 值更高，天氣更舒服，治安更安全，楓葉卡也比綠卡更好拿，為甚麼大家還是去美國？這個問題沒有標準答案，每個人的答案一定都不相同，對我來說，我嚮往這樣的大城市，我喜歡每天都有有趣的事情發生，我喜歡接收到最新的資訊，我喜歡在新聞上看到我家附近的拉麵店有大王具足蟲。</p><p>每當下班時看到信義區車水馬龍，101 聳入雲霄，心理就會冒出一個想法，「沒錯！這就是我想像中的台北」。現在的我有一份我喜歡的工作，很好的公司，很聰明的同事，很照顧人的室友，偶爾吃飯喝酒的朋友，還能有運動的時間，我還能再奢求甚麼呢！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89b0dbcb3b6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[無須抵押品就可以貸款？利用 Aave 實作閃電貸（下）]]></title>
            <link>https://medium.com/taipei-ethereum-meetup/%E7%84%A1%E9%A0%88%E6%8A%B5%E6%8A%BC%E5%93%81%E5%B0%B1%E5%8F%AF%E4%BB%A5%E8%B2%B8%E6%AC%BE-%E5%88%A9%E7%94%A8-aave-%E5%AF%A6%E4%BD%9C%E9%96%83%E9%9B%BB%E8%B2%B8-%E4%B8%8B-abad23d5dad2?source=rss-23c193ee744c------2</link>
            <guid isPermaLink="false">https://medium.com/p/abad23d5dad2</guid>
            <dc:creator><![CDATA[kkken.eth]]></dc:creator>
            <pubDate>Sat, 15 Apr 2023 01:31:01 GMT</pubDate>
            <atom:updated>2023-04-15T01:31:01.410Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/taipei-ethereum-meetup/%E7%84%A1%E9%A0%88%E6%8A%B5%E6%8A%BC%E5%93%81%E5%B0%B1%E5%8F%AF%E4%BB%A5%E8%B2%B8%E6%AC%BE-%E5%88%A9%E7%94%A8-aave-%E5%AF%A6%E4%BD%9C%E9%96%83%E9%9B%BB%E8%B2%B8-%E4%B8%8A-3d8573df00f3">上一篇</a>我們介紹了甚麼是閃電貸，並且介紹了閃電貸的使用場景，這篇我們將介紹閃電貸的合約是如何實現的，並且用 Aave 實作出來。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lDcXj6ayQhtZ7N7F" /><figcaption>Photo by <a href="https://unsplash.com/@steve_j?utm_source=medium&amp;utm_medium=referral">Steve Johnson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>閃電貸流程</h3><p>首先，我們先來看看 Aave 閃電貸的流程是甚麼</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pxOiRKUMcGL-1_t_.png" /></figure><ol><li>對你的合約發起一個交易，你的合約會呼叫 Aave pool 合約裡面的 FlashLoanSimple() 並指定這次閃電貸要借的 token 數量。</li><li>Aave pool 合約執行 FlashLoanSimple() 轉移要借出的 token 到你的合約，並且執行你的合約中的 executeOperation()。</li><li>現在你的合約中擁有從 Aave 借來的貸款，並且可以做你想做的任何事情，等到 executeOperation() 執行成功後，Aave pool 合約會從你的合約中把應該要還的錢加上費用一同償還給 Aave。</li><li>以上所有事情都發生在同一個 transaction 中，因此也會在同一個 block。</li></ol><h3>Aave 閃電貸合約簡介</h3><p>接下來我們透過程式碼來實際看看 Aave 的 FlashLoanSimple() 流程，以下只會列出跟閃電貸有關的程式碼，有興趣的讀者可以到他們的 <a href="https://github.com/aave/aave-v3-core">GitHub</a> 觀看完整的程式碼。</p><ul><li>以下是 <a href="https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/pool/Pool.sol#L427">FlashLoanSimple()</a> 的完整程式碼，可以看到最下面一行的 executeFlashLoanSimple() 才是真正在執行閃電貸的程式碼。</li></ul><pre>// Pool.sol<br><br>function flashLoanSimple(<br>  address receiverAddress,<br>  address asset,<br>  uint256 amount,<br>  bytes calldata params,<br>  uint16 referralCode<br>) public virtual override {<br>  DataTypes.FlashloanSimpleParams memory flashParams = DataTypes.FlashloanSimpleParams({<br>    receiverAddress: receiverAddress,<br>    asset: asset,<br>    amount: amount,<br>    params: params,<br>    referralCode: referralCode,<br>    flashLoanPremiumToProtocol: _flashLoanPremiumToProtocol,<br>    flashLoanPremiumTotal: _flashLoanPremiumTotal<br>  });<br>  FlashLoanLogic.executeFlashLoanSimple(_reserves[asset], flashParams);<br>}</pre><ul><li>接著我們繼續追蹤 <a href="https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/libraries/logic/FlashLoanLogic.sol#L179">executeFlashLoanSimple()</a> 看看他在做甚麼，以下程式 碼只節錄重要部分，可以看到在 require() 裡面的第一個參數是 receiver.executeOperation()，receiver 就是你的合約，他會執行你合約中的 executeOperation()，如果回傳的是 true，代表你的合約已經透過閃電貸做完你想做的事情，接下來會需要償還貸款，那就是 _handleFlashLoanRepayment() 所處理的。</li></ul><pre>// FlashLoanLogic.sol<br><br>function executeFlashLoanSimple(<br>  DataTypes.ReserveData storage reserve,<br>  DataTypes.FlashloanSimpleParams memory params<br>) external {<br><br>  // ...<br><br>  require(<br>    receiver.executeOperation(<br>      params.asset,<br>      params.amount,<br>      totalPremium,<br>      msg.sender,<br>      params.params<br>    ),<br>    Errors.INVALID_FLASHLOAN_EXECUTOR_RETURN<br>  );<br>  <br>  _handleFlashLoanRepayment(<br>    reserve,<br>    DataTypes.FlashLoanRepaymentParams({<br>      asset: params.asset,<br>      receiverAddress: params.receiverAddress,<br>      amount: params.amount,<br>      totalPremium: totalPremium,<br>      flashLoanPremiumToProtocol: params.flashLoanPremiumToProtocol,<br>      referralCode: params.referralCode<br>    })<br>  );<br>}</pre><ul><li>在 <a href="https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/libraries/logic/FlashLoanLogic.sol#L223">_handleFlashLoanRepayment()</a> 中，我們一樣只看最重要的部分，Aave 會從你的合約中將一開始借出的 token 數量，加上使用閃電貸的服務費用，一次轉回來。在這個步驟中，如果你的合約 token 餘額不足，或是 allowance 給的不夠，交易就會被 revert。到這邊整個閃電貸才算是完成。</li></ul><pre>// FlashLoanLogic.sol<br><br>function _handleFlashLoanRepayment(<br>  DataTypes.ReserveData storage reserve,<br>  DataTypes.FlashLoanRepaymentParams memory params<br>) internal {<br><br>  // ...<br><br>  IERC20(params.asset).safeTransferFrom(<br>    params.receiverAddress,<br>    reserveCache.aTokenAddress,<br>    amountPlusPremium<br><br>  // ...<br><br>);</pre><h3>合約實作</h3><p>知道了閃電貸的流程以及 Aave 合約中是如何實作的之後，我們就要開始寫一個自己的合約來呼叫 Aave 的閃電貸 function。</p><ul><li>首先，我們要先將會用到的 Aave 合約下載下來。</li></ul><pre>npm i @aave/core-v3</pre><ul><li>接著引入會使用到的合約並且繼承 FlashLoanSimpleReceiverBase。</li></ul><pre>// FlashLoan.sol<br>// SPDX-License-Identifier: MIT<br>pragma solidity 0.8.10;<br><br>import {FlashLoanSimpleReceiverBase} from &quot;@aave/core-v3/contracts/flashloan/base/FlashLoanSimpleReceiverBase.sol&quot;;<br>import {IPoolAddressesProvider} from &quot;@aave/core-v3/contracts/interfaces/IPoolAddressesProvider.sol&quot;;<br>import {IERC20} from &quot;@aave/core-v3/contracts/dependencies/openzeppelin/contracts/IERC20.sol&quot;;<br><br>contract FlashLoan is FlashLoanSimpleReceiverBase {}</pre><ul><li>實作 constrctor()，這邊需要 _addressProvider 作為 input 是因為 Aave 的借貸池子是可變動的，所以為了要拿到現在可以借貸的池子，Aave 提供了 PoolAddressesProvider 可供查詢，這個參數就是那個合約的地址，可以從 Aave 的 <a href="https://docs.aave.com/developers/deployed-contracts/v3-mainnet/ethereum-mainnet">Doc</a> 查到。</li></ul><pre>constructor(address _addressProvider) FlashLoanSimpleReceiverBase(IPoolAddressesProvider(_addressProvider)) {<br>  owner = payable(msg.sender);<br>}</pre><ul><li>實作 executeOperation() 給 Aave 合約呼叫。</li></ul><pre>function executeOperation(<br>  address asset, <br>  uint256 amount, <br>  uint256 premium, <br>  address initiator, <br>  bytes calldata params<br>) external override returns (bool) {<br>  // Logic you want to implement goes here<br><br>  // Approve the Pool contract allowance to *pull* the owed amount<br>  uint256 amountOwed = amount + premium;<br>  IERC20(asset).approve(address(POOL), amountOwed);<br><br>  return true;<br>}</pre><ul><li>實作 requestFlashLoan() 給 EOA 呼叫，並且呼叫 Aave 的閃電貸 function。</li></ul><pre>function requestFlashLoan(address _token, uint256 _amount) public {<br>  address reciverAddress = address(this);<br>  address asset = _token;<br>  uint256 amount = _amount;<br>  bytes memory params = &quot;&quot;;<br>  uint16 referralCode = 0;<br><br>  POOL.flashLoanSimple(reciverAddress, asset, amount, params, referralCode);<br>}</pre><ul><li>別忘了加上 withdraw()，否則在合約裡面的錢是拿不出來的。</li></ul><pre>function withdraw(address _tokenAddress) external onlyOwner {<br>  IERC20 token = IERC20(_tokenAddress);<br>  token.transfer(msg.sender, token.balanceOf(address(this)));<br>}</pre><p>以上就是利用 Aave 實作閃電貸合約的所有細節，有興趣的讀者可以到<a href="https://github.com/Jin-K-Yang/Flash-loan">這裡</a>查看完整的 repo。</p><h3>Conclusion</h3><p>經過之前的介紹，我們已經對閃電貸有了初步的認識，在這篇文章中我們更深入地了解了閃電貸的合約實現方式以及使用 Aave 實作的例子。希望大家能夠注意任何有可能利用閃電貸所引發的漏洞，同時也能善用區塊鏈的特性，利用閃電貸激盪出與傳統金融截然不同的點子。</p><h3>References</h3><ul><li><a href="https://docs.aave.com/developers/v/2.0/guides/flash-loans">Aave Flash Loans Docs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abad23d5dad2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/taipei-ethereum-meetup/%E7%84%A1%E9%A0%88%E6%8A%B5%E6%8A%BC%E5%93%81%E5%B0%B1%E5%8F%AF%E4%BB%A5%E8%B2%B8%E6%AC%BE-%E5%88%A9%E7%94%A8-aave-%E5%AF%A6%E4%BD%9C%E9%96%83%E9%9B%BB%E8%B2%B8-%E4%B8%8B-abad23d5dad2">無須抵押品就可以貸款？利用 Aave 實作閃電貸（下）</a> was originally published in <a href="https://medium.com/taipei-ethereum-meetup">Taipei Ethereum Meetup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[無須抵押品就可以貸款？利用 Aave 實作閃電貸（上）]]></title>
            <link>https://medium.com/taipei-ethereum-meetup/%E7%84%A1%E9%A0%88%E6%8A%B5%E6%8A%BC%E5%93%81%E5%B0%B1%E5%8F%AF%E4%BB%A5%E8%B2%B8%E6%AC%BE-%E5%88%A9%E7%94%A8-aave-%E5%AF%A6%E4%BD%9C%E9%96%83%E9%9B%BB%E8%B2%B8-%E4%B8%8A-3d8573df00f3?source=rss-23c193ee744c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d8573df00f3</guid>
            <category><![CDATA[flash-loan-attack]]></category>
            <category><![CDATA[arbitrage]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[flash-loan]]></category>
            <dc:creator><![CDATA[kkken.eth]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 01:31:36 GMT</pubDate>
            <atom:updated>2023-03-13T01:31:36.369Z</atom:updated>
            <content:encoded><![CDATA[<p>在 Defi 的領域中，閃電貸扮演著一個非常重要的角色，他是一把雙面刃，本系列將分成上下兩篇文章分別介紹閃電貸以及如何利用去中心化借貸平台 Aave 來實作閃電貸智能合約。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6a7S0J3bRFDeZhel" /><figcaption>Photo by <a href="https://unsplash.com/@steve_j?utm_source=medium&amp;utm_medium=referral">Steve Johnson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>甚麼是閃電貸？</h4><p>閃電貸是一種無需抵押品便可以獲得貸款的方式，而且貸款沒有限制，這是利用以太坊上的交易機制來達到的。<strong>在同一筆交易中借款還款</strong>，交易完成後，以區塊的角度來看，<strong>你的餘額完全沒有改變</strong> ，但其實你已經借了幾百萬美金又還款了，這就是閃電貸的基本原理。</p><p>但你可能會問，如果我沒有還款不就可以拿走這些錢了嗎？以太坊的交易機制保證一筆交易要馬全部執行，要馬完全不執行。如果借款人在交易結束前沒有還款，該交易就會被 revert，回到借款發生前的 state，也就是說<strong>借款從來沒有發生過</strong>。因此，不會發生未還款就完成交易的情況。使用者只會損失這筆交易執行到一半所耗費的 gas fee 而已。</p><h4>常見的閃電貸使用方式</h4><p>因為閃電貸無須抵押品，並且可以立即得到一大筆資金，因此閃電貸的用途涵蓋了非常廣的範圍，以下將介紹幾個閃電貸常用的使用方式。需要注意的是這些使用方式通通都是在 <strong>一個 transaction</strong> 中完成的。</p><blockquote>P.S. 以下範例並沒有將 Defi protocol 的手續費以及 gas fee 考慮進去，在實務上這些都是很重要的一點，例如 Aave 對於使用閃電貸的人會收取一定比例的費用，根據官方文檔，目前是 0.09%，但是會隨著社區治理而變動。</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wlsh2pO9Rqzx0YXV.jpg" /><figcaption><a href="https://www.moonpay.com/learn/defi/defi-flash-loans">https://www.moonpay.com/learn/defi/defi-flash-loans</a></figcaption></figure><p><strong>套利 Arbitrage</strong></p><p>利用閃電貸套利的方式非常多種，以下將解釋最常見的套利方式，利用不同交易所的<strong>價格差</strong>來進行套利。</p><p>假設：</p><ul><li>ETH 在 Uniswap 的價格：2000</li><li>ETH 在 Sushiswap 的價格：2001</li></ul><p>套利步驟為：</p><ol><li>在去中心化借貸平台如 Aave 使用閃電貸借入一筆 USDC。</li><li>在 Uniswap 以 2000 的價格買入 ETH。</li><li>在 Sushiswap 以 2001 的價格賣掉 ETH。</li><li>向 Aave 償還 USDC 貸款。</li><li>賺取差價利潤。</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BtlgdSCyHF4lu_Dc" /><figcaption><a href="https://www.moonpay.com/learn/defi/defi-flash-loans">https://www.moonpay.com/learn/defi/defi-flash-loans</a></figcaption></figure><p><strong>替換抵押品 Collateral Swapping</strong></p><p>假設你在 Aave 抵押了 1 ETH 借到了 1000 USDC，而你覺得 ETH 當抵押品可能相對沒有那麼穩定，你想要換成等值的 BTC 當作抵押品，正常的情況下你必須要先償還 1000 USDC 才能夠做到，但是有了閃電貸的幫助，能夠讓你在不還債的情況下做到這件事，步驟如下：</p><ol><li>在去中心化借貸平台如 Aave 使用閃電貸借入 1000 USDC。</li><li>利用這 1000 USDC 去還債並且將你的抵押品（1 ETH）拿回來。</li><li>將 1 ETH 換成等值的 BTC。</li><li>將等值的 BTC 拿去抵押並借入 1000 USDC。</li><li>利用借入的 1000 USDC 償還閃電貸的貸款。</li></ol><p><strong>清算自己的債務 Self-liquidation</strong></p><p>假設現在 ETH 價格為 2000 USDC，而你在 Aave 抵押了 1 ETH 借到了 1000 USDC，而 ETH 的價格一直下跌到 1500 USDC，即將跌到清算價格，這時候你想要將 ETH 拿回來賣掉止損，正常情況下你需要 1000 USDC 才能夠拿回你抵押的 ETH。但如果使用閃電貸，你可以在沒有錢償還債務的情況下拿回你抵押的 1 ETH，步驟如下：</p><ol><li>在去中心化借貸平台如 Aave 使用閃電貸借入 1000 USDC。</li><li>償還 1000 USDC 的債務並拿回 1 ETH 的抵押品。</li><li>將 1 ETH 換成 1500 USDC。</li><li>使用 1000 USDC 償還閃電貸貸款。</li><li>持有剩下的 500 USDC。</li></ol><h4>閃電貸與預言機攻擊</h4><p>另外一個閃電貸的用途就是駭客攻擊，攻擊手法有非常多種，最常見的一種是<strong>價格預言機攻擊</strong>，駭客可以利用閃電貸瞬間拿到一大筆資金，並且針對使用單一 DEX 餵價的 Defi protocol 進行攻擊。詳細步驟如下：</p><ol><li>攻擊者利用閃電貸借到一筆 token A。</li><li>攻擊者利用 token A 去 Uniswap 交換 token B，導致 tokne A 的價格在 Uniswap 急遽下跌，而 token B 的價格急遽上漲。</li><li>假設有一個借貸平台，他的 token 價格來源只有 Uniswap，這個時候攻擊者向此借貸平台抵押價格上漲的 token B ，然後借出價格下跌的 token A，攻擊者可以借出比正常數量還要多的 token A。</li><li>攻擊者將一部份借出的 token A 償還給閃電貸並且持有剩下的 token A，這些就是攻擊者的營利。</li><li>此筆交易結束後，Uniswap 上的 token A 和 token B 的價格會因為套利行為而回到正常的市場價格，然而這個借貸平台卻借出了不符合抵押品價格的 token A。</li></ol><p>上述攻擊步驟都發生在一筆交易中，然而攻擊者可以重複發出這筆交易，直到合約裡所有的錢都被駭走為止。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TfaButg2WO7cfYyM.png" /><figcaption><a href="https://chain.link/education-hub/flash-loans">https://chain.link/education-hub/flash-loans</a></figcaption></figure><p><strong>那麼，該要如何避免這類攻擊手法呢？</strong></p><p>既然單一來源的餵價會造成問題，那就讓它變成多個來源，也就是說不止參考 Uniswap 的價格，也參考 Sushiswap 的價格，甚至參考一些中心化交易所的價格。目前最多人用的是使用 Chainlink 提供的價格預言機，它的原理就是利用多個價格的中位數，這樣一來如果有其中一個交易所的價格偏離太多，也不會發生任何問題，如果對於 Chainlink 的原理有興趣可以閱讀他們的 <a href="https://blog.chain.link/chainlink-price-feeds-secure-defi/?_ga=2.112211076.1690183760.1677998517-1988017328.1674545803">Doc</a>。</p><h4>Conclusion</h4><p>閃電貸是把雙面刃，既可以用於套利，也可以用於駭客攻擊，而且完全沒有風險，因為如果交易失敗頂多就是損失 gas fee（如果進階一點甚至連交易失敗的 gas fee 都可以用 <a href="https://docs.flashbots.net/flashbots-protect/rpc/quick-start#how-to-use-flashbots-protect-rpc-in-metamask">Flashbots</a> 節省掉）。</p><p>在 Defi 領域中他是聲名狼藉的存在，大多數人聽到閃電貸都會覺得又有攻擊事件發生了，但我認為閃電貸只是提供了一種新的資本利用方法，真正的問題應該是有漏洞的合約。長期來看，閃電貸甚至是有益於整個生態產業的，因為未來的 Defi protocol 工程師都必須要考慮以閃電貸獲得的大量資金會不會是潛在的安全漏洞，進而讓整個 Defi 產業變的更加安全穩固。</p><h4>References</h4><ul><li><a href="https://www.moonpay.com/learn/defi/defi-flash-loans#what-are-flash-loans">DeFi flash loans explained</a></li><li><a href="https://hypertrader.app/use-cases-of-flash-loans/">Use-Cases of Flash Loans</a></li><li><a href="https://medium.com/coinmonks/all-you-need-to-know-about-defi-flash-loans-ca0ff4592d90#b5db">All You Need to Know About DeFi Flash Loans</a></li><li><a href="https://chain.link/education-hub/flash-loans#:~:text=Flash%20Loans%20and%20Price%20Oracle%20Attacks">Flash Loans and Price Oracle Attacks</a></li><li><a href="https://shardeum.org/blog/what-is-a-flash-loan-attack/#How_Do_I_Prevent_a_Flash_Loan_Attack">What is a Flash Loan Attack? And How Do I Prevent it?</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d8573df00f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/taipei-ethereum-meetup/%E7%84%A1%E9%A0%88%E6%8A%B5%E6%8A%BC%E5%93%81%E5%B0%B1%E5%8F%AF%E4%BB%A5%E8%B2%B8%E6%AC%BE-%E5%88%A9%E7%94%A8-aave-%E5%AF%A6%E4%BD%9C%E9%96%83%E9%9B%BB%E8%B2%B8-%E4%B8%8A-3d8573df00f3">無須抵押品就可以貸款？利用 Aave 實作閃電貸（上）</a> was originally published in <a href="https://medium.com/taipei-ethereum-meetup">Taipei Ethereum Meetup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[公鑰、私鑰、地址傻傻分不清！？]]></title>
            <link>https://medium.com/taipei-ethereum-meetup/%E5%85%AC%E9%91%B0-%E7%A7%81%E9%91%B0-%E5%9C%B0%E5%9D%80%E5%82%BB%E5%82%BB%E5%88%86%E4%B8%8D%E6%B8%85-f83b8fe424e?source=rss-23c193ee744c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f83b8fe424e</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[private-key]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[kkken.eth]]></dc:creator>
            <pubDate>Wed, 11 Jan 2023 10:39:04 GMT</pubDate>
            <atom:updated>2023-02-15T03:22:55.137Z</atom:updated>
            <content:encoded><![CDATA[<p>在區塊鏈的世界中，我們時常會用到私鑰簽署交易，但我們真的理解私鑰的意義嗎？而公鑰又是甚麼？和地址又有甚麼區別呢？然而每條區塊鏈所用的 加密方式都不盡相同，本文將會以 Ethereum 為例深入探討這些看似簡單卻又複雜的問題。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n4rSGgp77ube9Y6Y" /><figcaption>Photo by <a href="https://unsplash.com/@jasondeblooisphotography?utm_source=medium&amp;utm_medium=referral">Jason D</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>私鑰 Private Key</h4><p><strong>首先，我們先來探討甚麼是私鑰？</strong></p><blockquote>It is assumed that the sender has a valid private key pr, which is a randomly selected positive integer (represented as a byte array of length 32 in big-endian form) in the range [1, secp256k1n − 1].</blockquote><p>上面是引用 <a href="http://gavwood.com/paper.pdf">Ethereum 黃皮書</a>對私鑰的介紹，其中 <em>secp256k1n = 2²⁵⁶。</em>私鑰其實就是一串隨機數，具體而言，以太坊的私鑰是一串隨機正整數，而這個值的區間位於 <em>1 ~ 2²⁵⁶ — 1 </em>之間，也就是說，它是一串隨機生成的 256 bits 序列。這個 range 是非常巨大的，要生成兩個一樣的私鑰是一件幾乎不可能會發生的事。（如果你無法想像 <em>2²⁵⁶ </em>實際到底有多大，可以觀看以下影片）</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FS9JGmA5_unY%3Fstart%3D289%26feature%3Doembed%26start%3D289&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DS9JGmA5_unY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FS9JGmA5_unY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/44c38ba10c3a70f42986f147ea08805d/href">https://medium.com/media/44c38ba10c3a70f42986f147ea08805d/href</a></iframe><p><strong>而私鑰為甚麼會如此重要呢？</strong></p><p>在真實的世界中，「<strong>擁有</strong>」的定義是領有、具有，得到或者保持著某種東西，你可以透過出示地契證明你擁有某一棟房子。但在區塊鏈的世界中，<strong>擁有</strong>某個東西只不過是在帳本上將你的資產做加法，並且用數學的方式<strong>證明</strong>它的存在，當全世界的人都<strong>認可</strong>這個紀錄，那麼你就<strong>擁有</strong>它，儘管你其實並沒有實際擁有任何東西。簡單來講，當你知道你的私鑰的時候，你就<strong>擁有</strong>你所有的貨幣資產，包括 NFT 和 Token，因為多數人都能夠<strong>證明</strong>這條紀錄是千真萬確的。</p><p>私鑰可以簽署交易，就像在現實生活中需要簽名才能夠轉帳一樣，簽署過後的交易才能夠對你的帳戶資產進行更改。所以雖然在區塊鏈中大家都可以產生一筆交易更動你的資產，但是只有擁有私鑰的人才能夠簽署這筆交易，交易才能被認可和被驗證。</p><blockquote>在現實世界中可以捏造一個假的簽名，完成交易，但是在區塊鏈的世界中，因為它底層的密碼學特性，這件事情是不可能發生的，目前沒有一個人可以在沒有私鑰的情況下簽署交易。</blockquote><blockquote>Not Your Keys, Not Your Coins</blockquote><p>這也是上面這句格言的由來，如果有人<strong>知道</strong>你的私鑰，那麼他就<strong>擁有</strong>你所有的資產了，許多駭客就是透過釣魚信件和瀏覽器快取在你沒發現的情況下竊取你的私鑰，進而盜走你的資產。</p><h4>公鑰 Public Key</h4><p>在介紹公鑰之前須要先說明一下甚麼是<strong>單向函數（One-way function）</strong>，單向函數指的是輸入一個 input 到函數 <em>f(x)</em>，會很容易地得到 output，但是只給定 output 卻很難反向計算出 input。舉個例子，我們假設 <em>p, q</em> 為質數，並且是非常大的數，對於 <em>n = p * q </em>，給定一個 <em>p</em> 和 <em>q</em> 可以很容易得到 <em>n</em>，但給定一個 <em>n </em>卻很難得出 <em>p</em> 和 <em>q</em>。</p><blockquote>注意：單向函數很難反向計算，但我們沒辦法證明它真的很難計算，我們只能說目前沒有人可以反向計算出來而已，不能保證明天還是沒有人計算出來，因此「單向函數真的存在嗎？」是一個目前為止都沒有辦法回答的問題。</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*upDx16KnvrMrGQBmzJ1SjA.png" /><figcaption><a href="https://computersciencewiki.org/index.php/One-way_function">https://computersciencewiki.org/index.php/One-way_function</a></figcaption></figure><p>在 Ethereum 中，私鑰是用來將訊息<strong>簽名</strong>的，而公鑰是用來<strong>驗證簽名</strong>的，所有人都可以獲取你的公鑰以驗證簽名。Ethereum 的<strong>公鑰</strong>是由<strong>私鑰</strong>經過<strong>橢圓曲線演算法 </strong><a href="https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm"><strong>ECDSA</strong></a><strong>(Elliptic Curve Digital Signature Algorithm)</strong> 算出來的，得出的結果長度為 512 bits，其演算法使用橢圓曲線（Elliptic curve）這個<strong>單向函數</strong>。因此透過私鑰轉換成公鑰非常容易，但是要透過公鑰轉換成私鑰是一件非常困難的事，這也恰恰符合前面所說的私鑰不能隨意洩露。</p><blockquote>ECDSA 背後牽涉到很多艱深的數學，因此本篇文章不會討論他的原理，未來會另外寫一篇有關 ECDSA 的文章加以探討。</blockquote><h4>地址 Address</h4><p>地址就像銀行帳號，是 Ethereum 中用來代表一個帳戶的方式，任何交易都是由一個地址發起的，而根據 Ethereum 黃皮書中對於地址的定義如下：</p><blockquote>For a given private key, the Ethereum address A is defined as the rightmost 160-bits of the Keccak hash of the corresponding ECDSA public key.</blockquote><p>Ethereum 的地址是由公鑰生成的，先將公鑰代入 Keccak hash function 中，這個函數是一個單向函數，其 output 長度為 256 bits，Ethereum 取最右邊的 160 bits 作為帳戶地址。</p><p>然而你可能會問為何需要地址呢？其實在 Bitcoin 的白皮書裡是沒有地址這個概念的，是後來 Ethereum 為了讓帳戶位址更容易記住才有地址這個概念的。（壓縮過後的公鑰為 256 bits vs. 地址 160 bits）</p><p><strong>地址有可能重複嗎？</strong></p><p>答案是有的，但是機率非常小，小到幾乎不可能，Ethereum 地址長度為 160 bits，代表有 2¹⁶⁰ 種可能，根據<a href="https://zh.wikipedia.org/zh-tw/%E7%94%9F%E6%97%A5%E5%95%8F%E9%A1%8C">生日問題</a>，當有 2⁸⁰ 個不同的地址被創造出來時，地址重複的機率會上升到 50%。然而要產生 2⁸⁰ 個不同的地址，需要地球上的每一個人每秒都能夠產生一個新的地址，持續產生八百萬年才有可能。</p><h4>Conclusion</h4><p>上面我們講述了私鑰、公鑰以及地址是如何產生的，以及個別的功用是甚麼，下圖簡單的總結了從私鑰變成地址的過程。雖然省略了中間的數學過程，但是希望大家看完本文能夠對於區塊鏈的奧妙更加了解。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*1RkWbm58snAEi325ltzbDA.png" /><figcaption><a href="https://medium.com/@codetractio/inside-an-ethereum-transaction-fa94ffca912f">https://medium.com/@codetractio/inside-an-ethereum-transaction-fa94ffca912f</a></figcaption></figure><h4>Reference</h4><ul><li><a href="https://medium.com/portis/part-one-understanding-private-keys-311389737fbe">Part One: Understanding Private Keys</a></li><li><a href="https://medium.com/portis/part-two-turning-random-numbers-into-an-ethereum-address-3928f56b225c">Part Two: Turning Random Numbers into an Ethereum Address</a></li><li><a href="http://gavwood.com/paper.pdf">Ethereum Yellow Paper</a></li><li><a href="https://www.cs.utexas.edu/users/moore/acl2/manuals/current/manual/index-seo.php/ECURVE____SECP256K1-DOMAIN-PARAMETERS#:~:text=Domain%20parameters%20of%20the%20secp256k1,the%20curve%2C%20as%20nullary%20functions.">Secp256k1-domain-parameters</a></li><li><a href="https://ethereum.stackexchange.com/questions/33171/ethereum-address-vs-public-key">Ethereum Address vs Public Key</a></li><li><a href="https://ethereum.stackexchange.com/questions/4299/account-uniqueness-guaranteed">Account uniqueness guaranteed?</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f83b8fe424e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/taipei-ethereum-meetup/%E5%85%AC%E9%91%B0-%E7%A7%81%E9%91%B0-%E5%9C%B0%E5%9D%80%E5%82%BB%E5%82%BB%E5%88%86%E4%B8%8D%E6%B8%85-f83b8fe424e">公鑰、私鑰、地址傻傻分不清！？</a> was originally published in <a href="https://medium.com/taipei-ethereum-meetup">Taipei Ethereum Meetup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Flex and Bison to parse the regular expression]]></title>
            <link>https://ken8989580.medium.com/using-flex-and-bison-to-parse-the-regular-expression-3eb3004539b8?source=rss-23c193ee744c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3eb3004539b8</guid>
            <category><![CDATA[parser]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[lexical-analysis]]></category>
            <dc:creator><![CDATA[kkken.eth]]></dc:creator>
            <pubDate>Sun, 25 Jul 2021 16:47:13 GMT</pubDate>
            <atom:updated>2022-01-10T23:26:45.536Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zWBEK11qSZKLDG9h" /><figcaption>Photo by <a href="https://unsplash.com/@sincerelymedia?utm_source=medium&amp;utm_medium=referral">Sincerely Media</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>What are Flex and Bison?</h4><p>Flex and Bison are tools for parsing the input string. They were originally tools for building compilers. But they are also useful in many other areas. Flex can transfer a string into the tokens. Bison will check these tokens if it is correct. In this article, We’ll look at an example of using Flex and Bison to parse the regular expression.</p><h4>Flex</h4><p>Flex is a scanner that can divide a string into tokens. Let’s just check out the code directly.</p><pre><strong>// file name is &quot;parser.l&quot;</strong></pre><pre>%{<br><strong>// part1: </strong><strong>declarations</strong><br>#include &quot;y.tab.h&quot;<br>%}</pre><pre>%%<br><strong>// part2: translation rules</strong><br>[a-z] {<br>         yylval.charVal = yytext[0]<br>         return LOWERCASE<br>      }<br>[A-Z] {<br>         yylval.charVal = yytext[0]<br>         return UPPERCASE<br>      }<br>[0-9] {<br>         yylval.intVal = atoi(yytext);<br>         return INTEGER;<br>      }<br>%% <br><strong>//</strong><strong> part3: auxiliary functions</strong></pre><p>As you can see, the file divides into three parts.</p><p><strong>1. Declarations</strong></p><p>You can declare some variable or function in this area. Flex will copy the code to the .c file.</p><p><strong>2. Translation rules</strong></p><p>The second part is the most important also the kernel of Flex. <strong>[a-z] </strong>is the regular expression that represents the letter a, b, c, …, z. letter ‘a’ matches this expression. If you don’t know what string matches this regular expression. You can go to this website to check.</p><p><a href="https://regex101.com/">regex101: build, test, and debug regex</a></p><p>Next, the code in the scope is C code. That means what Flex will do after the input string matches the regular expression you set. <strong>yytext</strong> is a *char data type that represents the string. <strong>charVal </strong>is defined in Bison file which we will talk about it later. <strong>LOWERCASE </strong>is a token. when input ‘a’ is scanned by Flex, It will transfer it into the token LOWERCASE and tell Bison.</p><p>So, if the input is ‘a’, what these codes do is to know what the input is. And tell Bison it is a LOWERCASE token. this token’s value is ‘a’.</p><p><strong>3. auxiliary functions</strong></p><p>The third part is like the first part. Usually, in this area, you will implement the code you define in the first part. Flex will also copy the code to the .c file.</p><h4>Bison</h4><p>Bison is a parser that can parse the token that comes from Flex. The file also divided into three parts.</p><pre><strong>// the filename is &quot;parser.y&quot;</strong></pre><pre>%token INTEGER LOWERCASE UPPERCASE LEFT_B_P RIGHT_B_P COMMA<br>%union {<br>         char charVal;<br>         int intVal;<br>       }</pre><pre>%{<br><strong>// part1: </strong><strong>declarations</strong><br>#include &quot;stdio.h&quot;<br>#include &quot;stdlib.h&quot;<br>%}</pre><pre>%%<br><strong>// part2: grammar rules</strong><br>program:<br>    program statement &#39;\n&#39;  {printf(&quot;success!&quot;);}<br>    |<br>    ;<br>statement:<br>    expr size<br>    ;<br>size:<br>    INTEGER                 {$$ = $1;}<br>    |LEFT_B_P size RIGHT_B_P<br>    |LEFT_B_P size COMMA size RIGHT_B_P<br>    |LEFT_B_P size COMMA RIGHT_B_P<br>    |&#39;+&#39;<br>    |&#39;*&#39;<br>    ;<br>%%</pre><pre><strong>//</strong><strong> part3: supporting C routines<br></strong>int main(void)<strong><br></strong>{  <br>    yyparse();<br>    return 0;<br>}</pre><p>At the top of the file is some declarations of the tokens. Commonly used declarations are: %token, %union %start %type %left %right %nonassoc, etc.</p><p><strong>1. Declarations</strong></p><p>You can write some definitions here. Bison will copy the code to the .c file.</p><p><strong>2. Grammar rules</strong></p><p>This part is composed of rules and actions (including C code).<strong> Bison’s basic rule is BNF grammar. But it makes a little simplification to input easily.</strong></p><pre>size:<br>    INTEGER     {$$ = $1;}</pre><p>Let’s just look at this part. the ‘size’ token can be an ‘INTEGER’ token. When the input matches the grammar, it will execute the code in {}. The code in {} is C code. ‘$$=$1’ means ‘size=INTEGER’. For example, if the input is ‘3’, the ‘INTEGER’ token will be 3, and you can get this number from ‘$1’ variable and assign the number to the ‘size’ token by using &#39;$$=$1&#39;. (Remember to put the semicolon at the end of the code because this is the C code.)</p><p><strong>3. auxiliary functions</strong></p><p>This part is the same as the third part in Flex. Bison will copy the code into the .c file.</p><h4>Makefile</h4><p>At this point, the build process is complex enough to be worth putting into a Makefile.</p><pre>CC = gcc<br>OUT = parser.out <br>all : <br>    flex parser.l <br>    bison -vdty parser.y <br>    $(CC) -o $(OUT) lex.yy.c y.tab.c <br>clean : <br>    rm -rf *.tab.c *.tab.h *.output lex.yy.c $(OUT)</pre><p>First it runs flex to create <strong>lex.yy.c</strong>, then it runs bison with the -d(for “definitions” file) flag, which creates <strong>parser.tab.c</strong> and <strong>parser.tab.h</strong>. Then it compiles them together, along with the flex library. If you are developing some complicated program, you can add the -d(debug) flag when you run the Flex. The code will be like this:</p><pre>flex -d parser.l</pre><h4><strong>Conclusion</strong></h4><p>This is my note for learning Flex and Bison. Of course, there are more powerful things in Flex and Bison. But this is just for a beginner who doesn’t know where to start. If you want to see the whole project, below is my code on GitHub. You can download it and run it by yourself. It will make you feel how powerful Flex and Bison are. Hope you guys are doing well. Thanks for your reading.</p><p><a href="https://github.com/Jin-K-Yang/Regular-expression-generator">GitHub - Jin-K-Yang/Regular-expression-generator: Use regular expression to generate random number or alphabet through flex and bison.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3eb3004539b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>