2018年 の投稿一覧

Metamaskからエクスポートした秘密鍵をweb3jsとethereumjsでインポートしてみる

EthreumJS


var pk = "0f0ed71771c3cb767ce1eca984f....";// Metamaskからエクスポートした秘密鍵文字列
var pu = ethereumjs.Util.privateToPublic("0x" + pk );

console.log( pu.toString("hex") ); // アドレスがMetamaskと一致

// Metamaskからエクスポートしたまま、Prefixがないとダメ
var pu = ethereumjs.Util.privateToPublic("0x" + pk );
Uncaught RangeError: private key length is invalid
    at Object.exports.isBufferLength (assert.js:31)
    at Object.publicKeyCreate (index.js:61)
    at Object.exports.privateToPublic (index.js:356)
    at :1:25

Web3は秘密鍵のチェックがあまい?


web3  = new Web3();

var pk = "0f0ed71771c3cb767ce1eca984f....";// Metamaskからエクスポートした秘密鍵文字列

var account = web3.eth.accounts.privateKeyToAccount( pk );

console.log( accoun );
{address: "0x6C0(Metamaskと違う)", privateKey: "0f0ed71771c3cb767ce1eca984f....", signTransaction: ƒ, sign: ƒ, encrypt: ƒ}

// Metamaskからエクスポートしたまま、Prefixがないとダメ
var account = web3.eth.accounts.privateKeyToAccount( "0x" + pk );

console.log( accoun );
{address: "0xa43d0(Metamaskと一致)", privateKey: "0x0f0ed71771c3cb767ce1eca984f....", signTransaction: ƒ, sign: ƒ, encrypt: ƒ}

ファイルによって「 Invalid JSON RPC response」なんて言われるから
通信してるかと思ったけど、よく調べたらmetamaskが提供してくれるweb3.jsと
自分がローカルで使ってるweb3.jsが結構違ったのでメモ

https://github.com/MetaMask/metamask-extension/blob/develop/package.json
Metamaskの提供してくれるweb3ではaccounts系は提供されていません。


var account = web3.eth.accounts.privateKeyToAccount( "0x" + pk );
inpage.js:1 Uncaught Error: Invalid JSON RPC response: undefined
    at Object.InvalidResponse (inpage.js:1)
    at s.send (inpage.js:1)
    at n.accounts (inpage.js:1)
    at :1:15

web3-1.0系だとprivateKeyToAccountがあります。

https://raw.githubusercontent.com/ethereum/web3.js/v1.0.0-beta.35/dist/web3.js


