Skip to content

Commit

Permalink
update some test;fix issue1;fix pr #7 (#8)
Browse files Browse the repository at this point in the history
* update some test;fix issue1;fix pr #7

* update tsconfig.json for build amd file
  • Loading branch information
MickWang authored Apr 4, 2018
1 parent 553f3e4 commit 098d4f4
Show file tree
Hide file tree
Showing 30 changed files with 1,179 additions and 143 deletions.
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
"main": "./lib/index.js",
"types": "./lib/types/index.d.ts",
"scripts": {
"test": "jest",
"build:dev": "webpack --display-error-details --config webpack.config.js --progress --color",
"build:prod": "webpack --env.prod --config webpack.config.js --progress --color"
"test": "./node_modules/.bin/jest",
"build:dev": "./node_modules/.bin/webpack --display-error-details --config webpack.config.js --progress --color",
"build:prod": "./node_modules/.bin/webpack --env.prod --config webpack.config.js --progress --color"
},
"jest": {
"moduleFileExtensions": [
Expand Down
60 changes: 44 additions & 16 deletions src/SDK/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,33 @@ import axios from 'axios'
import {BigNumber} from 'bignumber.js'
import {DDO} from '../transaction/ddo';
export class SDK {
static SERVER_NODE : string
static REST_PORT : string
static SOCKET_PORT : string

static setServerNode(node : string) {
if(node) {
SDK.SERVER_NODE = node
return;
}
throw new Error('Can not set ' + node + 'as server node')
}

static setRestPort(port: string) {
if (port) {
SDK.REST_PORT = port
return;
}
throw new Error('Can not set ' + port + ' as restful port')
}

static setSocketPort(port: string) {
if (port) {
SDK.SOCKET_PORT = port
return;
}
throw new Error('Can not set ' + port + 'as socket port')
}

static getDecryptError(err:any) {
return {
Expand Down Expand Up @@ -80,7 +107,8 @@ export class SDK {
socket.close()
}
}
var txSender = new TxSender(ONT_NETWORK.TEST)
let socket = `ws://${SDK.SERVER_NODE}:${SDK.SOCKET_PORT}`
var txSender = new TxSender(socket)
txSender.sendTxWithSocket(param, socketCallback)
// callback && sendBackResult2Native(JSON.stringify(obj), callback)
return obj
Expand All @@ -90,10 +118,8 @@ export class SDK {
password : string, callback ?: string) {
let identity = new Identity()
let wallet = Wallet.parseJson(walletDataStr)
let privateKey = ''
try {
//TODO check ontid
privateKey = scrypt.decrypt(encryptedPrivateKey, password)
identity = Identity.importIdentity(label, encryptedPrivateKey, password)
} catch (err) {
let obj = this.getDecryptError(err)
Expand All @@ -109,9 +135,10 @@ export class SDK {
desc : ''
}
//check ontid on chain
let tx = buildGetDDOTx(identity.ontid, privateKey)
let tx = buildGetDDOTx(identity.ontid)
let param = buildRestfulParam(tx)
let url = sendRawTxRestfulUrl(TEST_ONT_URL.REST_URL, true)
let restUrl = `http://${SDK.SERVER_NODE}:${SDK.REST_PORT}/`
let url = sendRawTxRestfulUrl(restUrl, true)
axios.post(url, param).then((res:any) => {
if (res.data.Result && res.data.Result.length > 0 && res.data.Result[0] !== '0000000000000000') {

Expand All @@ -130,9 +157,7 @@ export class SDK {
static importIdentity(label : string, encryptedPrivateKey : string, password : string, callback ?: string) {
let identity = new Identity()
let error = {}
let privateKey
try {
privateKey = scrypt.decrypt(encryptedPrivateKey, password)
identity = Identity.importIdentity(label, encryptedPrivateKey, password)
let wallet = new Wallet()
wallet.create(identity.label)
Expand All @@ -145,10 +170,11 @@ export class SDK {
desc: ''
}
//check ontid on chain
let tx = buildGetDDOTx(identity.ontid, privateKey)
let tx = buildGetDDOTx(identity.ontid)
let param = buildRestfulParam(tx)
let url = sendRawTxRestfulUrl(TEST_ONT_URL.REST_URL, true)
axios.post(url, param).then((res: any) => {
let restUrl = `http://${SDK.SERVER_NODE}:${SDK.REST_PORT}/`
let url = sendRawTxRestfulUrl(restUrl, true)
return axios.post(url, param).then((res: any) => {
if (res.data.Result && res.data.Result.length > 0 && res.data.Result[0] !== '0000000000000000') {

} else {
Expand All @@ -163,7 +189,7 @@ export class SDK {
} catch(err) {
error = this.getDecryptError(err)
callback && sendBackResult2Native(JSON.stringify(error), callback)
return error
return Promise.reject(error)
}
}

Expand All @@ -180,8 +206,9 @@ export class SDK {
//register ontid
let tx = buildRegisterOntidTx(identity.ontid, privateKey)
let param = buildRestfulParam(tx)
const url = TEST_ONT_URL.sendRawTxByRestful
axios.post(url, param).then((res: any) => {
let restUrl = `http://${SDK.SERVER_NODE}:${SDK.REST_PORT}${REST_API.sendRawTx}`

axios.post(restUrl, param).then((res: any) => {
if(res.data.Error === 0) {
callback && sendBackResult2Native(JSON.stringify(obj), callback)
} else {
Expand Down Expand Up @@ -322,7 +349,8 @@ export class SDK {
// let txId = core.getHash(tx.serialize())
let param = buildTxParam(tx)
//通过socket能获得推送的结果
var txSender = new TxSender(ONT_NETWORK.TEST)
let socket = `ws://${SDK.SERVER_NODE}:${SDK.SOCKET_PORT}`
var txSender = new TxSender(socket)
const socketCallback = function(res : any, socket : any) {
console.log('res: '+ JSON.stringify(res))
if(res.Action === 'InvokeTransaction' && res.Error === 0) {
Expand Down Expand Up @@ -365,7 +393,7 @@ export class SDK {
if(address.length === 40) {
address = core.u160ToAddress(address)
}
let request = `http://${TEST_NODE}:${HTTP_REST_PORT}${REST_API.getBalance}/${address}`
let request = `http://${SDK.SERVER_NODE}:${SDK.REST_PORT}${REST_API.getBalance}/${address}`
axios.get(request).then((res : any) => {
if(res.data.Error === 0) {
let result = res.data.Result
Expand Down Expand Up @@ -423,7 +451,7 @@ export class SDK {

let tx = makeTransferTransaction('ONT',from, to, value, privateKey)
var param = buildRestfulParam(tx)
let request = `http://${TEST_NODE}:${HTTP_REST_PORT}${REST_API.sendRawTx}`
let request = `http://${SDK.SERVER_NODE}:${SDK.REST_PORT}${REST_API.sendRawTx}`
axios.post(request, param).then( (res:any) => {
console.log('transfer response: ' + JSON.stringify(res.data))
if(res.data.Error === 0) {
Expand Down
2 changes: 1 addition & 1 deletion src/claim.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export class Claim {
this.Id = CryptoJS.SHA256(CryptoJS.enc.Hex.parse(JSON.stringify(body))).toString()
}

sign( privateKey: string ) {
sign( privateKey: string ) : Signature {
let claimBody = {
Context: this.Context,
Id: this.Id,
Expand Down
41 changes: 41 additions & 0 deletions src/common/fixed64.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
* Copyright (C) 2018 The ontology Authors
* This file is part of The ontology library.
*
* The ontology is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ontology 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with The ontology. If not, see <http://www.gnu.org/licenses/>.
*/


import {str2hexstr, hexstr2str ,StringReader} from '../utils'
const Fixed64Len = 8
export default class Fixed64 {
//8 bytes
value : string
constructor() {
this.value = '0000000000000000'
}

serialize() {
// return str2hexstr(this.value)
return this.value
}

static deserialize(sr:StringReader) {
let f = new Fixed64()
const v = sr.read(8)
// f.value = hexstr2str(v)
f.value = v
return f
}
}
4 changes: 2 additions & 2 deletions src/consts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export class Algorithm {
export const DEFAULT_ALGORITHM = {
algorithm : "ECDSA",
parameters : {
"curve": "secp256r1"
"curve": "secp256r1" // also called p256
}
}

Expand Down Expand Up @@ -77,7 +77,7 @@ export const TEST_ONT_URL = {

RPC_URL: `http://${TEST_NODE}:${HTTP_JSON_PORT}/`,

REST_URL: `http://${TEST_NODE}:${HTTP_REST_PORT}/`,
REST_URL: `http://${TEST_NODE}:${HTTP_REST_PORT}/`,

sendRawTxByRestful : `http://${TEST_NODE}:${HTTP_REST_PORT}${REST_API.sendRawTx}`
}
Expand Down
42 changes: 36 additions & 6 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,13 @@ import * as base58 from 'bs58'
import * as ecurve from 'ecurve'
import * as bigInteger from 'bigi'
import { ab2hexstring, hexstring2ab, StringReader, hexstr2str, num2hexstring } from './utils'
import { ADDR_VERSION } from './consts'
import { ADDR_VERSION, TEST_ONT_URL } from './consts'
import * as scrypt from './scrypt'
import {ERROR_CODE} from './error'
import { VmType } from './transaction/vmcode';
import { buildGetDDOTx, buildRestfulParam, sendRawTxRestfulUrl} from './transaction/transactionBuilder'
import axios from 'axios'
import { DDO } from './transaction/ddo'

var ec = require('elliptic').ec
var wif = require('wif')
Expand Down Expand Up @@ -147,12 +150,20 @@ export function signatureData(data: string, privateKey: string): string {
return signatureValue.toString('hex');
}

export function verifySignature(data : string, signature : string, publicKey : string) {

/*
@data original value of signature
@signature
@publicKey the public key of the signer. is array-like or buffer
*/
export function verifySignature(data: string, signature: string, publicKey: any) {
let msg = cryptoJS.enc.Hex.parse(data)
let msgHash = cryptoJS.SHA256(msg)

let elliptic = new ec('p256')
const result = elliptic.verify(data.toString(), signature, publicKey, null)
let r = signature.substr(0, 64)
let s = signature.substr(64, 64)
const result = elliptic.verify(msgHash.toString(), { r, s }, publicKey, null)
return result
}

Expand Down Expand Up @@ -212,11 +223,30 @@ export function checkPrivateKey(encryptedPrivateKey : string, password : string)
return true
}


/*
@claim claim json object
*/
export function verifyOntidClaim(claim : any) {
if(!claim.Metadata || !claim.Metadata.Issuer) {
throw new Error('Invalid claim.')
}
let issuer = claim.Metadata.Issuer
//TODO
let issuerDid = claim.Metadata.Issuer
let tx = buildGetDDOTx(issuerDid)
let param = buildRestfulParam(tx)
let url = sendRawTxRestfulUrl(TEST_ONT_URL.REST_URL, true)
return axios.post(url, param).then( (res:any) => {
if (res.data.Result && res.data.Result.length > 0) {
console.log('ddo hexstr: '+ res.data.Result[0])
const ddo = DDO.deserialize(res.data.Result[0])
console.log('ddo: ' + JSON.stringify(ddo))
if(ddo.publicKeys.length > 0) {
const pk = ddo.publicKeys[0].pk
const signature = claim.Signature.Value
claim.delete('Signature')
return verifySignature(JSON.stringify(claim), signature, hexstring2ab(pk))
} else {
return false
}
}
})
}
23 changes: 23 additions & 0 deletions src/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,26 @@ export enum SignatureSchema {

SHA512withEDDSA
}

export enum CurveLabel {
P224 = 1,
P256 = 2,
P384 = 3,
P521 = 4,

SM2P256V1 = 20,

ED25519 = 25
}

export enum KeyType {
PK_ECDSA = 0x12,
PK_SM2 = 0x13,
PK_EDDSA = 0x14,
}

export class PublicKey {
algorithm: number
curve: number
pk: string
}
3 changes: 1 addition & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ import * as core from './core'
import * as utils from './utils'
import * as CONST from './consts'
import { SDK } from './SDK/index'
import { CompleterResult } from 'readline';

class ONT {
Account : any
Expand Down Expand Up @@ -81,7 +80,7 @@ class ONT {
this.CONST.HTTP_REST_PORT = port
}

setWsPortyarn(port: string) {
setSocketPort(port: string) {
this.CONST.HTTP_WS_PORT = port
}
}
Expand Down
Loading

0 comments on commit 098d4f4

Please sign in to comment.