0.4.4 • Published 2 years ago

solregex2 v0.4.4

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

solregex

Travis npm Gitter

Tool to generate a Solidity smart contract for a given regular expression.

Installing

npm install -g solregex2

Usage

Provide optional --name parameter and regex as argument.

$ solregex2 --name EmailRegex '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-_]+\.[a-zA-Z]{2,}'

solregex prints the contents of a standalone Solidity source file (.sol) to your terminal's standard out.

You may want to:

  • Save to disk (e.g. solregex 'ab*c?' > Regex.sol)
  • Copy/paste it into an IDE (e.g. solregex '.+abc.*' | pbcopy on macOS, or select with mouse)

Workflow Usage

There are many different workflows for developing / deploying applications with Ethereum.

Generally the process follows these steps:

  1. Run solregex with a regular expression (generates Solidity smart contract)
  2. Compile smart contract
  3. Deploy compiled contract
  4. Use in another contract

Graphviz Output

solregex2 supports generating Graphviz DOT output for a given regular expression's DFA (deterministic finite automaton).

To generate DOT output instead of Solidity, pass the --dot parameter.

Sample Regex DFA

Sample DOT Output: solregex --dot '[a-f]x|[d-i]y|[g-l]z' | dot -Tsvg > sample-regex.svg

Examples

A contract to match email addresses is deployed at 0x537837D00047C874D19B68E94ADbA107674C21b8 (Etherscan)

A contract to match Ethereum addresses is deployed at 0x62C8b4aC2aEF3Ed13B929cA9FB20caCB222E3fA6 (Etherscan)

Approach

Compiling a regular expression to Solidity is done via several steps:

  1. Parse regex using regjsparser

  2. Build NFA (non-deterministic finite automaton) from parse result. Use graph.js for underlying state machine data.

  3. Split overlapping character class ranges into non-overlapping subset ranges (e.g. [a-f], [d-i] become [a-c], [d-f], [g-i]) using interval trees Ref. Graphviz output above for example to highlight this behavior.

  4. Use powerset construction to convert NFA to DFA (deterministic finite automaton)

  5. Convert DFA into Solidity source using a handlebars template.

Status

What's Supported

Supports disjunctions |, alternations (e.g. ab, concatenation), quantifiers (+, *, ?, {n}, {n,m}, {n,}), wildcard matching (.), quantified groups ((...)*, etc.), character classes (positive, negative, ranges)

Supports true/false result for string matching against a regex.

What's Missing

  • Assertions (^, $ for start/end). Currently "enabled" by default.
  • Capturing groups (e.g. (a*)(b*) indicating a/b groups in input string)
  • Backreferences (e.g. (a*)\1)
  • Escape sequences for things like tabs, newlines, word characters, etc.
  • Any kind of multi-line smartness
  • Unicode support
  • Probably more, let me know!

Known Inefficiencies

  • Quantifiers using numeric literals (e.g. a{40}) generate numerous resulting DFA states. This makes the output code very large very fast.

    It may be possible to add support for compressing mostly-identical states into a single state with parameters, to avoid so much output code.

Contributing

Feel free to contact me in the Gitter channel for this repository with any comments, concerns, questions. Let me know if anything is unclear about usage or if you encounter any problems!

If you are interested in helping improve the state of efficient string pattern matching on the EVM, get in touch or open a pull request! Feedback, fixes, and improvements of all kinds are most appreciated :). Thank you!

