@ocap/state 1.13.63 → 1.13.67

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,15 +2,16 @@
2
2
 
3
3
  const create = ({ txHash, txTime }) => ({
4
4
  genesisTime: txTime || '',
5
- genesisTx: txHash || null,
5
+ genesisTx: txHash || '',
6
6
  renaissanceTime: txTime || '',
7
- renaissanceTx: txHash || null,
7
+ renaissanceTx: txHash || '',
8
8
  });
9
9
 
10
10
  const update = (context, { txHash, txTime }) => ({
11
11
  ...context,
12
+ genesisTx: context.genesisTx || '',
12
13
  renaissanceTime: txTime || '',
13
- renaissanceTx: txHash || null,
14
+ renaissanceTx: txHash || '',
14
15
  });
15
16
 
16
17
  module.exports = { create, update };
package/lib/index.js CHANGED
@@ -10,8 +10,6 @@ const rollup = require('./states/rollup');
10
10
  const rollupBlock = require('./states/rollup-block');
11
11
  const evidence = require('./states/evidence');
12
12
 
13
- const Joi = require('./joi');
14
-
15
13
  const Blacklist = require('./states/blacklist');
16
14
 
17
15
  module.exports = {
@@ -56,5 +54,4 @@ module.exports = {
56
54
  ],
57
55
 
58
56
  Blacklist,
59
- Joi,
60
57
  };
@@ -1,35 +1,40 @@
1
1
  const pick = require('lodash/pick');
2
2
  const uniq = require('lodash/uniq');
3
3
  const flatten = require('lodash/flatten');
4
- const { toBase64, toUint8Array, BN } = require('@ocap/util');
4
+ const { isFromPublicKey } = require('@arcblock/did');
5
+ const { toBase58, BN } = require('@ocap/util');
5
6
 
7
+ const Joi = require('@ocap/validator');
6
8
  const { create: createStateContext, update: updateStateContext } = require('../contexts/state');
7
9
 