Accounts.prototype.create = function create(entropy) {
    return this._addAccountFunctions(Account.create(entropy || utils.randomHex(32)));
};
Accounts.prototype.privateKeyToAccount = function privateKeyToAccount(privateKey) {
    return this._addAccountFunctions(Account.fromPrivate(privateKey));
};
Accounts.prototype.signTransaction = function signTransaction(tx, privateKey, callback) {

Windows8タブレット( 64bitなのにUEFIが32bit )にUbuntu18のインストール

macOSXでubuntuとdebianのisoから必要なファイルをUSBにコピーするのですが
iosはMacでマウントできないといわれたので、hdiutilをつかってマウントする。


$ hdiutil attach -nobrowse -nomount debian-9.5.0-amd64-i386-netinst.iso
/dev/disk3              Apple_partition_scheme
/dev/disk3s1            Apple_partition_map
/dev/disk3s2            Apple_HFS
$ mount -t cd9660 /dev/disk3 debian

windowsタブレットはUSBポートが少ないので
USBハブにUSBメモリ、マウス、キーボードをつけて
BIOSメニューからまずは、secureBootの無効化をして起動順を設定しますが、それだと起動しなかったので、Save & ExitにあるBoot OverrideからUSBを指定して起動

USBデバイスがBlk数字としては認識してるけど
fs数字になっていない。。
UEFIのシェルからUSBのBlkをマウントしても中身がみえない。。


mount blk5 usb5
usb5:
ls

Pcirootからのところをよく見ると
USBがGPTじゃなくてMBRになっていました。
USBメモリをフォーマットするときに選択ミスしていたみたい。


map fs*
map blk*

Ethereum – スマートコントラクト作成 – プライベート・ネットワークの作成

https://book.ethereum-jp.net/first_use/connect_to_private_net.html

Ubuntuが良さそうですが、手元にCentos6しかなかったのでとりあえすやってみます。

Ethereumでは以下の3つの形態のP2Pネットワークを構築しブロックチェーンを運用していくことが可能です。

パブリック・ネットワーク:不特定多数のノードのノードが参加し、かつその参加に制限が全くないネットワークです。参加ノードはそのネットワーク上で共有管理されたブロックチェーンに対して自由に、読み取り、トランザクションの発行、マイニングが可能です。仮想通貨としてのEthereumや、多くのパブリックなdAppはこのパブリックネットワーク上で運用されています。
コンソーシアム・ネットワーク:あらかじめ参加を許されたノードのみが参加することが可能なネットワークです。参加を許されるノードは一つの組織のみに管理されたものとは限らず、複数の利害関係が一致しない組織がそれぞれのノードを管理することが通常です。例えば国際送金の管理を行うブロックチェーンを構築したい場合、予め参加を許された複数の金融企業がそれぞれ管理するノードをこのP2Pのネットワークに参加することで、一つの企業にのみ管理されたシステムではない半非中央集権なシステムが構築可能になります。
プライベート・ネットワーク:一つの組織のみに管理されたノードのみが参加することが可能なネットワークです。ネットワークは自身の管理下に置くことが可能になり、中央集権的なP2Pシステムが可能になります。


mkdir eth_private_net

vi eth_private_netg/enesis.json


{
  "config": {
    "chainId": 15
  },
  "nonce": "0x0000000000000042",
  "timestamp": "0x0",
  "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "extraData": "",
  "gasLimit": "0x8000000",
  "difficulty": "0x4000",
  "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "coinbase": "0x3333333333333333333333333333333333333333",
  "alloc": {}
}


 geth --datadir ~/eth_private_net init ~/eth_private_net/genesis.json
INFO [02-15|04:00:34] Maximum peer count                       ETH=25 LES=0 total=25
INFO [02-15|04:00:34] Allocated cache and file handles         database=/home/dp/eth_private_net/geth/c
haindata cache=16 handles=16
INFO [02-15|04:00:34] Writing custom genesis block 
INFO [02-15|04:00:34] Persisted trie from memory database      nodes=0 size=0.00B time=6.642µs gcnodes=0 gcsize
=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [02-15|04:00:34] Successfully wrote genesis state         database=chaindata                              
         hash=7b2e8b…7e0432
INFO [02-15|04:00:34] Allocated cache and file handles         database=/home/dp/eth_private_net/geth/l
ightchaindata cache=16 handles=16
INFO [02-15|04:00:34] Writing custom genesis block 
INFO [02-15|04:00:34] Persisted trie from memory database      nodes=0 size=0.00B time=2.335µs gcnodes=0 gcsize
=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [02-15|04:00:34] Successfully wrote genesis state         database=lightchaindata                         
              hash=7b2e8b…7e0432


geth --networkid "15" --nodiscover --datadir ~/eth_private_net/  console 2>> ~/eth_privat
e_net/err.log
Welcome to the Geth JavaScript console!
instance: Geth/v1.8.1-unstable-dc7ca52b/linux-amd64/go1.9.2
 modules: admin:1.0 debug:1.0 eth:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0
>

Genesisブロックの確認


> eth.getBlock(0)
{
  difficulty: 16384,
  extraData: "0x",
  gasLimit: 134217728,
  gasUsed: 0,
  hash: "0x7b2e8be699df0d329cc74a99271ff7720e2875cd2c4dd0b419ec60d1fe7e0432",
  logsBloom: "0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000",
  miner: "0x3333333333333333333333333333333333333333",
  mixHash: "0x0000000000000000000000000000000000000000000000000000000000000000",
  nonce: "0x0000000000000042",
  number: 0,
  parentHash: "0x0000000000000000000000000000000000000000000000000000000000000000",
  receiptsRoot: "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
  sha3Uncles: "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
  size: 507,
  stateRoot: "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
  timestamp: 0,
  totalDifficulty: 16384,
  transactions: [],
  transactionsRoot: "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
  uncles: []
}
> 

Ethereum – スマートコントラクト開発 – 開発環境を構築する

Go Ehtereumのインストール


brew tap ethereum/ethereum
ずらずら
==> Tapping ethereum/ethereum
Cloning into '/usr/local/Homebrew/Library/Taps/ethereum/homebrew-ethereum'...
remote: Counting objects: 6, done.
remote: Compressing objects: 100% (6/6), done.
remote: Total 6 (delta 1), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (6/6), done.
Tapped 3 formulae (32 files, 33.7KB)


brew install ethereum


npm install -g ethereumjs-testrpc


mba:~ dp$ ll
.e
.eclipse/                     .electrum-ltc/                .esets/
.electron/                    .emulator_console_auth_token  .ethereum_dev/
mba:~ dp$  geth --datadir .ethereum_dev/privatenet init .ethereum_dev/privatenet/genesis.json 
INFO [02-15|11:53:46] Maximum peer count                       ETH=25 LES=0 total=25
INFO [02-15|11:53:46] Allocated cache and file handles         database=/Users/dp/.ethereum_dev/privatenet/geth/chaindata cache=16 handles=16
INFO [02-15|11:53:46] Writing custom genesis block 
INFO [02-15|11:53:46] Persisted trie from memory database      nodes=0 size=0.00B time=19.224µs gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [02-15|11:53:46] Successfully wrote genesis state         database=chaindata                                           hash=17fa94…cca181
INFO [02-15|11:53:46] Allocated cache and file handles         database=/Users/dp/.ethereum_dev/privatenet/geth/lightchaindata cache=16 handles=16
INFO [02-15|11:53:46] Writing custom genesis block 
INFO [02-15|11:53:46] Persisted trie from memory database      nodes=0 size=0.00B time=4.766µs  gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [02-15|11:53:46] Successfully wrote genesis state         database=lightchaindata                                           hash=17fa94…cca181

Respect/Validation のよくやる設定ミス

Respect/Validationライブラリで数値のチェックを行なっていると、コピペしすぎて0をうまく判定してくれない時がある。

Respect/Validationに「notEmpty」というメソッドがあって
空判定として呼び出していたけど、数値の0はnotEmpty()を通らないので下記のようになってしまう。


$type = 0;

var_dump( Validator::notEmpty()->intVal()->validate( $type ) );
=> False
var_dump( Validator::intVal()->validate( $type ) );
=> True

Cordova ( web3js, infura, ethereumjs-tx.js) でsendSignedTransaction



self.sendTransaction = function( account , toaddress , amountEth ) {
    var   deferred  = $q.defer();
    const amountWei = self.web3.utils.toWei( amountEth , 'ether');

    var tx = {
        from  : account.address,
        to    : toaddress,
        value : amountWei,
    };

    self.web3.eth.estimateGas( tx ).then( ( gasLimit ) => {
        // Gasを前もって仮計算するけど、その瞬間なのでちょっと多めにする。
        tx.gasLimit = self.web3.utils.toHex( gasLimit + 10000 );
        return self.web3.eth.getGasPrice();
    }).then( ( gasPrice ) => {
        // Gasを設定して、nonceを取得(Metamaskでこれが困ったことがあった..)
        tx.gasPrice = self.web3.utils.toHex( gasPrice );
        return self.web3.eth.getTransactionCount( account.address );
    }).then( ( count ) => {
        // 今回は1トランザクションだけど、複数送信の場合は注意
        tx.nonce = count;

        const transaction = new ethereumjs.Tx( tx );
        var privatekey  = account.privateKey;
        // keystoreから復元したら秘密鍵に0xが付いてたけど0xあるとsignで失敗する
        var prefix  = "0x";
        if( privatekey.indexOf( prefix ) === 0 ){
            privatekey = privatekey.slice( prefix.length ) ;
        }
        transaction.sign( ethereumjs.Buffer.Buffer.from( privatekey , 'hex' ) );
        const transactionHex = '0x'+transaction.serialize().toString( 'hex' )
        self.web3.eth.sendSignedTransaction( transactionHex ).once('transactionHash', (hash) => {
                console.log('transaction Hash', 'https://ropsten.etherscan.io/tx/' + hash);
              }).once('receipt', ( receipt ) => {
                console.log('receipt' , receipt );
              })
              .on('confirmation' , (confirmationNumber, receipt) => {
                console.log('confirmation', confirmationNumber, receipt);
              })
              .on('error', console.error );
        });

confirmationをonceにしたから、confirmationずっと流れると思ったけど24で終了した?
解除ってどうやるんだろう、それかonだけにするしかないかな。

OnsenUI2 ons-iconでmd-***してもmaterialデザインのアイコンが表示されない


//出る
<ons-icon icon="md-face"></ons-icon>
//出ない
<ons-icon icon="md-account_circle"></ons-icon>
//出る
<ons-icon icon="md-account-circle"></ons-icon>


勘違いしていました。
こっちだと思っていましたが違いました。
https://material.io/tools/icons/
OnsenUIのマテリアルアイコンはこっちでした。
http://zavoloklom.github.io/material-design-iconic-font/icons.html

と思ってましたが、別のPCでOnsenUIのリファレンス見てたら
やっぱりmaterial.ioへのリンクになってると思って見比べたら

https://ja.onsen.io/v2/api/angular1/ons-icon.html
のMaterial Iconsのリンクは
https://material.io/tools/icons/
だけど
https://onsen.io/v2/api/angular2/ons-icon.html#tutorial
のMaterial Iconsのリンクは
http://zavoloklom.github.io/material-design-iconic-font/icons.html
になってるな、なんだろう。

Cordova – Command failed with exit code 1 Error output: Could not merge source set folders:

Cordova buildがエラーになりました。


Error: /Users/dp/Dropbox/cordova/ethereumApp/platforms/android/gradlew: Command failed with exit code 1 Error output:
注意:一部の入力ファイルは非推奨のAPIを使用またはオーバーライドしています。
注意:詳細は、-Xlint:deprecationオプションを指定して再コンパイルしてください。
Could not merge source set folders:
[www/node_modules/semver/semver.browser.js] /Users/dp/Dropbox/cordova/ethereumApp/platforms/android/assets/www/node_modules/semver/semver.browser.js    [www/node_modules/semver/semver.browser.js] /Users/dp/Dropbox/cordova/ethereumApp/platforms/android/assets/www/node_modules/semver/semver.browser.js.gz: Error: Duplicate resources

semver?なんだこれ?


mac:dp dp$ npm ls --depth=2
net.dp.wallet@1.0.0 /Users/dp/Dropbox/cordova/ethereumApp
├─┬ cordova-android@6.2.3
│ ├─┬ cordova-common@2.0.2
│ │ ├── ansi@0.3.1
│ │ ├── bplist-parser@0.1.1
│ │ ├── cordova-registry-mapper@1.1.15
│ │ ├── elementtree@0.1.6 deduped
│ │ ├── glob@5.0.15
│ │ ├── minimatch@3.0.3
│ │ ├── osenv@0.1.4
│ │ ├── plist@1.2.0
│ │ ├── q@1.5.0 deduped
│ │ ├── semver@5.3.0
│ │ ├── shelljs@0.5.3 deduped
│ │ ├── underscore@1.8.3
│ │ └── unorm@1.4.1
│ ├─┬ elementtree@0.1.6
│ │ └── sax@0.3.5
│ ├─┬ nopt@3.0.6
│ │ └── abbrev@1.1.0
│ ├── properties-parser@0.2.3
│ ├── q@1.5.0
│ └── shelljs@0.5.3
└── cordova-plugin-whitelist@1.3.3

Cordovaのプロジェクト直下で依存を見てみると「cordova-android」の依存に「semver@5.3.0」がいました。

次にwwwに移動して依存をチェック


├─┬ gulp@3.9.1
│ ├── archy@1.0.0
│ ├─┬ chalk@1.1.3
│ │ ├── ansi-styles@2.2.1
つづく
│ ├── pretty-hrtime@1.0.3
│ ├── semver@4.3.6

いました、gulpの依存になっています。
gulp??devDependenciesなんだけどな。。。
bashのヒストリーを確認しましたが
npm installの際に、「–production」を忘れてdevDependenciesも入ってしまったようです。
node_modulesを一旦削除して、「npm install –production」でgulpがなくなったら
「cordova run android」も成功しました。

GulpでSass構文エラーで止まるのを防ぐ

https://github.com/dlmanning/gulp-sass/issues/44
を参考にonとerrorLogToConsoleを追加


gulp.task('sass', function(){
    gulp.src('./src/scss/*.scss')
    .pipe(sass({errLogToConsole: true}))
    .on('error', catchErr)
    .pipe(sass({style : 'expanded'}))
    .pipe(gulp.dest('./dist/css'));
});
function catchErr(e) {
    console.log(e);
    this.emit('end');
}

errLogToConsoleだけでもいいのかと思いましたがそれだと止まります。

Gulpとか設定面倒だよと思って http-server -c-1 と sass –watch scss:dist/css をターミナルで別々にやってた頃が恥ずかしい。

acquireLatestImageから取得するスクショ画像に黒い枠?

getPixelStrideとgetRowStrideを取得して、Bitmap.createBitmapしてたんだけど
自分の端末だと8px画像サイズが大きくなり、FullHDのはずだけど1088pxになって
余分の8pxは黒になってしまった。

他の端末だと、もっと黒枠が広くなることもあればない時もある。。
調べて見たらこれ?

Why does the output bitmap (currently I don’t do anything with it, because it’s still POC) have black margins in it? What’s wrong with the code in this matter?

You have black margins around your screenshot because you are not using realSize of the window you’re in. To solve this:

https://stackoverflow.com/questions/43705756/how-to-properly-take-a-screenshot-globally/43844977

https://github.com/AndroidDeveloperLB/ScreenshotSample

ImageReader.newInstanceに渡すサイズの設定が違ったみたい。
そして、copyPixelsFromBufferでgetRealSizeしたサイズのBitmapに流し込んでみたら
黒枠?がなくなってサイズは1080になった。


windowSize  = new Point();
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getRealSize(windowSize);
width   = windowSize.x;
height  = windowSize.y;
imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 10 );
virtualDisplay  = mediaProjection.createVirtualDisplay("Capturing Display", width, height, density, VIRTUAL_DISPLAY_FLAGS, imageReader.getSurface(), null, null);


int pixelStride = planes[ 0 ].getPixelStride(), rowStride = planes[ 0 ].getRowStride();
int rowPadding = rowStride - pixelStride * width;
bitmap = Bitmap.createBitmap( width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888 );
bitmap.copyPixelsFromBuffer( buffer );
croppedBitmap = Bitmap.createBitmap( bitmap, 0, 0, windowSize.x, windowSize.y );