acorn-dynamic-importacorn-jsxacceptsacornajvalign-textajv-keywordsamdefineansi-regexansi-escapesansi-stylesansi-htmlarr-diffanymatcharray-flattenarr-flattenarray-unionarray-uniqueasn1.jsassertasyncbabel-code-framebabel-helper-call-delegatebabel-generatorbabel-helper-builder-binary-assignment-operator-visitorarray-uniqarrifybabel-helper-function-namebabel-helper-explode-assignable-expressionbabel-helper-define-mapasync-eachbabel-helper-get-function-aritybabel-helper-remap-async-to-generatorbabel-helper-optimise-call-expressionbabel-helpersbabel-helper-hoist-variablesbabel-helper-regexbabel-messagesbabel-plugin-check-es2015-constantsbabel-helper-replace-supersbabel-plugin-syntax-async-functionsbabel-plugin-syntax-trailing-function-commasbabel-plugin-syntax-exponentiation-operatorbabel-plugin-transform-es2015-block-scoped-functionsbabel-plugin-transform-es2015-arrow-functionsbabel-plugin-transform-async-to-generatorbabel-plugin-transform-es2015-classesbabel-plugin-transform-es2015-destructuringbabel-plugin-transform-es2015-computed-propertiesbabel-plugin-transform-es2015-block-scopingbabel-plugin-transform-es2015-duplicate-keysbabel-plugin-transform-es2015-for-ofbabel-plugin-transform-es2015-literalsbabel-plugin-transform-es2015-modules-systemjsbabel-plugin-transform-es2015-modules-amdbabel-plugin-transform-es2015-modules-commonjsbabel-plugin-transform-es2015-function-namebabel-plugin-transform-es2015-modules-umdbabel-plugin-transform-es2015-shorthand-propertiesbabel-plugin-transform-es2015-object-superbabel-plugin-transform-es2015-parametersbabel-plugin-transform-es2015-sticky-regexbabel-plugin-transform-es2015-template-literalsbabel-plugin-transform-es2015-spreadbabel-plugin-transform-strict-modebabel-plugin-transform-es2015-typeof-symbolbabel-plugin-transform-es2015-unicode-regexbabel-plugin-transform-exponentiation-operatorbabel-preset-envbabel-plugin-transform-regeneratorbabel-templatebabel-registerbabel-typesbabel-traversebabylonbase64-jsbatchbrace-expansionbalanced-matchbig.jsbracesbluebirdbn.jsbinary-extensionsbrorandbrowser-fingerprintbrowserify-aesbrowser-stdoutbrowserify-cipherbrowserify-rsabrowserify-desbrowserify-signbrowserify-zlibbrowserslistbuffer-frombufferbuiltin-status-codesbuiltin-modulesbytesbuffer-xorcaller-pathcamelcasecallsitescaniuse-litecenter-alignchokidarchalkcli-cursorcircular-jsoncipher-basecli-widthcliuicocolor-namecode-point-atcompressiblecolor-convertcommandercompressioncommondirconcat-streamconcat-mapconsole-browserifyconnect-history-api-fallbackcontent-dispositionconstants-browserifycontent-typecookieconvert-source-mapcore-util-iscore-jscreate-ecdhcookie-signaturecreate-hashcreate-hmaccrypto-browserifyddebugcuiddate-nowdeep-isdecamelizedes.jsdeldepddestroydiffie-hellmandetect-indentdetect-nodedomain-browserdiffee-firstdoctrineelectron-to-chromiumemojis-listenhanced-resolveellipticencodeurlerror-exes5-extes6-mapes6-iteratores6-setes6-weak-mapes6-symbolerrnoescape-htmlescape-string-regexpescopeespreeesrecurseesqueryesprimaestraverseetagevent-emitteresutilseventemitter3eventsexit-hookeventsourceexpand-rangeextglobexpand-bracketsfast-levenshteinexpressfiguresfilename-regexfile-entry-cacheevp_bytestokeyfinalhandlerfind-upfaye-websocketfill-rangefind-cache-dirflat-cachefor-infor-ownforwardedfreshfs.realpathfs-extragenerate-functiongenerate-object-propertyglobglobalsget-caller-fileglob-parentglobbygraceful-fsglob-basehandle-thinggraceful-readlinkhas-ansigrowlhas-flaghome-or-tmphash.jshash-basehmac-drbghosted-git-infohpack.jshtml-entitieshttp-errorshttp-deceiverhttp-proxyhttps-browserifyhttp-proxy-middlewareieee754imurmurhashindexofignoreinflightinterpretinheritsinvert-kvinquireris-arrayishipaddr.jsis-binary-pathis-bufferinvariantis-builtin-moduleis-equal-shallowis-extglobis-dotfileis-extendableis-fullwidth-code-pointis-globis-finiteis-numberis-path-in-cwdis-path-insideis-my-json-validis-path-cwdis-posix-bracketis-primitiveis-resolvableisobjectisarrayjs-tokensis-propertyis-utf8js-yamljson-stable-stringifyjsescjson-loaderjsonfilejson5jsonifyjsonpointerjson3kind-ofkeypresslazy-cacheklawlevnloader-fs-cachelcidloader-utilsloader-runnerload-json-filelodashlodash._basecreatelodash._basecopylodash._getnativelodash._isiterateecalllodash.createlodash._baseassignlodash.assignlodash.isarraylongestlodash.isargumentslodash.keysmedia-typerloose-envifymemory-fsmemorystreammime-dbmerge-descriptorsmiller-rabinmicromatchmethodsmimeminimalistic-assertminimistminimatchmime-typesmsmute-streamminimalistic-crypto-utilsmkdirpnegotiatornatural-comparenormalize-package-datanormalize-pathnode-fingerprintnode-libs-browsernodent-runtimenumber-is-nanobject-assignobject.omitobufon-headersobject-hashonceoptimiston-finishedonetimeoptionatoropnoriginalos-homediros-browserifyparse-asn1pakoos-localeos-tmpdirparse-globparse-jsonparseurlpath-browserifypath-existspath-is-insidepath-parsepath-is-absolutepath-to-regexppath-dirnamepath-typepbkdf2pinkiepkg-dirpinkie-promiseprelude-lspifyportfinderpluralizeprivateprocess-nextick-argspreserveprocessprogressproxy-addrqsprrpublic-encryptpunycodequerystring-es3querystringquerystringifyrandomaticrange-parserread-pkgread-pkg-upreadable-streamreaddirprandombytesregenerator-runtimeregenerateregenerator-transformregexpu-corerechoirregex-cacherepeat-elementregjsgenreadline2repeat-stringrepeatingremove-trailing-separatorrequire-from-stringrequire-directoryrequire-uncachedrequire-main-filenameresolverequires-portresolve-fromright-alignripemd160rimrafrestore-cursorrx-literun-asyncselect-hosesendsafe-buffersemverserve-indexserve-staticset-immediate-shimset-blockingshallowequalsetimmediatesha.jsshelljssockjs-clientsetprototypeofslashsource-list-mapsockjsslice-ansisource-map-supportsource-mapspdyspdx-expression-parsespdy-transportspdx-correctsprintf-jsstream-httpspdx-license-idsstatusesstring-widthstream-browserifystring_decoderstrip-json-commentsstrip-ansistrip-bomsupports-colortabletext-tabletimers-browserifytapableto-arraybufferto-fast-propertiestoposortthroughtty-browserifytryittrim-righttype-istype-checktypedarrayuniconsuglify-jsunpipeurluglify-to-browserifyurl-parseuser-homeutilutil-deprecateutils-mergevaryuuidvalidate-npm-package-licensewbufvm-browserifywebpack-sourceswebpack-dev-middlewarewebsocket-driverwebsocket-extensionswindow-sizewhich-modulewordwrapwatchpackwrap-ansiwritewrappyxtendy18nyargsyargs-parser
0.4.4

2 years ago

0.4.1

2 years ago

0.4.0

2 years ago

0.4.3

2 years ago

0.3.1

3 years ago