10
+ const schema = Joi.object({
11
+ address: Joi.DID().required(),
12
+ pk: Joi.string().allow(''),
13
+ issuer: Joi.DID().allow(''),
14
+ moniker: Joi.string().trim().min(2).max(40).allow(''),
15
+ nonce: Joi.number().min(0).default(0),
16
+ tokens: Joi.object().pattern(Joi.DID().role('ROLE_TOKEN'), Joi.BN().min(0)).default({}),
17
+ migratedTo: Joi.array().items(Joi.DID()).default([]),
18
+ migratedFrom: Joi.array().items(Joi.DID()).default([]),
19
+ context: Joi.schemas.context,
20
+ data: Joi.any().optional(),
21
+ }).options({ stripUnknown: true, noDefaults: false });
22
+
8
23
  const create = (attrs, context) => {
9
24
  const account = {
10
- balance: '0',
11
- gasBalance: '0',
12
25
  nonce: 0,
13
- numTxs: 0,
14
- numAssets: 0,
15
26
  migratedTo: [],
16
27
  migratedFrom: [],
17
- stake: null,
18
28
  tokens: {},
19
29
  context: createStateContext(context),
20
30
  ...pick(attrs, ['address', 'pk', 'issuer', 'moniker', 'data', 'nonce', 'migratedFrom', 'tokens']),
21
31
  };
22
32
 
23
- // ensure we have correct pk
24
- if (typeof account.pk !== 'string') {
25
- account.pk = toBase64(toUint8Array(account.pk));
33
+ if (!account.moniker) {
34
+ account.moniker = [account.address.slice(0, 6), account.address.slice(-5)].join('-');
26
35
  }
27
36
 
28
- if (!account.data) {
29
- account.data = null;
30
- }
31
-
32
- return account;
37
+ return validate(account);
33
38
  };
34
39
 
35
40
  const update = (state, attrs, context) => {
@@ -37,20 +42,47 @@ const update = (state, attrs, context) => {
37
42
  throw new Error('nonce must be greater in newer transactions');
38
43
  }
39
44
 
45
+ // ensure we are updating the correct pk
46
+ if (attrs.pk && isFromPublicKey(state.address, attrs.pk) === false) {
47
+ delete attrs.pk;
48
+ }
49
+
40
50
  const account = {
41
51
  ...state,
42
- ...pick(attrs, ['moniker', 'data', 'migratedTo', 'nonce', 'tokens']),
52
+ ...pick(attrs, ['moniker', 'data', 'migratedTo', 'nonce', 'tokens', 'pk']),
43
53
  migratedTo: uniq(flatten(attrs.migratedTo ? [attrs.migratedTo].concat(state.migratedTo) : state.migratedTo)),
44
54
  context: updateStateContext(state.context, context),
45
55
  };
46
56
 
47
- if (!account.data) {
48
- account.data = null;
57
+ return validate(account);
58
+ };
59
+
60
+ const updateOrCreate = (state, attrs, context) => {
61
+ if (state) {
62
+ return update(state, attrs, context);
63
+ }
64
+
65
+ return create(attrs, context);
66
+ };
67
+
68
+ const validate = (state) => {
69
+ // ensure we have correct pk
70
+ if (state.pk && typeof state.pk !== 'string') {
71
+ state.pk = toBase58(state.pk);
72
+ }
73
+
74
+ const { value, error } = schema.validate(state);
75
+ if (error) {
76
+ throw new Error(`Invalid account: ${error.details.map((x) => x.message).join(', ')}`);
77
+ }
78
+
79
+ if (!value.data) {
80
+ value.data = null;
49
81
  }
50
82
 
51
- return account;
83
+ return value;
52
84
  };
53
85
 
54
86
  const isMigrated = (state) => (state.migratedTo || []).length > 0;
55
87
 
56
- module.exports = { create, update, isMigrated };
88
+ module.exports = { create, update, updateOrCreate, validate, isMigrated };
@@ -7,7 +7,7 @@ const create = (attrs) => {
7
7
  const context = { txTime: new Date().toISOString() };
8
8
  const chain = {
9
9
  context: createStateContext(context),
10
- ...pick(attrs, ['address', 'chainId', 'version', 'transaction', 'moderator', 'accounts', 'token']),
10
+ ...pick(attrs, ['address', 'chainId', 'version', 'transaction', 'moderator', 'accounts', 'token', 'vaults']),
11
11
  };
12
12
 
13
13
  return chain;
@@ -25,7 +25,7 @@ const update = (state, updates) => {
25
25
  const context = { txTime: new Date().toISOString() };
26
26
  const chain = {
27
27
  ...state,
28
- ...pick(updates, ['version', 'transaction', 'accounts']),
28
+ ...pick(updates, ['version', 'transaction', 'accounts', 'vaults']),
29
29
  context: updateStateContext(state.context, context),
30
30
  };
31
31
 
@@ -1,11 +1,11 @@
1
1
  const pick = require('lodash/pick');
2
2
 
3
- const Joi = require('../joi');
3
+ const Joi = require('@ocap/validator');
4
4
  const { create: createStateContext } = require('../contexts/state');
5
5
 
6
6
  const schema = Joi.object({
7
7
  hash: Joi.string().trim().required(),
8
- context: Joi.contextSchema,
8
+ context: Joi.schemas.context,
9
9
  data: Joi.any().optional(),
10
10
  }).options({ stripUnknown: true, noDefaults: false });
11
11
 
@@ -1,22 +1,22 @@
1
1
  const pick = require('lodash/pick');
2
2
 
3
- const Joi = require('../joi');
3
+ const Joi = require('@ocap/validator');
4
4
  const { create: createStateContext, update: updateStateContext } = require('../contexts/state');
5
5
 
6
6
  const schema = Joi.object({
7
- hash: Joi.string().regex(Joi.hashRegexp).required(),
7
+ hash: Joi.string().regex(Joi.patterns.txHash).required(),
8
8
  height: Joi.number().integer().greater(0).required(),
9
- merkleRoot: Joi.string().regex(Joi.hashRegexp).required(),
9
+ merkleRoot: Joi.string().regex(Joi.patterns.txHash).required(),
10
10
  previousHash: Joi.string().when('height', {
11
11
  is: 1,
12
12
  then: Joi.string().optional().allow(''),
13
- otherwise: Joi.string().regex(Joi.hashRegexp).required(),
13
+ otherwise: Joi.string().regex(Joi.patterns.txHash).required(),
14
14
  }),
15
- txsHash: Joi.string().regex(Joi.hashRegexp).required(),
16
- txs: Joi.array().items(Joi.string().regex(Joi.hashRegexp).required()).min(1).unique().required(),
15
+ txsHash: Joi.string().regex(Joi.patterns.txHash).required(),
16
+ txs: Joi.array().items(Joi.string().regex(Joi.patterns.txHash).required()).min(1).unique().required(),
17
17
 
18
18
  proposer: Joi.DID().wallet('ethereum').required(),
19
- signatures: Joi.multiSigSchema.min(1).required(),
19
+ signatures: Joi.schemas.multiSig.min(1).required(),
20
20
 
21
21
  rollup: Joi.DID().role('ROLE_ROLLUP').required(),
22
22
 
@@ -26,7 +26,7 @@ const schema = Joi.object({
26
26
 
27
27
  minReward: Joi.BN().min(0).required(),
28
28
 
29
- context: Joi.contextSchema,
29
+ context: Joi.schemas.context,
30
30
  data: Joi.any().optional(),
31
31
  }).options({ stripUnknown: true, noDefaults: false });
32
32
 
@@ -1,6 +1,6 @@
1
1
  const pick = require('lodash/pick');
2
2
 
3
- const Joi = require('../joi');
3
+ const Joi = require('@ocap/validator');
4
4
  const { create: createStateContext, update: updateStateContext } = require('../contexts/state');
5
5
 
6
6
  const validator = Joi.object({
@@ -54,14 +54,14 @@ const schema = Joi.object({
54
54
  maxWithdrawFee: Joi.BN().min(Joi.ref('minWithdrawFee')).required(),
55
55
 
56
56
  blockHeight: Joi.number().integer().min(0).required(),
57
- blockHash: Joi.string().regex(Joi.hashRegexp).optional().allow(''),
57
+ blockHash: Joi.string().regex(Joi.patterns.txHash).optional().allow(''),
58
58
  issuer: Joi.DID().optional(),
59
59
 
60
60
  leaveWaitingPeriod: Joi.number().integer().min(Joi.ref('minBlockInterval')).default(0),
61
61
  publishWaitingPeriod: Joi.number().integer().min(Joi.ref('minBlockInterval')).default(0),
62
62
  publishSlashRate: Joi.number().integer().min(1).max(10000).required(),
63
63
 
64
- context: Joi.contextSchema,
64
+ context: Joi.schemas.context,
65
65
  data: Joi.any().optional(),
66
66
  }).options({ stripUnknown: true, noDefaults: false });
67
67
 
@@ -1,20 +1,20 @@
1
1
  const pick = require('lodash/pick');
2
2
 
3
- const Joi = require('../joi');
3
+ const Joi = require('@ocap/validator');
4
4
  const { create: createStateContext, update: updateStateContext } = require('../contexts/state');
5
5
 
6
6
  const schema = Joi.object({
7
7
  address: Joi.DID().role('ROLE_STAKE').trim().required(),
8
8
  sender: Joi.DID().trim().required(),
9
9
  receiver: Joi.DID().trim().required(),
10
- tokens: Joi.object().default({}),
10
+ tokens: Joi.object({}).pattern(Joi.DID().role('ROLE_TOKEN'), Joi.BN().min(0)).default({}),
11
11
  assets: Joi.array().items(Joi.DID().role('ROLE_ASSET')).default([]),
12
12
  revocable: Joi.boolean().default(true),
13
13
  message: Joi.string().trim().min(1).max(256).required(),
14
14
  revokeWaitingPeriod: Joi.number().integer().min(0).default(0),
15
- revokedTokens: Joi.object().default({}),
15
+ revokedTokens: Joi.object({}).pattern(Joi.DID().role('ROLE_TOKEN'), Joi.BN().min(0)).default({}),
16
16
  revokedAssets: Joi.array().items(Joi.DID().role('ROLE_ASSET')).default([]),
17
- context: Joi.contextSchema,
17
+ context: Joi.schemas.context,
18
18
  data: Joi.any().optional(),
19
19
  }).options({ stripUnknown: true, noDefaults: false });
20
20
 
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.13.63",
6
+ "version": "1.13.67",
7
7
  "description": "",
8
8
  "main": "lib/index.js",
9
9
  "files": [
@@ -16,21 +16,20 @@
16
16
  "coverage": "npm run test -- --coverage"
17
17
  },
18
18
  "dependencies": {
19
- "@arcblock/did": "1.13.63",
20
- "@ocap/contract": "1.13.63",
21
- "@ocap/message": "1.13.63",
22
- "@ocap/util": "1.13.63",
19
+ "@arcblock/did": "1.13.67",
20
+ "@ocap/contract": "1.13.67",
21
+ "@ocap/mcrypto": "1.13.67",
22
+ "@ocap/message": "1.13.67",
23
+ "@ocap/util": "1.13.67",
24
+ "@ocap/validator": "1.13.67",
23
25
  "bloom-filters": "^1.3.1",
24
- "debug": "^4.3.2",
25
- "joi": "^17.4.2",
26
26
  "lodash": "^4.17.21"
27
27
  },
28
28
  "devDependencies": {
29
- "@ocap/mcrypto": "1.13.63",
30
29
  "jest": "^27.3.1"
31
30
  },
32
31
  "keywords": [],
33
32
  "author": "wangshijun <wangshijun2010@gmail.com> (http://github.com/wangshijun)",
34
33
  "license": "MIT",
35
- "gitHead": "7e40f22f90f4f5ac08fde3d4d3b7194aa792c95d"
34
+ "gitHead": "866f6a0dbf4fc22425b8583d84610880472a3109"
36
35
  }
@@ -1,130 +0,0 @@
1
- const { BN } = require('@ocap/util');
2
-
3
- module.exports = (Joi) => ({
4
- type: 'BN',
5
- base: Joi.any(),
6
- messages: {
7
- 'bn.nan': '{{#label}} is not a big number',
8
- 'bn.max': '{{#label}} needs to be less than or equal to "{{#threshold}}"',
9
- 'bn.min': '{{#label}} needs to be greater than or equal to "{{#threshold}}"',
10
- 'bn.less': '{{#label}} needs to be less than "{{#threshold}}"',
11
- 'bn.greater': '{{#label}} needs to be greater than "{{#threshold}}"',
12
- 'bn.positive': '{{#label}} needs to be positive',
13
- 'bn.negative': '{{#label}} needs to be negative',
14
- },
15
-
16
- prepare(value, helpers) {
17
- try {
18
- return { value: new BN(value) };
19
- } catch (err) {
20
- return { errors: helpers.error('bn.nan') };
21
- }
22
- },
23
- coerce(value) {
24
- return { value: value.toString(10) };
25
- },
26
-
27
- validate(value) {
28
- return { value };
29
- },
30
-
31
- rules: {
32
- gt: {
33
- args: [
34
- {
35
- name: 'threshold',
36
- ref: true,
37
- assert: (v) => BN.isBN(v),
38
- message: 'must be a big number',
39
- normalize: (v) => new BN(v),
40
- },
41
- {
42
- name: 'equal',
43
- assert: (v) => typeof v === 'boolean',
44
- message: 'must be a boolean',
45
- },
46
- ],
47
- // The rule return structure is different from the root
48
- // eslint-disable-next-line consistent-return
49
- validate(value, helpers, args) {
50
- const v = new BN(value);
51
- if (args.equal && v.lt(args.threshold)) {
52
- return helpers.error('bn.min', args);
53
- }
54
- if (!args.equal && v.lte(args.threshold)) {
55
- return helpers.error('bn.greater', args);
56
- }
57
-
58
- // must return value when valid
59
- return value;
60
- },
61
- },
62
-
63
- lt: {
64
- args: [
65
- {
66
- name: 'threshold',
67
- ref: true,
68
- assert: (v) => BN.isBN(v),
69
- message: 'must be a big number',
70
- normalize: (v) => new BN(v),
71
- },
72
- {
73
- name: 'equal',
74
- assert: (v) => typeof v === 'boolean',
75
- message: 'must be a boolean',
76
- },
77
- ],
78
- // The rule return structure is different from the root
79
- // eslint-disable-next-line consistent-return
80
- validate(value, helpers, args) {
81
- const v = new BN(value);
82
- if (args.equal && v.gt(args.threshold)) {
83
- return helpers.error('bn.max', args);
84
- }
85
- if (!args.equal && v.gte(args.threshold)) {
86
- return helpers.error('bn.less', args);
87
- }
88
-
89
- // must return value when valid
90
- return value;
91
- },
92
- },
93
-
94
- min: {
95
- alias: 'gte',
96
- method(threshold) {
97
- return this.$_addRule({ name: 'gt', args: { threshold, equal: true } });
98
- },
99
- },
100
- max: {
101
- alias: 'lte',
102
- method(threshold) {
103
- return this.$_addRule({ name: 'lt', args: { threshold, equal: true } });
104
- },
105
- },
106
- greater: {
107
- alias: 'gt',
108
- method(threshold) {
109
- return this.$_addRule({ name: 'gt', args: { threshold, equal: false } });
110
- },
111
- },
112
- less: {
113
- alias: 'lt',
114
- method(threshold) {
115
- return this.$_addRule({ name: 'lt', args: { threshold, equal: false } });
116
- },
117
- },
118
-
119
- positive: {
120
- method() {
121
- return this.$_addRule({ name: 'gt', args: { threshold: 0, equal: false } });
122
- },
123
- },
124
- negative: {
125
- method() {
126
- return this.$_addRule({ name: 'lt', args: { threshold: 0, equal: false } });
127
- },
128
- },
129
- },
130
- });
@@ -1,100 +0,0 @@
1
- const isEqual = require('lodash/isEqual');
2
- const { types } = require('@ocap/mcrypto');
3
- const { isValid, toTypeInfo, DID_TYPE_ARCBLOCK, DID_TYPE_ETHEREUM } = require('@arcblock/did');
4
-
5
- const ruleTypes = {
6
- wallet: ['arcblock', 'ethereum', 'default', 'eth'],
7
- pk: Object.keys(types.KeyType),
8
- hash: Object.keys(types.HashType),
9
- role: Object.keys(types.RoleType),
10
- };
11
-
12
- module.exports = (Joi) => ({
13
- type: 'DID',
14
- base: Joi.string().trim(),
15
- messages: {
16
- 'did.empty': 'Expect {{#label}} to be non-empty string, got "{{#value}}"',
17
- 'did.invalid': 'Expect {{#label}} to be valid did, got "{{#value}}"',
18
- 'did.wallet': 'Expect wallet type of {{#label}} to be "{{#expected}}" wallet, got "{{#actual}}"',
19
- 'did.pk': 'Expect pk type of {{#label}} to be "{{#expected}}", got "{{#actual}}"',
20
- 'did.hash': 'Expect hash type of {{#label}} to be "{{#expected}}", got "{{#actual}}"',
21
- 'did.role': 'Expect role type of {{#label}} to be "{{#expected}}", got "{{#actual}}"',
22
- },
23
-
24
- validate(value, helpers) {
25
- if (!value || typeof value !== 'string') {
26
- return { errors: helpers.error('did.empty', { value }) };
27
- }
28
-
29
- if (isValid(value) === false) {
30
- return { errors: helpers.error('did.invalid', { value }) };
31
- }
32
-
33
- return { value };
34
- },
35
-
36
- rules: {
37
- type: {
38
- args: [
39
- {
40
- name: 'key',
41
- ref: true,
42
- assert: (v) => Object.keys(ruleTypes).includes(v),
43
- message: `must be one of ${Object.keys(ruleTypes).join(', ')}`,
44
- },
45
- {
46
- name: 'expected',
47
- assert: (v) => Object.keys(ruleTypes).some((x) => ruleTypes[x].includes(v)),
48
- message: 'must be valid type',
49
- },
50
- ],
51
- // The rule return structure is different from the root
52
- // eslint-disable-next-line consistent-return
53
- validate(value, helpers, args) {
54
- const type = toTypeInfo(value);
55
- const typeStr = toTypeInfo(value, true);
56
-
57
- if (args.key === 'wallet') {
58
- if (['ethereum', 'eth'].includes(args.expected) && isEqual(type, DID_TYPE_ETHEREUM) === false) {
59
- return helpers.error('did.wallet', { ...args, actual: JSON.stringify(typeStr) });
60
- }
61
- if (['arcblock', 'default'].includes(args.expected) && isEqual(type, DID_TYPE_ARCBLOCK) === false) {
62
- return helpers.error('did.wallet', { ...args, actual: JSON.stringify(typeStr) });
63
- }
64
- }
65
- if (args.key === 'pk' && typeStr.pk !== args.expected) {
66
- return helpers.error('did.pk', { ...args, actual: typeStr.pk });
67
- }
68
- if (args.key === 'hash' && typeStr.hash !== args.expected) {
69
- return helpers.error('did.hash', { ...args, actual: typeStr.hash });
70
- }
71
- if (args.key === 'role' && typeStr.role !== args.expected) {
72
- return helpers.error('did.role', { ...args, actual: typeStr.role });
73
- }
74
-
75
- return value;
76
- },
77
- },
78
-
79
- wallet: {
80
- method(type) {
81
- return this.$_addRule({ name: 'type', args: { key: 'wallet', expected: type } });
82
- },
83
- },
84
- pk: {
85
- method(type) {
86
- return this.$_addRule({ name: 'type', args: { key: 'pk', expected: type } });
87
- },
88
- },
89
- hash: {
90
- method(type) {
91
- return this.$_addRule({ name: 'type', args: { key: 'hash', expected: type } });
92
- },
93
- },
94
- role: {
95
- method(type) {
96
- return this.$_addRule({ name: 'type', args: { key: 'role', expected: type } });
97
- },
98
- },
99
- },
100
- });
package/lib/joi/index.js DELETED
@@ -1,53 +0,0 @@
1
- const JOI = require('joi');
2
-
3
- const bnExtension = require('./extension/bn');
4
- const didExtension = require('./extension/did');
5
-
6
- const Joi = JOI.extend(didExtension).extend(bnExtension);
7
-
8
- const hashRegexp = /^(0x)?([A-Fa-f0-9]{64})$/;
9
-
10
- const contextSchema = Joi.object({
11
- genesisTime: Joi.date().iso().required().raw(),
12
- genesisTx: Joi.string().regex(hashRegexp).required(),
13
- renaissanceTime: Joi.date().iso().required().raw(),
14
- renaissanceTx: Joi.string().regex(hashRegexp).required(),
15
- });
16
-
17
- const tokenInputSchema = Joi.object({
18
- address: Joi.DID().role('ROLE_TOKEN').required(),
19
- value: Joi.BN().positive().required(),
20
- });
21
-
22
- const indexedTokenInputSchema = Joi.object({
23
- address: Joi.DID().role('ROLE_TOKEN').required(),
24
- value: Joi.BN().positive().required(),
25
- decimal: Joi.number().integer().greater(0).required(),
26
- symbol: Joi.string().required(),
27
- unit: Joi.string().required(),
28
- });
29
-
30
- const multiSigSchema = Joi.array().items({
31
- signer: Joi.DID().required(),
32
- pk: Joi.any().required(),
33
- signature: Joi.any().required(),
34
- delegator: Joi.DID().valid('').optional(),
35
- data: Joi.any().optional(),
36
- });
37
-
38
- const foreignTokenSchema = Joi.object({
39
- type: Joi.string().min(1).max(32).required(),
40
- contractAddress: Joi.DID().wallet('ethereum').required(),
41
- chainType: Joi.string().min(1).max(32).required(),
42
- chainName: Joi.string().min(1).max(32).required(),
43
- chainId: Joi.number().positive().required(),
44
- });
45
-
46
- module.exports = Joi;
47
-
48
- module.exports.contextSchema = contextSchema;
49
- module.exports.tokenInputSchema = tokenInputSchema;
50
- module.exports.indexedTokenInputSchema = indexedTokenInputSchema;
51
- module.exports.multiSigSchema = multiSigSchema;
52
- module.exports.foreignTokenSchema = foreignTokenSchema;
53
- module.exports.hashRegexp = hashRegexp;