ethereum_js.go 476 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package jsre
  17. const Web3_JS = `
  18. require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  19. module.exports=[
  20. {
  21. "constant": true,
  22. "inputs": [
  23. {
  24. "name": "_owner",
  25. "type": "address"
  26. }
  27. ],
  28. "name": "name",
  29. "outputs": [
  30. {
  31. "name": "o_name",
  32. "type": "bytes32"
  33. }
  34. ],
  35. "type": "function"
  36. },
  37. {
  38. "constant": true,
  39. "inputs": [
  40. {
  41. "name": "_name",
  42. "type": "bytes32"
  43. }
  44. ],
  45. "name": "owner",
  46. "outputs": [
  47. {
  48. "name": "",
  49. "type": "address"
  50. }
  51. ],
  52. "type": "function"
  53. },
  54. {
  55. "constant": true,
  56. "inputs": [
  57. {
  58. "name": "_name",
  59. "type": "bytes32"
  60. }
  61. ],
  62. "name": "content",
  63. "outputs": [
  64. {
  65. "name": "",
  66. "type": "bytes32"
  67. }
  68. ],
  69. "type": "function"
  70. },
  71. {
  72. "constant": true,
  73. "inputs": [
  74. {
  75. "name": "_name",
  76. "type": "bytes32"
  77. }
  78. ],
  79. "name": "addr",
  80. "outputs": [
  81. {
  82. "name": "",
  83. "type": "address"
  84. }
  85. ],
  86. "type": "function"
  87. },
  88. {
  89. "constant": false,
  90. "inputs": [
  91. {
  92. "name": "_name",
  93. "type": "bytes32"
  94. }
  95. ],
  96. "name": "reserve",
  97. "outputs": [],
  98. "type": "function"
  99. },
  100. {
  101. "constant": true,
  102. "inputs": [
  103. {
  104. "name": "_name",
  105. "type": "bytes32"
  106. }
  107. ],
  108. "name": "subRegistrar",
  109. "outputs": [
  110. {
  111. "name": "",
  112. "type": "address"
  113. }
  114. ],
  115. "type": "function"
  116. },
  117. {
  118. "constant": false,
  119. "inputs": [
  120. {
  121. "name": "_name",
  122. "type": "bytes32"
  123. },
  124. {
  125. "name": "_newOwner",
  126. "type": "address"
  127. }
  128. ],
  129. "name": "transfer",
  130. "outputs": [],
  131. "type": "function"
  132. },
  133. {
  134. "constant": false,
  135. "inputs": [
  136. {
  137. "name": "_name",
  138. "type": "bytes32"
  139. },
  140. {
  141. "name": "_registrar",
  142. "type": "address"
  143. }
  144. ],
  145. "name": "setSubRegistrar",
  146. "outputs": [],
  147. "type": "function"
  148. },
  149. {
  150. "constant": false,
  151. "inputs": [],
  152. "name": "Registrar",
  153. "outputs": [],
  154. "type": "function"
  155. },
  156. {
  157. "constant": false,
  158. "inputs": [
  159. {
  160. "name": "_name",
  161. "type": "bytes32"
  162. },
  163. {
  164. "name": "_a",
  165. "type": "address"
  166. },
  167. {
  168. "name": "_primary",
  169. "type": "bool"
  170. }
  171. ],
  172. "name": "setAddress",
  173. "outputs": [],
  174. "type": "function"
  175. },
  176. {
  177. "constant": false,
  178. "inputs": [
  179. {
  180. "name": "_name",
  181. "type": "bytes32"
  182. },
  183. {
  184. "name": "_content",
  185. "type": "bytes32"
  186. }
  187. ],
  188. "name": "setContent",
  189. "outputs": [],
  190. "type": "function"
  191. },
  192. {
  193. "constant": false,
  194. "inputs": [
  195. {
  196. "name": "_name",
  197. "type": "bytes32"
  198. }
  199. ],
  200. "name": "disown",
  201. "outputs": [],
  202. "type": "function"
  203. },
  204. {
  205. "anonymous": false,
  206. "inputs": [
  207. {
  208. "indexed": true,
  209. "name": "_name",
  210. "type": "bytes32"
  211. },
  212. {
  213. "indexed": false,
  214. "name": "_winner",
  215. "type": "address"
  216. }
  217. ],
  218. "name": "AuctionEnded",
  219. "type": "event"
  220. },
  221. {
  222. "anonymous": false,
  223. "inputs": [
  224. {
  225. "indexed": true,
  226. "name": "_name",
  227. "type": "bytes32"
  228. },
  229. {
  230. "indexed": false,
  231. "name": "_bidder",
  232. "type": "address"
  233. },
  234. {
  235. "indexed": false,
  236. "name": "_value",
  237. "type": "uint256"
  238. }
  239. ],
  240. "name": "NewBid",
  241. "type": "event"
  242. },
  243. {
  244. "anonymous": false,
  245. "inputs": [
  246. {
  247. "indexed": true,
  248. "name": "name",
  249. "type": "bytes32"
  250. }
  251. ],
  252. "name": "Changed",
  253. "type": "event"
  254. },
  255. {
  256. "anonymous": false,
  257. "inputs": [
  258. {
  259. "indexed": true,
  260. "name": "name",
  261. "type": "bytes32"
  262. },
  263. {
  264. "indexed": true,
  265. "name": "addr",
  266. "type": "address"
  267. }
  268. ],
  269. "name": "PrimaryChanged",
  270. "type": "event"
  271. }
  272. ]
  273. },{}],2:[function(require,module,exports){
  274. module.exports=[
  275. {
  276. "constant": true,
  277. "inputs": [
  278. {
  279. "name": "_name",
  280. "type": "bytes32"
  281. }
  282. ],
  283. "name": "owner",
  284. "outputs": [
  285. {
  286. "name": "",
  287. "type": "address"
  288. }
  289. ],
  290. "type": "function"
  291. },
  292. {
  293. "constant": false,
  294. "inputs": [
  295. {
  296. "name": "_name",
  297. "type": "bytes32"
  298. },
  299. {
  300. "name": "_refund",
  301. "type": "address"
  302. }
  303. ],
  304. "name": "disown",
  305. "outputs": [],
  306. "type": "function"
  307. },
  308. {
  309. "constant": true,
  310. "inputs": [
  311. {
  312. "name": "_name",
  313. "type": "bytes32"
  314. }
  315. ],
  316. "name": "addr",
  317. "outputs": [
  318. {
  319. "name": "",
  320. "type": "address"
  321. }
  322. ],
  323. "type": "function"
  324. },
  325. {
  326. "constant": false,
  327. "inputs": [
  328. {
  329. "name": "_name",
  330. "type": "bytes32"
  331. }
  332. ],
  333. "name": "reserve",
  334. "outputs": [],
  335. "type": "function"
  336. },
  337. {
  338. "constant": false,
  339. "inputs": [
  340. {
  341. "name": "_name",
  342. "type": "bytes32"
  343. },
  344. {
  345. "name": "_newOwner",
  346. "type": "address"
  347. }
  348. ],
  349. "name": "transfer",
  350. "outputs": [],
  351. "type": "function"
  352. },
  353. {
  354. "constant": false,
  355. "inputs": [
  356. {
  357. "name": "_name",
  358. "type": "bytes32"
  359. },
  360. {
  361. "name": "_a",
  362. "type": "address"
  363. }
  364. ],
  365. "name": "setAddr",
  366. "outputs": [],
  367. "type": "function"
  368. },
  369. {
  370. "anonymous": false,
  371. "inputs": [
  372. {
  373. "indexed": true,
  374. "name": "name",
  375. "type": "bytes32"
  376. }
  377. ],
  378. "name": "Changed",
  379. "type": "event"
  380. }
  381. ]
  382. },{}],3:[function(require,module,exports){
  383. module.exports=[
  384. {
  385. "constant": false,
  386. "inputs": [
  387. {
  388. "name": "from",
  389. "type": "bytes32"
  390. },
  391. {
  392. "name": "to",
  393. "type": "address"
  394. },
  395. {
  396. "name": "value",
  397. "type": "uint256"
  398. }
  399. ],
  400. "name": "transfer",
  401. "outputs": [],
  402. "type": "function"
  403. },
  404. {
  405. "constant": false,
  406. "inputs": [
  407. {
  408. "name": "from",
  409. "type": "bytes32"
  410. },
  411. {
  412. "name": "to",
  413. "type": "address"
  414. },
  415. {
  416. "name": "indirectId",
  417. "type": "bytes32"
  418. },
  419. {
  420. "name": "value",
  421. "type": "uint256"
  422. }
  423. ],
  424. "name": "icapTransfer",
  425. "outputs": [],
  426. "type": "function"
  427. },
  428. {
  429. "constant": false,
  430. "inputs": [
  431. {
  432. "name": "to",
  433. "type": "bytes32"
  434. }
  435. ],
  436. "name": "deposit",
  437. "outputs": [],
  438. "type": "function"
  439. },
  440. {
  441. "anonymous": false,
  442. "inputs": [
  443. {
  444. "indexed": true,
  445. "name": "from",
  446. "type": "address"
  447. },
  448. {
  449. "indexed": false,
  450. "name": "value",
  451. "type": "uint256"
  452. }
  453. ],
  454. "name": "AnonymousDeposit",
  455. "type": "event"
  456. },
  457. {
  458. "anonymous": false,
  459. "inputs": [
  460. {
  461. "indexed": true,
  462. "name": "from",
  463. "type": "address"
  464. },
  465. {
  466. "indexed": true,
  467. "name": "to",
  468. "type": "bytes32"
  469. },
  470. {
  471. "indexed": false,
  472. "name": "value",
  473. "type": "uint256"
  474. }
  475. ],
  476. "name": "Deposit",
  477. "type": "event"
  478. },
  479. {
  480. "anonymous": false,
  481. "inputs": [
  482. {
  483. "indexed": true,
  484. "name": "from",
  485. "type": "bytes32"
  486. },
  487. {
  488. "indexed": true,
  489. "name": "to",
  490. "type": "address"
  491. },
  492. {
  493. "indexed": false,
  494. "name": "value",
  495. "type": "uint256"
  496. }
  497. ],
  498. "name": "Transfer",
  499. "type": "event"
  500. },
  501. {
  502. "anonymous": false,
  503. "inputs": [
  504. {
  505. "indexed": true,
  506. "name": "from",
  507. "type": "bytes32"
  508. },
  509. {
  510. "indexed": true,
  511. "name": "to",
  512. "type": "address"
  513. },
  514. {
  515. "indexed": false,
  516. "name": "indirectId",
  517. "type": "bytes32"
  518. },
  519. {
  520. "indexed": false,
  521. "name": "value",
  522. "type": "uint256"
  523. }
  524. ],
  525. "name": "IcapTransfer",
  526. "type": "event"
  527. }
  528. ]
  529. },{}],4:[function(require,module,exports){
  530. var f = require('./formatters');
  531. var SolidityType = require('./type');
  532. /**
  533. * SolidityTypeAddress is a prootype that represents address type
  534. * It matches:
  535. * address
  536. * address[]
  537. * address[4]
  538. * address[][]
  539. * address[3][]
  540. * address[][6][], ...
  541. */
  542. var SolidityTypeAddress = function () {
  543. this._inputFormatter = f.formatInputInt;
  544. this._outputFormatter = f.formatOutputAddress;
  545. };
  546. SolidityTypeAddress.prototype = new SolidityType({});
  547. SolidityTypeAddress.prototype.constructor = SolidityTypeAddress;
  548. SolidityTypeAddress.prototype.isType = function (name) {
  549. return !!name.match(/address(\[([0-9]*)\])?/);
  550. };
  551. SolidityTypeAddress.prototype.staticPartLength = function (name) {
  552. return 32 * this.staticArrayLength(name);
  553. };
  554. module.exports = SolidityTypeAddress;
  555. },{"./formatters":9,"./type":14}],5:[function(require,module,exports){
  556. var f = require('./formatters');
  557. var SolidityType = require('./type');
  558. /**
  559. * SolidityTypeBool is a prootype that represents bool type
  560. * It matches:
  561. * bool
  562. * bool[]
  563. * bool[4]
  564. * bool[][]
  565. * bool[3][]
  566. * bool[][6][], ...
  567. */
  568. var SolidityTypeBool = function () {
  569. this._inputFormatter = f.formatInputBool;
  570. this._outputFormatter = f.formatOutputBool;
  571. };
  572. SolidityTypeBool.prototype = new SolidityType({});
  573. SolidityTypeBool.prototype.constructor = SolidityTypeBool;
  574. SolidityTypeBool.prototype.isType = function (name) {
  575. return !!name.match(/^bool(\[([0-9]*)\])*$/);
  576. };
  577. SolidityTypeBool.prototype.staticPartLength = function (name) {
  578. return 32 * this.staticArrayLength(name);
  579. };
  580. module.exports = SolidityTypeBool;
  581. },{"./formatters":9,"./type":14}],6:[function(require,module,exports){
  582. var f = require('./formatters');
  583. var SolidityType = require('./type');
  584. /**
  585. * SolidityTypeBytes is a prootype that represents bytes type
  586. * It matches:
  587. * bytes
  588. * bytes[]
  589. * bytes[4]
  590. * bytes[][]
  591. * bytes[3][]
  592. * bytes[][6][], ...
  593. * bytes32
  594. * bytes64[]
  595. * bytes8[4]
  596. * bytes256[][]
  597. * bytes[3][]
  598. * bytes64[][6][], ...
  599. */
  600. var SolidityTypeBytes = function () {
  601. this._inputFormatter = f.formatInputBytes;
  602. this._outputFormatter = f.formatOutputBytes;
  603. };
  604. SolidityTypeBytes.prototype = new SolidityType({});
  605. SolidityTypeBytes.prototype.constructor = SolidityTypeBytes;
  606. SolidityTypeBytes.prototype.isType = function (name) {
  607. return !!name.match(/^bytes([0-9]{1,})(\[([0-9]*)\])*$/);
  608. };
  609. SolidityTypeBytes.prototype.staticPartLength = function (name) {
  610. var matches = name.match(/^bytes([0-9]*)/);
  611. var size = parseInt(matches[1]);
  612. return size * this.staticArrayLength(name);
  613. };
  614. module.exports = SolidityTypeBytes;
  615. },{"./formatters":9,"./type":14}],7:[function(require,module,exports){
  616. /*
  617. This file is part of web3.js.
  618. web3.js is free software: you can redistribute it and/or modify
  619. it under the terms of the GNU Lesser General Public License as published by
  620. the Free Software Foundation, either version 3 of the License, or
  621. (at your option) any later version.
  622. web3.js is distributed in the hope that it will be useful,
  623. but WITHOUT ANY WARRANTY; without even the implied warranty of
  624. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  625. GNU Lesser General Public License for more details.
  626. You should have received a copy of the GNU Lesser General Public License
  627. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  628. */
  629. /**
  630. * @file coder.js
  631. * @author Marek Kotewicz <marek@ethdev.com>
  632. * @date 2015
  633. */
  634. var f = require('./formatters');
  635. var SolidityTypeAddress = require('./address');
  636. var SolidityTypeBool = require('./bool');
  637. var SolidityTypeInt = require('./int');
  638. var SolidityTypeUInt = require('./uint');
  639. var SolidityTypeDynamicBytes = require('./dynamicbytes');
  640. var SolidityTypeString = require('./string');
  641. var SolidityTypeReal = require('./real');
  642. var SolidityTypeUReal = require('./ureal');
  643. var SolidityTypeBytes = require('./bytes');
  644. /**
  645. * SolidityCoder prototype should be used to encode/decode solidity params of any type
  646. */
  647. var SolidityCoder = function (types) {
  648. this._types = types;
  649. };
  650. /**
  651. * This method should be used to transform type to SolidityType
  652. *
  653. * @method _requireType
  654. * @param {String} type
  655. * @returns {SolidityType}
  656. * @throws {Error} throws if no matching type is found
  657. */
  658. SolidityCoder.prototype._requireType = function (type) {
  659. var solidityType = this._types.filter(function (t) {
  660. return t.isType(type);
  661. })[0];
  662. if (!solidityType) {
  663. throw Error('invalid solidity type!: ' + type);
  664. }
  665. return solidityType;
  666. };
  667. /**
  668. * Should be used to encode plain param
  669. *
  670. * @method encodeParam
  671. * @param {String} type
  672. * @param {Object} plain param
  673. * @return {String} encoded plain param
  674. */
  675. SolidityCoder.prototype.encodeParam = function (type, param) {
  676. return this.encodeParams([type], [param]);
  677. };
  678. /**
  679. * Should be used to encode list of params
  680. *
  681. * @method encodeParams
  682. * @param {Array} types
  683. * @param {Array} params
  684. * @return {String} encoded list of params
  685. */
  686. SolidityCoder.prototype.encodeParams = function (types, params) {
  687. var solidityTypes = this.getSolidityTypes(types);
  688. var encodeds = solidityTypes.map(function (solidityType, index) {
  689. return solidityType.encode(params[index], types[index]);
  690. });
  691. var dynamicOffset = solidityTypes.reduce(function (acc, solidityType, index) {
  692. var staticPartLength = solidityType.staticPartLength(types[index]);
  693. var roundedStaticPartLength = Math.floor((staticPartLength + 31) / 32) * 32;
  694. return acc + roundedStaticPartLength;
  695. }, 0);
  696. var result = this.encodeMultiWithOffset(types, solidityTypes, encodeds, dynamicOffset);
  697. return result;
  698. };
  699. SolidityCoder.prototype.encodeMultiWithOffset = function (types, solidityTypes, encodeds, dynamicOffset) {
  700. var result = "";
  701. var self = this;
  702. var isDynamic = function (i) {
  703. return solidityTypes[i].isDynamicArray(types[i]) || solidityTypes[i].isDynamicType(types[i]);
  704. };
  705. types.forEach(function (type, i) {
  706. if (isDynamic(i)) {
  707. result += f.formatInputInt(dynamicOffset).encode();
  708. var e = self.encodeWithOffset(types[i], solidityTypes[i], encodeds[i], dynamicOffset);
  709. dynamicOffset += e.length / 2;
  710. } else {
  711. // don't add length to dynamicOffset. it's already counted
  712. result += self.encodeWithOffset(types[i], solidityTypes[i], encodeds[i], dynamicOffset);
  713. }
  714. // TODO: figure out nested arrays
  715. });
  716. types.forEach(function (type, i) {
  717. if (isDynamic(i)) {
  718. var e = self.encodeWithOffset(types[i], solidityTypes[i], encodeds[i], dynamicOffset);
  719. dynamicOffset += e.length / 2;
  720. result += e;
  721. }
  722. });
  723. return result;
  724. };
  725. // TODO: refactor whole encoding!
  726. SolidityCoder.prototype.encodeWithOffset = function (type, solidityType, encoded, offset) {
  727. var self = this;
  728. if (solidityType.isDynamicArray(type)) {
  729. return (function () {
  730. // offset was already set
  731. var nestedName = solidityType.nestedName(type);
  732. var nestedStaticPartLength = solidityType.staticPartLength(nestedName);
  733. var result = encoded[0];
  734. (function () {
  735. var previousLength = 2; // in int
  736. if (solidityType.isDynamicArray(nestedName)) {
  737. for (var i = 1; i < encoded.length; i++) {
  738. previousLength += +(encoded[i - 1])[0] || 0;
  739. result += f.formatInputInt(offset + i * nestedStaticPartLength + previousLength * 32).encode();
  740. }
  741. }
  742. })();
  743. // first element is length, skip it
  744. (function () {
  745. for (var i = 0; i < encoded.length - 1; i++) {
  746. var additionalOffset = result / 2;
  747. result += self.encodeWithOffset(nestedName, solidityType, encoded[i + 1], offset + additionalOffset);
  748. }
  749. })();
  750. return result;
  751. })();
  752. } else if (solidityType.isStaticArray(type)) {
  753. return (function () {
  754. var nestedName = solidityType.nestedName(type);
  755. var nestedStaticPartLength = solidityType.staticPartLength(nestedName);
  756. var result = "";
  757. if (solidityType.isDynamicArray(nestedName)) {
  758. (function () {
  759. var previousLength = 0; // in int
  760. for (var i = 0; i < encoded.length; i++) {
  761. // calculate length of previous item
  762. previousLength += +(encoded[i - 1] || [])[0] || 0;
  763. result += f.formatInputInt(offset + i * nestedStaticPartLength + previousLength * 32).encode();
  764. }
  765. })();
  766. }
  767. (function () {
  768. for (var i = 0; i < encoded.length; i++) {
  769. var additionalOffset = result / 2;
  770. result += self.encodeWithOffset(nestedName, solidityType, encoded[i], offset + additionalOffset);
  771. }
  772. })();
  773. return result;
  774. })();
  775. }
  776. return encoded;
  777. };
  778. /**
  779. * Should be used to decode bytes to plain param
  780. *
  781. * @method decodeParam
  782. * @param {String} type
  783. * @param {String} bytes
  784. * @return {Object} plain param
  785. */
  786. SolidityCoder.prototype.decodeParam = function (type, bytes) {
  787. return this.decodeParams([type], bytes)[0];
  788. };
  789. /**
  790. * Should be used to decode list of params
  791. *
  792. * @method decodeParam
  793. * @param {Array} types
  794. * @param {String} bytes
  795. * @return {Array} array of plain params
  796. */
  797. SolidityCoder.prototype.decodeParams = function (types, bytes) {
  798. var solidityTypes = this.getSolidityTypes(types);
  799. var offsets = this.getOffsets(types, solidityTypes);
  800. return solidityTypes.map(function (solidityType, index) {
  801. return solidityType.decode(bytes, offsets[index], types[index], index);
  802. });
  803. };
  804. SolidityCoder.prototype.getOffsets = function (types, solidityTypes) {
  805. var lengths = solidityTypes.map(function (solidityType, index) {
  806. return solidityType.staticPartLength(types[index]);
  807. });
  808. for (var i = 1; i < lengths.length; i++) {
  809. // sum with length of previous element
  810. lengths[i] += lengths[i - 1];
  811. }
  812. return lengths.map(function (length, index) {
  813. // remove the current length, so the length is sum of previous elements
  814. var staticPartLength = solidityTypes[index].staticPartLength(types[index]);
  815. return length - staticPartLength;
  816. });
  817. };
  818. SolidityCoder.prototype.getSolidityTypes = function (types) {
  819. var self = this;
  820. return types.map(function (type) {
  821. return self._requireType(type);
  822. });
  823. };
  824. var coder = new SolidityCoder([
  825. new SolidityTypeAddress(),
  826. new SolidityTypeBool(),
  827. new SolidityTypeInt(),
  828. new SolidityTypeUInt(),
  829. new SolidityTypeDynamicBytes(),
  830. new SolidityTypeBytes(),
  831. new SolidityTypeString(),
  832. new SolidityTypeReal(),
  833. new SolidityTypeUReal()
  834. ]);
  835. module.exports = coder;
  836. },{"./address":4,"./bool":5,"./bytes":6,"./dynamicbytes":8,"./formatters":9,"./int":10,"./real":12,"./string":13,"./uint":15,"./ureal":16}],8:[function(require,module,exports){
  837. var f = require('./formatters');
  838. var SolidityType = require('./type');
  839. var SolidityTypeDynamicBytes = function () {
  840. this._inputFormatter = f.formatInputDynamicBytes;
  841. this._outputFormatter = f.formatOutputDynamicBytes;
  842. };
  843. SolidityTypeDynamicBytes.prototype = new SolidityType({});
  844. SolidityTypeDynamicBytes.prototype.constructor = SolidityTypeDynamicBytes;
  845. SolidityTypeDynamicBytes.prototype.isType = function (name) {
  846. return !!name.match(/^bytes(\[([0-9]*)\])*$/);
  847. };
  848. SolidityTypeDynamicBytes.prototype.staticPartLength = function (name) {
  849. return 32 * this.staticArrayLength(name);
  850. };
  851. SolidityTypeDynamicBytes.prototype.isDynamicType = function () {
  852. return true;
  853. };
  854. module.exports = SolidityTypeDynamicBytes;
  855. },{"./formatters":9,"./type":14}],9:[function(require,module,exports){
  856. /*
  857. This file is part of web3.js.
  858. web3.js is free software: you can redistribute it and/or modify
  859. it under the terms of the GNU Lesser General Public License as published by
  860. the Free Software Foundation, either version 3 of the License, or
  861. (at your option) any later version.
  862. web3.js is distributed in the hope that it will be useful,
  863. but WITHOUT ANY WARRANTY; without even the implied warranty of
  864. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  865. GNU Lesser General Public License for more details.
  866. You should have received a copy of the GNU Lesser General Public License
  867. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  868. */
  869. /**
  870. * @file formatters.js
  871. * @author Marek Kotewicz <marek@ethdev.com>
  872. * @date 2015
  873. */
  874. var BigNumber = require('bignumber.js');
  875. var utils = require('../utils/utils');
  876. var c = require('../utils/config');
  877. var SolidityParam = require('./param');
  878. /**
  879. * Formats input value to byte representation of int
  880. * If value is negative, return it's two's complement
  881. * If the value is floating point, round it down
  882. *
  883. * @method formatInputInt
  884. * @param {String|Number|BigNumber} value that needs to be formatted
  885. * @returns {SolidityParam}
  886. */
  887. var formatInputInt = function (value) {
  888. BigNumber.config(c.ETH_BIGNUMBER_ROUNDING_MODE);
  889. var result = utils.padLeft(utils.toTwosComplement(value).round().toString(16), 64);
  890. return new SolidityParam(result);
  891. };
  892. /**
  893. * Formats input bytes
  894. *
  895. * @method formatInputBytes
  896. * @param {String}
  897. * @returns {SolidityParam}
  898. */
  899. var formatInputBytes = function (value) {
  900. var result = utils.toHex(value).substr(2);
  901. var l = Math.floor((result.length + 63) / 64);
  902. result = utils.padRight(result, l * 64);
  903. return new SolidityParam(result);
  904. };
  905. /**
  906. * Formats input bytes
  907. *
  908. * @method formatDynamicInputBytes
  909. * @param {String}
  910. * @returns {SolidityParam}
  911. */
  912. var formatInputDynamicBytes = function (value) {
  913. var result = utils.toHex(value).substr(2);
  914. var length = result.length / 2;
  915. var l = Math.floor((result.length + 63) / 64);
  916. result = utils.padRight(result, l * 64);
  917. return new SolidityParam(formatInputInt(length).value + result);
  918. };
  919. /**
  920. * Formats input value to byte representation of string
  921. *
  922. * @method formatInputString
  923. * @param {String}
  924. * @returns {SolidityParam}
  925. */
  926. var formatInputString = function (value) {
  927. var result = utils.fromUtf8(value).substr(2);
  928. var length = result.length / 2;
  929. var l = Math.floor((result.length + 63) / 64);
  930. result = utils.padRight(result, l * 64);
  931. return new SolidityParam(formatInputInt(length).value + result);
  932. };
  933. /**
  934. * Formats input value to byte representation of bool
  935. *
  936. * @method formatInputBool
  937. * @param {Boolean}
  938. * @returns {SolidityParam}
  939. */
  940. var formatInputBool = function (value) {
  941. var result = '000000000000000000000000000000000000000000000000000000000000000' + (value ? '1' : '0');
  942. return new SolidityParam(result);
  943. };
  944. /**
  945. * Formats input value to byte representation of real
  946. * Values are multiplied by 2^m and encoded as integers
  947. *
  948. * @method formatInputReal
  949. * @param {String|Number|BigNumber}
  950. * @returns {SolidityParam}
  951. */
  952. var formatInputReal = function (value) {
  953. return formatInputInt(new BigNumber(value).times(new BigNumber(2).pow(128)));
  954. };
  955. /**
  956. * Check if input value is negative
  957. *
  958. * @method signedIsNegative
  959. * @param {String} value is hex format
  960. * @returns {Boolean} true if it is negative, otherwise false
  961. */
  962. var signedIsNegative = function (value) {
  963. return (new BigNumber(value.substr(0, 1), 16).toString(2).substr(0, 1)) === '1';
  964. };
  965. /**
  966. * Formats right-aligned output bytes to int
  967. *
  968. * @method formatOutputInt
  969. * @param {SolidityParam} param
  970. * @returns {BigNumber} right-aligned output bytes formatted to big number
  971. */
  972. var formatOutputInt = function (param) {
  973. var value = param.staticPart() || "0";
  974. // check if it's negative number
  975. // it it is, return two's complement
  976. if (signedIsNegative(value)) {
  977. return new BigNumber(value, 16).minus(new BigNumber('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16)).minus(1);
  978. }
  979. return new BigNumber(value, 16);
  980. };
  981. /**
  982. * Formats right-aligned output bytes to uint
  983. *
  984. * @method formatOutputUInt
  985. * @param {SolidityParam}
  986. * @returns {BigNumeber} right-aligned output bytes formatted to uint
  987. */
  988. var formatOutputUInt = function (param) {
  989. var value = param.staticPart() || "0";
  990. return new BigNumber(value, 16);
  991. };
  992. /**
  993. * Formats right-aligned output bytes to real
  994. *
  995. * @method formatOutputReal
  996. * @param {SolidityParam}
  997. * @returns {BigNumber} input bytes formatted to real
  998. */
  999. var formatOutputReal = function (param) {
  1000. return formatOutputInt(param).dividedBy(new BigNumber(2).pow(128));
  1001. };
  1002. /**
  1003. * Formats right-aligned output bytes to ureal
  1004. *
  1005. * @method formatOutputUReal
  1006. * @param {SolidityParam}
  1007. * @returns {BigNumber} input bytes formatted to ureal
  1008. */
  1009. var formatOutputUReal = function (param) {
  1010. return formatOutputUInt(param).dividedBy(new BigNumber(2).pow(128));
  1011. };
  1012. /**
  1013. * Should be used to format output bool
  1014. *
  1015. * @method formatOutputBool
  1016. * @param {SolidityParam}
  1017. * @returns {Boolean} right-aligned input bytes formatted to bool
  1018. */
  1019. var formatOutputBool = function (param) {
  1020. return param.staticPart() === '0000000000000000000000000000000000000000000000000000000000000001' ? true : false;
  1021. };
  1022. /**
  1023. * Should be used to format output bytes
  1024. *
  1025. * @method formatOutputBytes
  1026. * @param {SolidityParam} left-aligned hex representation of string
  1027. * @returns {String} hex string
  1028. */
  1029. var formatOutputBytes = function (param) {
  1030. return '0x' + param.staticPart();
  1031. };
  1032. /**
  1033. * Should be used to format output bytes
  1034. *
  1035. * @method formatOutputDynamicBytes
  1036. * @param {SolidityParam} left-aligned hex representation of string
  1037. * @returns {String} hex string
  1038. */
  1039. var formatOutputDynamicBytes = function (param) {
  1040. var length = (new BigNumber(param.dynamicPart().slice(0, 64), 16)).toNumber() * 2;
  1041. return '0x' + param.dynamicPart().substr(64, length);
  1042. };
  1043. /**
  1044. * Should be used to format output string
  1045. *
  1046. * @method formatOutputString
  1047. * @param {SolidityParam} left-aligned hex representation of string
  1048. * @returns {String} ascii string
  1049. */
  1050. var formatOutputString = function (param) {
  1051. var length = (new BigNumber(param.dynamicPart().slice(0, 64), 16)).toNumber() * 2;
  1052. return utils.toUtf8(param.dynamicPart().substr(64, length));
  1053. };
  1054. /**
  1055. * Should be used to format output address
  1056. *
  1057. * @method formatOutputAddress
  1058. * @param {SolidityParam} right-aligned input bytes
  1059. * @returns {String} address
  1060. */
  1061. var formatOutputAddress = function (param) {
  1062. var value = param.staticPart();
  1063. return "0x" + value.slice(value.length - 40, value.length);
  1064. };
  1065. module.exports = {
  1066. formatInputInt: formatInputInt,
  1067. formatInputBytes: formatInputBytes,
  1068. formatInputDynamicBytes: formatInputDynamicBytes,
  1069. formatInputString: formatInputString,
  1070. formatInputBool: formatInputBool,
  1071. formatInputReal: formatInputReal,
  1072. formatOutputInt: formatOutputInt,
  1073. formatOutputUInt: formatOutputUInt,
  1074. formatOutputReal: formatOutputReal,
  1075. formatOutputUReal: formatOutputUReal,
  1076. formatOutputBool: formatOutputBool,
  1077. formatOutputBytes: formatOutputBytes,
  1078. formatOutputDynamicBytes: formatOutputDynamicBytes,
  1079. formatOutputString: formatOutputString,
  1080. formatOutputAddress: formatOutputAddress
  1081. };
  1082. },{"../utils/config":18,"../utils/utils":20,"./param":11,"bignumber.js":"bignumber.js"}],10:[function(require,module,exports){
  1083. var f = require('./formatters');
  1084. var SolidityType = require('./type');
  1085. /**
  1086. * SolidityTypeInt is a prootype that represents int type
  1087. * It matches:
  1088. * int
  1089. * int[]
  1090. * int[4]
  1091. * int[][]
  1092. * int[3][]
  1093. * int[][6][], ...
  1094. * int32
  1095. * int64[]
  1096. * int8[4]
  1097. * int256[][]
  1098. * int[3][]
  1099. * int64[][6][], ...
  1100. */
  1101. var SolidityTypeInt = function () {
  1102. this._inputFormatter = f.formatInputInt;
  1103. this._outputFormatter = f.formatOutputInt;
  1104. };
  1105. SolidityTypeInt.prototype = new SolidityType({});
  1106. SolidityTypeInt.prototype.constructor = SolidityTypeInt;
  1107. SolidityTypeInt.prototype.isType = function (name) {
  1108. return !!name.match(/^int([0-9]*)?(\[([0-9]*)\])*$/);
  1109. };
  1110. SolidityTypeInt.prototype.staticPartLength = function (name) {
  1111. return 32 * this.staticArrayLength(name);
  1112. };
  1113. module.exports = SolidityTypeInt;
  1114. },{"./formatters":9,"./type":14}],11:[function(require,module,exports){
  1115. /*
  1116. This file is part of web3.js.
  1117. web3.js is free software: you can redistribute it and/or modify
  1118. it under the terms of the GNU Lesser General Public License as published by
  1119. the Free Software Foundation, either version 3 of the License, or
  1120. (at your option) any later version.
  1121. web3.js is distributed in the hope that it will be useful,
  1122. but WITHOUT ANY WARRANTY; without even the implied warranty of
  1123. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  1124. GNU Lesser General Public License for more details.
  1125. You should have received a copy of the GNU Lesser General Public License
  1126. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  1127. */
  1128. /**
  1129. * @file param.js
  1130. * @author Marek Kotewicz <marek@ethdev.com>
  1131. * @date 2015
  1132. */
  1133. var utils = require('../utils/utils');
  1134. /**
  1135. * SolidityParam object prototype.
  1136. * Should be used when encoding, decoding solidity bytes
  1137. */
  1138. var SolidityParam = function (value, offset) {
  1139. this.value = value || '';
  1140. this.offset = offset; // offset in bytes
  1141. };
  1142. /**
  1143. * This method should be used to get length of params's dynamic part
  1144. *
  1145. * @method dynamicPartLength
  1146. * @returns {Number} length of dynamic part (in bytes)
  1147. */
  1148. SolidityParam.prototype.dynamicPartLength = function () {
  1149. return this.dynamicPart().length / 2;
  1150. };
  1151. /**
  1152. * This method should be used to create copy of solidity param with different offset
  1153. *
  1154. * @method withOffset
  1155. * @param {Number} offset length in bytes
  1156. * @returns {SolidityParam} new solidity param with applied offset
  1157. */
  1158. SolidityParam.prototype.withOffset = function (offset) {
  1159. return new SolidityParam(this.value, offset);
  1160. };
  1161. /**
  1162. * This method should be used to combine solidity params together
  1163. * eg. when appending an array
  1164. *
  1165. * @method combine
  1166. * @param {SolidityParam} param with which we should combine
  1167. * @param {SolidityParam} result of combination
  1168. */
  1169. SolidityParam.prototype.combine = function (param) {
  1170. return new SolidityParam(this.value + param.value);
  1171. };
  1172. /**
  1173. * This method should be called to check if param has dynamic size.
  1174. * If it has, it returns true, otherwise false
  1175. *
  1176. * @method isDynamic
  1177. * @returns {Boolean}
  1178. */
  1179. SolidityParam.prototype.isDynamic = function () {
  1180. return this.offset !== undefined;
  1181. };
  1182. /**
  1183. * This method should be called to transform offset to bytes
  1184. *
  1185. * @method offsetAsBytes
  1186. * @returns {String} bytes representation of offset
  1187. */
  1188. SolidityParam.prototype.offsetAsBytes = function () {
  1189. return !this.isDynamic() ? '' : utils.padLeft(utils.toTwosComplement(this.offset).toString(16), 64);
  1190. };
  1191. /**
  1192. * This method should be called to get static part of param
  1193. *
  1194. * @method staticPart
  1195. * @returns {String} offset if it is a dynamic param, otherwise value
  1196. */
  1197. SolidityParam.prototype.staticPart = function () {
  1198. if (!this.isDynamic()) {
  1199. return this.value;
  1200. }
  1201. return this.offsetAsBytes();
  1202. };
  1203. /**
  1204. * This method should be called to get dynamic part of param
  1205. *
  1206. * @method dynamicPart
  1207. * @returns {String} returns a value if it is a dynamic param, otherwise empty string
  1208. */
  1209. SolidityParam.prototype.dynamicPart = function () {
  1210. return this.isDynamic() ? this.value : '';
  1211. };
  1212. /**
  1213. * This method should be called to encode param
  1214. *
  1215. * @method encode
  1216. * @returns {String}
  1217. */
  1218. SolidityParam.prototype.encode = function () {
  1219. return this.staticPart() + this.dynamicPart();
  1220. };
  1221. /**
  1222. * This method should be called to encode array of params
  1223. *
  1224. * @method encodeList
  1225. * @param {Array[SolidityParam]} params
  1226. * @returns {String}
  1227. */
  1228. SolidityParam.encodeList = function (params) {
  1229. // updating offsets
  1230. var totalOffset = params.length * 32;
  1231. var offsetParams = params.map(function (param) {
  1232. if (!param.isDynamic()) {
  1233. return param;
  1234. }
  1235. var offset = totalOffset;
  1236. totalOffset += param.dynamicPartLength();
  1237. return param.withOffset(offset);
  1238. });
  1239. // encode everything!
  1240. return offsetParams.reduce(function (result, param) {
  1241. return result + param.dynamicPart();
  1242. }, offsetParams.reduce(function (result, param) {
  1243. return result + param.staticPart();
  1244. }, ''));
  1245. };
  1246. module.exports = SolidityParam;
  1247. },{"../utils/utils":20}],12:[function(require,module,exports){
  1248. var f = require('./formatters');
  1249. var SolidityType = require('./type');
  1250. /**
  1251. * SolidityTypeReal is a prootype that represents real type
  1252. * It matches:
  1253. * real
  1254. * real[]
  1255. * real[4]
  1256. * real[][]
  1257. * real[3][]
  1258. * real[][6][], ...
  1259. * real32
  1260. * real64[]
  1261. * real8[4]
  1262. * real256[][]
  1263. * real[3][]
  1264. * real64[][6][], ...
  1265. */
  1266. var SolidityTypeReal = function () {
  1267. this._inputFormatter = f.formatInputReal;
  1268. this._outputFormatter = f.formatOutputReal;
  1269. };
  1270. SolidityTypeReal.prototype = new SolidityType({});
  1271. SolidityTypeReal.prototype.constructor = SolidityTypeReal;
  1272. SolidityTypeReal.prototype.isType = function (name) {
  1273. return !!name.match(/real([0-9]*)?(\[([0-9]*)\])?/);
  1274. };
  1275. SolidityTypeReal.prototype.staticPartLength = function (name) {
  1276. return 32 * this.staticArrayLength(name);
  1277. };
  1278. module.exports = SolidityTypeReal;
  1279. },{"./formatters":9,"./type":14}],13:[function(require,module,exports){
  1280. var f = require('./formatters');
  1281. var SolidityType = require('./type');
  1282. var SolidityTypeString = function () {
  1283. this._inputFormatter = f.formatInputString;
  1284. this._outputFormatter = f.formatOutputString;
  1285. };
  1286. SolidityTypeString.prototype = new SolidityType({});
  1287. SolidityTypeString.prototype.constructor = SolidityTypeString;
  1288. SolidityTypeString.prototype.isType = function (name) {
  1289. return !!name.match(/^string(\[([0-9]*)\])*$/);
  1290. };
  1291. SolidityTypeString.prototype.staticPartLength = function (name) {
  1292. return 32 * this.staticArrayLength(name);
  1293. };
  1294. SolidityTypeString.prototype.isDynamicType = function () {
  1295. return true;
  1296. };
  1297. module.exports = SolidityTypeString;
  1298. },{"./formatters":9,"./type":14}],14:[function(require,module,exports){
  1299. var f = require('./formatters');
  1300. var SolidityParam = require('./param');
  1301. /**
  1302. * SolidityType prototype is used to encode/decode solidity params of certain type
  1303. */
  1304. var SolidityType = function (config) {
  1305. this._inputFormatter = config.inputFormatter;
  1306. this._outputFormatter = config.outputFormatter;
  1307. };
  1308. /**
  1309. * Should be used to determine if this SolidityType do match given name
  1310. *
  1311. * @method isType
  1312. * @param {String} name
  1313. * @return {Bool} true if type match this SolidityType, otherwise false
  1314. */
  1315. SolidityType.prototype.isType = function (name) {
  1316. throw "this method should be overrwritten for type " + name;
  1317. };
  1318. /**
  1319. * Should be used to determine what is the length of static part in given type
  1320. *
  1321. * @method staticPartLength
  1322. * @param {String} name
  1323. * @return {Number} length of static part in bytes
  1324. */
  1325. SolidityType.prototype.staticPartLength = function (name) {
  1326. throw "this method should be overrwritten for type: " + name;
  1327. };
  1328. /**
  1329. * Should be used to determine if type is dynamic array
  1330. * eg:
  1331. * "type[]" => true
  1332. * "type[4]" => false
  1333. *
  1334. * @method isDynamicArray
  1335. * @param {String} name
  1336. * @return {Bool} true if the type is dynamic array
  1337. */
  1338. SolidityType.prototype.isDynamicArray = function (name) {
  1339. var nestedTypes = this.nestedTypes(name);
  1340. return !!nestedTypes && !nestedTypes[nestedTypes.length - 1].match(/[0-9]{1,}/g);
  1341. };
  1342. /**
  1343. * Should be used to determine if type is static array
  1344. * eg:
  1345. * "type[]" => false
  1346. * "type[4]" => true
  1347. *
  1348. * @method isStaticArray
  1349. * @param {String} name
  1350. * @return {Bool} true if the type is static array
  1351. */
  1352. SolidityType.prototype.isStaticArray = function (name) {
  1353. var nestedTypes = this.nestedTypes(name);
  1354. return !!nestedTypes && !!nestedTypes[nestedTypes.length - 1].match(/[0-9]{1,}/g);
  1355. };
  1356. /**
  1357. * Should return length of static array
  1358. * eg.
  1359. * "int[32]" => 32
  1360. * "int256[14]" => 14
  1361. * "int[2][3]" => 3
  1362. * "int" => 1
  1363. * "int[1]" => 1
  1364. * "int[]" => 1
  1365. *
  1366. * @method staticArrayLength
  1367. * @param {String} name
  1368. * @return {Number} static array length
  1369. */
  1370. SolidityType.prototype.staticArrayLength = function (name) {
  1371. var nestedTypes = this.nestedTypes(name);
  1372. if (nestedTypes) {
  1373. return parseInt(nestedTypes[nestedTypes.length - 1].match(/[0-9]{1,}/g) || 1);
  1374. }
  1375. return 1;
  1376. };
  1377. /**
  1378. * Should return nested type
  1379. * eg.
  1380. * "int[32]" => "int"
  1381. * "int256[14]" => "int256"
  1382. * "int[2][3]" => "int[2]"
  1383. * "int" => "int"
  1384. * "int[]" => "int"
  1385. *
  1386. * @method nestedName
  1387. * @param {String} name
  1388. * @return {String} nested name
  1389. */
  1390. SolidityType.prototype.nestedName = function (name) {
  1391. // remove last [] in name
  1392. var nestedTypes = this.nestedTypes(name);
  1393. if (!nestedTypes) {
  1394. return name;
  1395. }
  1396. return name.substr(0, name.length - nestedTypes[nestedTypes.length - 1].length);
  1397. };
  1398. /**
  1399. * Should return true if type has dynamic size by default
  1400. * such types are "string", "bytes"
  1401. *
  1402. * @method isDynamicType
  1403. * @param {String} name
  1404. * @return {Bool} true if is dynamic, otherwise false
  1405. */
  1406. SolidityType.prototype.isDynamicType = function () {
  1407. return false;
  1408. };
  1409. /**
  1410. * Should return array of nested types
  1411. * eg.
  1412. * "int[2][3][]" => ["[2]", "[3]", "[]"]
  1413. * "int[] => ["[]"]
  1414. * "int" => null
  1415. *
  1416. * @method nestedTypes
  1417. * @param {String} name
  1418. * @return {Array} array of nested types
  1419. */
  1420. SolidityType.prototype.nestedTypes = function (name) {
  1421. // return list of strings eg. "[]", "[3]", "[]", "[2]"
  1422. return name.match(/(\[[0-9]*\])/g);
  1423. };
  1424. /**
  1425. * Should be used to encode the value
  1426. *
  1427. * @method encode
  1428. * @param {Object} value
  1429. * @param {String} name
  1430. * @return {String} encoded value
  1431. */
  1432. SolidityType.prototype.encode = function (value, name) {
  1433. var self = this;
  1434. if (this.isDynamicArray(name)) {
  1435. return (function () {
  1436. var length = value.length; // in int
  1437. var nestedName = self.nestedName(name);
  1438. var result = [];
  1439. result.push(f.formatInputInt(length).encode());
  1440. value.forEach(function (v) {
  1441. result.push(self.encode(v, nestedName));
  1442. });
  1443. return result;
  1444. })();
  1445. } else if (this.isStaticArray(name)) {
  1446. return (function () {
  1447. var length = self.staticArrayLength(name); // in int
  1448. var nestedName = self.nestedName(name);
  1449. var result = [];
  1450. for (var i = 0; i < length; i++) {
  1451. result.push(self.encode(value[i], nestedName));
  1452. }
  1453. return result;
  1454. })();
  1455. }
  1456. return this._inputFormatter(value, name).encode();
  1457. };
  1458. /**
  1459. * Should be used to decode value from bytes
  1460. *
  1461. * @method decode
  1462. * @param {String} bytes
  1463. * @param {Number} offset in bytes
  1464. * @param {String} name type name
  1465. * @returns {Object} decoded value
  1466. */
  1467. SolidityType.prototype.decode = function (bytes, offset, name) {
  1468. var self = this;
  1469. if (this.isDynamicArray(name)) {
  1470. return (function () {
  1471. var arrayOffset = parseInt('0x' + bytes.substr(offset * 2, 64)); // in bytes
  1472. var length = parseInt('0x' + bytes.substr(arrayOffset * 2, 64)); // in int
  1473. var arrayStart = arrayOffset + 32; // array starts after length; // in bytes
  1474. var nestedName = self.nestedName(name);
  1475. var nestedStaticPartLength = self.staticPartLength(nestedName); // in bytes
  1476. var roundedNestedStaticPartLength = Math.floor((nestedStaticPartLength + 31) / 32) * 32;
  1477. var result = [];
  1478. for (var i = 0; i < length * roundedNestedStaticPartLength; i += roundedNestedStaticPartLength) {
  1479. result.push(self.decode(bytes, arrayStart + i, nestedName));
  1480. }
  1481. return result;
  1482. })();
  1483. } else if (this.isStaticArray(name)) {
  1484. return (function () {
  1485. var length = self.staticArrayLength(name); // in int
  1486. var arrayStart = offset; // in bytes
  1487. var nestedName = self.nestedName(name);
  1488. var nestedStaticPartLength = self.staticPartLength(nestedName); // in bytes
  1489. var roundedNestedStaticPartLength = Math.floor((nestedStaticPartLength + 31) / 32) * 32;
  1490. var result = [];
  1491. for (var i = 0; i < length * roundedNestedStaticPartLength; i += roundedNestedStaticPartLength) {
  1492. result.push(self.decode(bytes, arrayStart + i, nestedName));
  1493. }
  1494. return result;
  1495. })();
  1496. } else if (this.isDynamicType(name)) {
  1497. return (function () {
  1498. var dynamicOffset = parseInt('0x' + bytes.substr(offset * 2, 64)); // in bytes
  1499. var length = parseInt('0x' + bytes.substr(dynamicOffset * 2, 64)); // in bytes
  1500. var roundedLength = Math.floor((length + 31) / 32); // in int
  1501. return self._outputFormatter(new SolidityParam(bytes.substr(dynamicOffset * 2, ( 1 + roundedLength) * 64), 0));
  1502. })();
  1503. }
  1504. var length = this.staticPartLength(name);
  1505. return this._outputFormatter(new SolidityParam(bytes.substr(offset * 2, length * 2)));
  1506. };
  1507. module.exports = SolidityType;
  1508. },{"./formatters":9,"./param":11}],15:[function(require,module,exports){
  1509. var f = require('./formatters');
  1510. var SolidityType = require('./type');
  1511. /**
  1512. * SolidityTypeUInt is a prootype that represents uint type
  1513. * It matches:
  1514. * uint
  1515. * uint[]
  1516. * uint[4]
  1517. * uint[][]
  1518. * uint[3][]
  1519. * uint[][6][], ...
  1520. * uint32
  1521. * uint64[]
  1522. * uint8[4]
  1523. * uint256[][]
  1524. * uint[3][]
  1525. * uint64[][6][], ...
  1526. */
  1527. var SolidityTypeUInt = function () {
  1528. this._inputFormatter = f.formatInputInt;
  1529. this._outputFormatter = f.formatOutputUInt;
  1530. };
  1531. SolidityTypeUInt.prototype = new SolidityType({});
  1532. SolidityTypeUInt.prototype.constructor = SolidityTypeUInt;
  1533. SolidityTypeUInt.prototype.isType = function (name) {
  1534. return !!name.match(/^uint([0-9]*)?(\[([0-9]*)\])*$/);
  1535. };
  1536. SolidityTypeUInt.prototype.staticPartLength = function (name) {
  1537. return 32 * this.staticArrayLength(name);
  1538. };
  1539. module.exports = SolidityTypeUInt;
  1540. },{"./formatters":9,"./type":14}],16:[function(require,module,exports){
  1541. var f = require('./formatters');
  1542. var SolidityType = require('./type');
  1543. /**
  1544. * SolidityTypeUReal is a prootype that represents ureal type
  1545. * It matches:
  1546. * ureal
  1547. * ureal[]
  1548. * ureal[4]
  1549. * ureal[][]
  1550. * ureal[3][]
  1551. * ureal[][6][], ...
  1552. * ureal32
  1553. * ureal64[]
  1554. * ureal8[4]
  1555. * ureal256[][]
  1556. * ureal[3][]
  1557. * ureal64[][6][], ...
  1558. */
  1559. var SolidityTypeUReal = function () {
  1560. this._inputFormatter = f.formatInputReal;
  1561. this._outputFormatter = f.formatOutputUReal;
  1562. };
  1563. SolidityTypeUReal.prototype = new SolidityType({});
  1564. SolidityTypeUReal.prototype.constructor = SolidityTypeUReal;
  1565. SolidityTypeUReal.prototype.isType = function (name) {
  1566. return !!name.match(/^ureal([0-9]*)?(\[([0-9]*)\])*$/);
  1567. };
  1568. SolidityTypeUReal.prototype.staticPartLength = function (name) {
  1569. return 32 * this.staticArrayLength(name);
  1570. };
  1571. module.exports = SolidityTypeUReal;
  1572. },{"./formatters":9,"./type":14}],17:[function(require,module,exports){
  1573. 'use strict';
  1574. // go env doesn't have and need XMLHttpRequest
  1575. if (typeof XMLHttpRequest === 'undefined') {
  1576. exports.XMLHttpRequest = {};
  1577. } else {
  1578. exports.XMLHttpRequest = XMLHttpRequest; // jshint ignore:line
  1579. }
  1580. },{}],18:[function(require,module,exports){
  1581. /*
  1582. This file is part of web3.js.
  1583. web3.js is free software: you can redistribute it and/or modify
  1584. it under the terms of the GNU Lesser General Public License as published by
  1585. the Free Software Foundation, either version 3 of the License, or
  1586. (at your option) any later version.
  1587. web3.js is distributed in the hope that it will be useful,
  1588. but WITHOUT ANY WARRANTY; without even the implied warranty of
  1589. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  1590. GNU Lesser General Public License for more details.
  1591. You should have received a copy of the GNU Lesser General Public License
  1592. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  1593. */
  1594. /** @file config.js
  1595. * @authors:
  1596. * Marek Kotewicz <marek@ethdev.com>
  1597. * @date 2015
  1598. */
  1599. /**
  1600. * Utils
  1601. *
  1602. * @module utils
  1603. */
  1604. /**
  1605. * Utility functions
  1606. *
  1607. * @class [utils] config
  1608. * @constructor
  1609. */
  1610. /// required to define ETH_BIGNUMBER_ROUNDING_MODE
  1611. var BigNumber = require('bignumber.js');
  1612. var ETH_UNITS = [
  1613. 'wei',
  1614. 'kwei',
  1615. 'Mwei',
  1616. 'Gwei',
  1617. 'szabo',
  1618. 'finney',
  1619. 'femtoether',
  1620. 'picoether',
  1621. 'nanoether',
  1622. 'microether',
  1623. 'milliether',
  1624. 'nano',
  1625. 'micro',
  1626. 'milli',
  1627. 'ether',
  1628. 'grand',
  1629. 'Mether',
  1630. 'Gether',
  1631. 'Tether',
  1632. 'Pether',
  1633. 'Eether',
  1634. 'Zether',
  1635. 'Yether',
  1636. 'Nether',
  1637. 'Dether',
  1638. 'Vether',
  1639. 'Uether'
  1640. ];
  1641. module.exports = {
  1642. ETH_PADDING: 32,
  1643. ETH_SIGNATURE_LENGTH: 4,
  1644. ETH_UNITS: ETH_UNITS,
  1645. ETH_BIGNUMBER_ROUNDING_MODE: { ROUNDING_MODE: BigNumber.ROUND_DOWN },
  1646. ETH_POLLING_TIMEOUT: 1000/2,
  1647. defaultBlock: 'latest',
  1648. defaultAccount: undefined
  1649. };
  1650. },{"bignumber.js":"bignumber.js"}],19:[function(require,module,exports){
  1651. /*
  1652. This file is part of web3.js.
  1653. web3.js is free software: you can redistribute it and/or modify
  1654. it under the terms of the GNU Lesser General Public License as published by
  1655. the Free Software Foundation, either version 3 of the License, or
  1656. (at your option) any later version.
  1657. web3.js is distributed in the hope that it will be useful,
  1658. but WITHOUT ANY WARRANTY; without even the implied warranty of
  1659. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  1660. GNU Lesser General Public License for more details.
  1661. You should have received a copy of the GNU Lesser General Public License
  1662. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  1663. */
  1664. /**
  1665. * @file sha3.js
  1666. * @author Marek Kotewicz <marek@ethdev.com>
  1667. * @date 2015
  1668. */
  1669. var CryptoJS = require('crypto-js');
  1670. var sha3 = require('crypto-js/sha3');
  1671. module.exports = function (value, options) {
  1672. if (options && options.encoding === 'hex') {
  1673. if (value.length > 2 && value.substr(0, 2) === '0x') {
  1674. value = value.substr(2);
  1675. }
  1676. value = CryptoJS.enc.Hex.parse(value);
  1677. }
  1678. return sha3(value, {
  1679. outputLength: 256
  1680. }).toString();
  1681. };
  1682. },{"crypto-js":58,"crypto-js/sha3":79}],20:[function(require,module,exports){
  1683. /*
  1684. This file is part of web3.js.
  1685. web3.js is free software: you can redistribute it and/or modify
  1686. it under the terms of the GNU Lesser General Public License as published by
  1687. the Free Software Foundation, either version 3 of the License, or
  1688. (at your option) any later version.
  1689. web3.js is distributed in the hope that it will be useful,
  1690. but WITHOUT ANY WARRANTY; without even the implied warranty of
  1691. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  1692. GNU Lesser General Public License for more details.
  1693. You should have received a copy of the GNU Lesser General Public License
  1694. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  1695. */
  1696. /**
  1697. * @file utils.js
  1698. * @author Marek Kotewicz <marek@ethdev.com>
  1699. * @date 2015
  1700. */
  1701. /**
  1702. * Utils
  1703. *
  1704. * @module utils
  1705. */
  1706. /**
  1707. * Utility functions
  1708. *
  1709. * @class [utils] utils
  1710. * @constructor
  1711. */
  1712. var BigNumber = require('bignumber.js');
  1713. var sha3 = require('./sha3.js');
  1714. var utf8 = require('utf8');
  1715. var unitMap = {
  1716. 'noether': '0',
  1717. 'wei': '1',
  1718. 'kwei': '1000',
  1719. 'Kwei': '1000',
  1720. 'babbage': '1000',
  1721. 'femtoether': '1000',
  1722. 'mwei': '1000000',
  1723. 'Mwei': '1000000',
  1724. 'lovelace': '1000000',
  1725. 'picoether': '1000000',
  1726. 'gwei': '1000000000',
  1727. 'Gwei': '1000000000',
  1728. 'shannon': '1000000000',
  1729. 'nanoether': '1000000000',
  1730. 'nano': '1000000000',
  1731. 'szabo': '1000000000000',
  1732. 'microether': '1000000000000',
  1733. 'micro': '1000000000000',
  1734. 'finney': '1000000000000000',
  1735. 'milliether': '1000000000000000',
  1736. 'milli': '1000000000000000',
  1737. 'ether': '1000000000000000000',
  1738. 'kether': '1000000000000000000000',
  1739. 'grand': '1000000000000000000000',
  1740. 'mether': '1000000000000000000000000',
  1741. 'gether': '1000000000000000000000000000',
  1742. 'tether': '1000000000000000000000000000000'
  1743. };
  1744. /**
  1745. * Should be called to pad string to expected length
  1746. *
  1747. * @method padLeft
  1748. * @param {String} string to be padded
  1749. * @param {Number} characters that result string should have
  1750. * @param {String} sign, by default 0
  1751. * @returns {String} right aligned string
  1752. */
  1753. var padLeft = function (string, chars, sign) {
  1754. return new Array(chars - string.length + 1).join(sign ? sign : "0") + string;
  1755. };
  1756. /**
  1757. * Should be called to pad string to expected length
  1758. *
  1759. * @method padRight
  1760. * @param {String} string to be padded
  1761. * @param {Number} characters that result string should have
  1762. * @param {String} sign, by default 0
  1763. * @returns {String} right aligned string
  1764. */
  1765. var padRight = function (string, chars, sign) {
  1766. return string + (new Array(chars - string.length + 1).join(sign ? sign : "0"));
  1767. };
  1768. /**
  1769. * Should be called to get utf8 from its hex representation
  1770. *
  1771. * @method toUtf8
  1772. * @param {String} string in hex
  1773. * @returns {String} ascii string representation of hex value
  1774. */
  1775. var toUtf8 = function(hex) {
  1776. // Find termination
  1777. var str = "";
  1778. var i = 0, l = hex.length;
  1779. if (hex.substring(0, 2) === '0x') {
  1780. i = 2;
  1781. }
  1782. for (; i < l; i+=2) {
  1783. var code = parseInt(hex.substr(i, 2), 16);
  1784. if (code === 0)
  1785. break;
  1786. str += String.fromCharCode(code);
  1787. }
  1788. return utf8.decode(str);
  1789. };
  1790. /**
  1791. * Should be called to get ascii from its hex representation
  1792. *
  1793. * @method toAscii
  1794. * @param {String} string in hex
  1795. * @returns {String} ascii string representation of hex value
  1796. */
  1797. var toAscii = function(hex) {
  1798. // Find termination
  1799. var str = "";
  1800. var i = 0, l = hex.length;
  1801. if (hex.substring(0, 2) === '0x') {
  1802. i = 2;
  1803. }
  1804. for (; i < l; i+=2) {
  1805. var code = parseInt(hex.substr(i, 2), 16);
  1806. str += String.fromCharCode(code);
  1807. }
  1808. return str;
  1809. };
  1810. /**
  1811. * Should be called to get hex representation (prefixed by 0x) of utf8 string
  1812. *
  1813. * @method fromUtf8
  1814. * @param {String} string
  1815. * @param {Number} optional padding
  1816. * @returns {String} hex representation of input string
  1817. */
  1818. var fromUtf8 = function(str) {
  1819. str = utf8.encode(str);
  1820. var hex = "";
  1821. for(var i = 0; i < str.length; i++) {
  1822. var code = str.charCodeAt(i);
  1823. if (code === 0)
  1824. break;
  1825. var n = code.toString(16);
  1826. hex += n.length < 2 ? '0' + n : n;
  1827. }
  1828. return "0x" + hex;
  1829. };
  1830. /**
  1831. * Should be called to get hex representation (prefixed by 0x) of ascii string
  1832. *
  1833. * @method fromAscii
  1834. * @param {String} string
  1835. * @param {Number} optional padding
  1836. * @returns {String} hex representation of input string
  1837. */
  1838. var fromAscii = function(str) {
  1839. var hex = "";
  1840. for(var i = 0; i < str.length; i++) {
  1841. var code = str.charCodeAt(i);
  1842. var n = code.toString(16);
  1843. hex += n.length < 2 ? '0' + n : n;
  1844. }
  1845. return "0x" + hex;
  1846. };
  1847. /**
  1848. * Should be used to create full function/event name from json abi
  1849. *
  1850. * @method transformToFullName
  1851. * @param {Object} json-abi
  1852. * @return {String} full fnction/event name
  1853. */
  1854. var transformToFullName = function (json) {
  1855. if (json.name.indexOf('(') !== -1) {
  1856. return json.name;
  1857. }
  1858. var typeName = json.inputs.map(function(i){return i.type; }).join();
  1859. return json.name + '(' + typeName + ')';
  1860. };
  1861. /**
  1862. * Should be called to get display name of contract function
  1863. *
  1864. * @method extractDisplayName
  1865. * @param {String} name of function/event
  1866. * @returns {String} display name for function/event eg. multiply(uint256) -> multiply
  1867. */
  1868. var extractDisplayName = function (name) {
  1869. var length = name.indexOf('(');
  1870. return length !== -1 ? name.substr(0, length) : name;
  1871. };
  1872. /// @returns overloaded part of function/event name
  1873. var extractTypeName = function (name) {
  1874. /// TODO: make it invulnerable
  1875. var length = name.indexOf('(');
  1876. return length !== -1 ? name.substr(length + 1, name.length - 1 - (length + 1)).replace(' ', '') : "";
  1877. };
  1878. /**
  1879. * Converts value to its decimal representation in string
  1880. *
  1881. * @method toDecimal
  1882. * @param {String|Number|BigNumber}
  1883. * @return {String}
  1884. */
  1885. var toDecimal = function (value) {
  1886. return toBigNumber(value).toNumber();
  1887. };
  1888. /**
  1889. * Converts value to its hex representation
  1890. *
  1891. * @method fromDecimal
  1892. * @param {String|Number|BigNumber}
  1893. * @return {String}
  1894. */
  1895. var fromDecimal = function (value) {
  1896. var number = toBigNumber(value);
  1897. var result = number.toString(16);
  1898. return number.lessThan(0) ? '-0x' + result.substr(1) : '0x' + result;
  1899. };
  1900. /**
  1901. * Auto converts any given value into its hex representation.
  1902. *
  1903. * And even stringifys objects before.
  1904. *
  1905. * @method toHex
  1906. * @param {String|Number|BigNumber|Object}
  1907. * @return {String}
  1908. */
  1909. var toHex = function (val) {
  1910. /*jshint maxcomplexity: 8 */
  1911. if (isBoolean(val))
  1912. return fromDecimal(+val);
  1913. if (isBigNumber(val))
  1914. return fromDecimal(val);
  1915. if (isObject(val))
  1916. return fromUtf8(JSON.stringify(val));
  1917. // if its a negative number, pass it through fromDecimal
  1918. if (isString(val)) {
  1919. if (val.indexOf('-0x') === 0)
  1920. return fromDecimal(val);
  1921. else if(val.indexOf('0x') === 0)
  1922. return val;
  1923. else if (!isFinite(val))
  1924. return fromAscii(val);
  1925. }
  1926. return fromDecimal(val);
  1927. };
  1928. /**
  1929. * Returns value of unit in Wei
  1930. *
  1931. * @method getValueOfUnit
  1932. * @param {String} unit the unit to convert to, default ether
  1933. * @returns {BigNumber} value of the unit (in Wei)
  1934. * @throws error if the unit is not correct:w
  1935. */
  1936. var getValueOfUnit = function (unit) {
  1937. unit = unit ? unit.toLowerCase() : 'ether';
  1938. var unitValue = unitMap[unit];
  1939. if (unitValue === undefined) {
  1940. throw new Error('This unit doesn\'t exists, please use the one of the following units' + JSON.stringify(unitMap, null, 2));
  1941. }
  1942. return new BigNumber(unitValue, 10);
  1943. };
  1944. /**
  1945. * Takes a number of wei and converts it to any other ether unit.
  1946. *
  1947. * Possible units are:
  1948. * SI Short SI Full Effigy Other
  1949. * - kwei femtoether babbage
  1950. * - mwei picoether lovelace
  1951. * - gwei nanoether shannon nano
  1952. * - -- microether szabo micro
  1953. * - -- milliether finney milli
  1954. * - ether -- --
  1955. * - kether -- grand
  1956. * - mether
  1957. * - gether
  1958. * - tether
  1959. *
  1960. * @method fromWei
  1961. * @param {Number|String} number can be a number, number string or a HEX of a decimal
  1962. * @param {String} unit the unit to convert to, default ether
  1963. * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number
  1964. */
  1965. var fromWei = function(number, unit) {
  1966. var returnValue = toBigNumber(number).dividedBy(getValueOfUnit(unit));
  1967. return isBigNumber(number) ? returnValue : returnValue.toString(10);
  1968. };
  1969. /**
  1970. * Takes a number of a unit and converts it to wei.
  1971. *
  1972. * Possible units are:
  1973. * SI Short SI Full Effigy Other
  1974. * - kwei femtoether babbage
  1975. * - mwei picoether lovelace
  1976. * - gwei nanoether shannon nano
  1977. * - -- microether szabo micro
  1978. * - -- microether szabo micro
  1979. * - -- milliether finney milli
  1980. * - ether -- --
  1981. * - kether -- grand
  1982. * - mether
  1983. * - gether
  1984. * - tether
  1985. *
  1986. * @method toWei
  1987. * @param {Number|String|BigNumber} number can be a number, number string or a HEX of a decimal
  1988. * @param {String} unit the unit to convert from, default ether
  1989. * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number
  1990. */
  1991. var toWei = function(number, unit) {
  1992. var returnValue = toBigNumber(number).times(getValueOfUnit(unit));
  1993. return isBigNumber(number) ? returnValue : returnValue.toString(10);
  1994. };
  1995. /**
  1996. * Takes an input and transforms it into an bignumber
  1997. *
  1998. * @method toBigNumber
  1999. * @param {Number|String|BigNumber} a number, string, HEX string or BigNumber
  2000. * @return {BigNumber} BigNumber
  2001. */
  2002. var toBigNumber = function(number) {
  2003. /*jshint maxcomplexity:5 */
  2004. number = number || 0;
  2005. if (isBigNumber(number))
  2006. return number;
  2007. if (isString(number) && (number.indexOf('0x') === 0 || number.indexOf('-0x') === 0)) {
  2008. return new BigNumber(number.replace('0x',''), 16);
  2009. }
  2010. return new BigNumber(number.toString(10), 10);
  2011. };
  2012. /**
  2013. * Takes and input transforms it into bignumber and if it is negative value, into two's complement
  2014. *
  2015. * @method toTwosComplement
  2016. * @param {Number|String|BigNumber}
  2017. * @return {BigNumber}
  2018. */
  2019. var toTwosComplement = function (number) {
  2020. var bigNumber = toBigNumber(number);
  2021. if (bigNumber.lessThan(0)) {
  2022. return new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).plus(bigNumber).plus(1);
  2023. }
  2024. return bigNumber;
  2025. };
  2026. /**
  2027. * Checks if the given string is strictly an address
  2028. *
  2029. * @method isStrictAddress
  2030. * @param {String} address the given HEX adress
  2031. * @return {Boolean}
  2032. */
  2033. var isStrictAddress = function (address) {
  2034. return /^0x[0-9a-f]{40}$/i.test(address);
  2035. };
  2036. /**
  2037. * Checks if the given string is an address
  2038. *
  2039. * @method isAddress
  2040. * @param {String} address the given HEX adress
  2041. * @return {Boolean}
  2042. */
  2043. var isAddress = function (address) {
  2044. if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) {
  2045. // check if it has the basic requirements of an address
  2046. return false;
  2047. } else if (/^(0x)?[0-9a-f]{40}$/.test(address) || /^(0x)?[0-9A-F]{40}$/.test(address)) {
  2048. // If it's all small caps or all all caps, return true
  2049. return true;
  2050. } else {
  2051. // Otherwise check each case
  2052. return isChecksumAddress(address);
  2053. }
  2054. };
  2055. /**
  2056. * Checks if the given string is a checksummed address
  2057. *
  2058. * @method isChecksumAddress
  2059. * @param {String} address the given HEX adress
  2060. * @return {Boolean}
  2061. */
  2062. var isChecksumAddress = function (address) {
  2063. // Check each case
  2064. address = address.replace('0x','');
  2065. var addressHash = sha3(address.toLowerCase());
  2066. for (var i = 0; i < 40; i++ ) {
  2067. // the nth letter should be uppercase if the nth digit of casemap is 1
  2068. if ((parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])) {
  2069. return false;
  2070. }
  2071. }
  2072. return true;
  2073. };
  2074. /**
  2075. * Makes a checksum address
  2076. *
  2077. * @method toChecksumAddress
  2078. * @param {String} address the given HEX adress
  2079. * @return {String}
  2080. */
  2081. var toChecksumAddress = function (address) {
  2082. if (typeof address === 'undefined') return '';
  2083. address = address.toLowerCase().replace('0x','');
  2084. var addressHash = sha3(address);
  2085. var checksumAddress = '0x';
  2086. for (var i = 0; i < address.length; i++ ) {
  2087. // If ith character is 9 to f then make it uppercase
  2088. if (parseInt(addressHash[i], 16) > 7) {
  2089. checksumAddress += address[i].toUpperCase();
  2090. } else {
  2091. checksumAddress += address[i];
  2092. }
  2093. }
  2094. return checksumAddress;
  2095. };
  2096. /**
  2097. * Transforms given string to valid 20 bytes-length addres with 0x prefix
  2098. *
  2099. * @method toAddress
  2100. * @param {String} address
  2101. * @return {String} formatted address
  2102. */
  2103. var toAddress = function (address) {
  2104. if (isStrictAddress(address)) {
  2105. return address;
  2106. }
  2107. if (/^[0-9a-f]{40}$/.test(address)) {
  2108. return '0x' + address;
  2109. }
  2110. return '0x' + padLeft(toHex(address).substr(2), 40);
  2111. };
  2112. /**
  2113. * Returns true if object is BigNumber, otherwise false
  2114. *
  2115. * @method isBigNumber
  2116. * @param {Object}
  2117. * @return {Boolean}
  2118. */
  2119. var isBigNumber = function (object) {
  2120. return object instanceof BigNumber ||
  2121. (object && object.constructor && object.constructor.name === 'BigNumber');
  2122. };
  2123. /**
  2124. * Returns true if object is string, otherwise false
  2125. *
  2126. * @method isString
  2127. * @param {Object}
  2128. * @return {Boolean}
  2129. */
  2130. var isString = function (object) {
  2131. return typeof object === 'string' ||
  2132. (object && object.constructor && object.constructor.name === 'String');
  2133. };
  2134. /**
  2135. * Returns true if object is function, otherwise false
  2136. *
  2137. * @method isFunction
  2138. * @param {Object}
  2139. * @return {Boolean}
  2140. */
  2141. var isFunction = function (object) {
  2142. return typeof object === 'function';
  2143. };
  2144. /**
  2145. * Returns true if object is Objet, otherwise false
  2146. *
  2147. * @method isObject
  2148. * @param {Object}
  2149. * @return {Boolean}
  2150. */
  2151. var isObject = function (object) {
  2152. return typeof object === 'object';
  2153. };
  2154. /**
  2155. * Returns true if object is boolean, otherwise false
  2156. *
  2157. * @method isBoolean
  2158. * @param {Object}
  2159. * @return {Boolean}
  2160. */
  2161. var isBoolean = function (object) {
  2162. return typeof object === 'boolean';
  2163. };
  2164. /**
  2165. * Returns true if object is array, otherwise false
  2166. *
  2167. * @method isArray
  2168. * @param {Object}
  2169. * @return {Boolean}
  2170. */
  2171. var isArray = function (object) {
  2172. return object instanceof Array;
  2173. };
  2174. /**
  2175. * Returns true if given string is valid json object
  2176. *
  2177. * @method isJson
  2178. * @param {String}
  2179. * @return {Boolean}
  2180. */
  2181. var isJson = function (str) {
  2182. try {
  2183. return !!JSON.parse(str);
  2184. } catch (e) {
  2185. return false;
  2186. }
  2187. };
  2188. module.exports = {
  2189. padLeft: padLeft,
  2190. padRight: padRight,
  2191. toHex: toHex,
  2192. toDecimal: toDecimal,
  2193. fromDecimal: fromDecimal,
  2194. toUtf8: toUtf8,
  2195. toAscii: toAscii,
  2196. fromUtf8: fromUtf8,
  2197. fromAscii: fromAscii,
  2198. transformToFullName: transformToFullName,
  2199. extractDisplayName: extractDisplayName,
  2200. extractTypeName: extractTypeName,
  2201. toWei: toWei,
  2202. fromWei: fromWei,
  2203. toBigNumber: toBigNumber,
  2204. toTwosComplement: toTwosComplement,
  2205. toAddress: toAddress,
  2206. isBigNumber: isBigNumber,
  2207. isStrictAddress: isStrictAddress,
  2208. isAddress: isAddress,
  2209. isChecksumAddress: isChecksumAddress,
  2210. toChecksumAddress: toChecksumAddress,
  2211. isFunction: isFunction,
  2212. isString: isString,
  2213. isObject: isObject,
  2214. isBoolean: isBoolean,
  2215. isArray: isArray,
  2216. isJson: isJson
  2217. };
  2218. },{"./sha3.js":19,"bignumber.js":"bignumber.js","utf8":84}],21:[function(require,module,exports){
  2219. module.exports={
  2220. "version": "0.15.3"
  2221. }
  2222. },{}],22:[function(require,module,exports){
  2223. /*
  2224. This file is part of web3.js.
  2225. web3.js is free software: you can redistribute it and/or modify
  2226. it under the terms of the GNU Lesser General Public License as published by
  2227. the Free Software Foundation, either version 3 of the License, or
  2228. (at your option) any later version.
  2229. web3.js is distributed in the hope that it will be useful,
  2230. but WITHOUT ANY WARRANTY; without even the implied warranty of
  2231. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  2232. GNU Lesser General Public License for more details.
  2233. You should have received a copy of the GNU Lesser General Public License
  2234. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  2235. */
  2236. /**
  2237. * @file web3.js
  2238. * @authors:
  2239. * Jeffrey Wilcke <jeff@ethdev.com>
  2240. * Marek Kotewicz <marek@ethdev.com>
  2241. * Marian Oancea <marian@ethdev.com>
  2242. * Fabian Vogelsteller <fabian@ethdev.com>
  2243. * Gav Wood <g@ethdev.com>
  2244. * @date 2014
  2245. */
  2246. var RequestManager = require('./web3/requestmanager');
  2247. var Iban = require('./web3/iban');
  2248. var Eth = require('./web3/methods/eth');
  2249. var DB = require('./web3/methods/db');
  2250. var Shh = require('./web3/methods/shh');
  2251. var Net = require('./web3/methods/net');
  2252. var Personal = require('./web3/methods/personal');
  2253. var Settings = require('./web3/settings');
  2254. var version = require('./version.json');
  2255. var utils = require('./utils/utils');
  2256. var sha3 = require('./utils/sha3');
  2257. var extend = require('./web3/extend');
  2258. var Batch = require('./web3/batch');
  2259. var Property = require('./web3/property');
  2260. var HttpProvider = require('./web3/httpprovider');
  2261. var IpcProvider = require('./web3/ipcprovider');
  2262. function Web3 (provider) {
  2263. this._requestManager = new RequestManager(provider);
  2264. this.currentProvider = provider;
  2265. this.eth = new Eth(this);
  2266. this.db = new DB(this);
  2267. this.shh = new Shh(this);
  2268. this.net = new Net(this);
  2269. this.personal = new Personal(this);
  2270. this.settings = new Settings();
  2271. this.version = {
  2272. api: version.version
  2273. };
  2274. this.providers = {
  2275. HttpProvider: HttpProvider,
  2276. IpcProvider: IpcProvider
  2277. };
  2278. this._extend = extend(this);
  2279. this._extend({
  2280. properties: properties()
  2281. });
  2282. }
  2283. // expose providers on the class
  2284. Web3.providers = {
  2285. HttpProvider: HttpProvider,
  2286. IpcProvider: IpcProvider
  2287. };
  2288. Web3.prototype.setProvider = function (provider) {
  2289. this._requestManager.setProvider(provider);
  2290. this.currentProvider = provider;
  2291. };
  2292. Web3.prototype.reset = function (keepIsSyncing) {
  2293. this._requestManager.reset(keepIsSyncing);
  2294. this.settings = new Settings();
  2295. };
  2296. Web3.prototype.toHex = utils.toHex;
  2297. Web3.prototype.toAscii = utils.toAscii;
  2298. Web3.prototype.toUtf8 = utils.toUtf8;
  2299. Web3.prototype.fromAscii = utils.fromAscii;
  2300. Web3.prototype.fromUtf8 = utils.fromUtf8;
  2301. Web3.prototype.toDecimal = utils.toDecimal;
  2302. Web3.prototype.fromDecimal = utils.fromDecimal;
  2303. Web3.prototype.toBigNumber = utils.toBigNumber;
  2304. Web3.prototype.toWei = utils.toWei;
  2305. Web3.prototype.fromWei = utils.fromWei;
  2306. Web3.prototype.isAddress = utils.isAddress;
  2307. Web3.prototype.isChecksumAddress = utils.isChecksumAddress;
  2308. Web3.prototype.toChecksumAddress = utils.toChecksumAddress;
  2309. Web3.prototype.isIBAN = utils.isIBAN;
  2310. Web3.prototype.sha3 = function(string, options) {
  2311. return '0x' + sha3(string, options);
  2312. };
  2313. /**
  2314. * Transforms direct icap to address
  2315. */
  2316. Web3.prototype.fromICAP = function (icap) {
  2317. var iban = new Iban(icap);
  2318. return iban.address();
  2319. };
  2320. var properties = function () {
  2321. return [
  2322. new Property({
  2323. name: 'version.node',
  2324. getter: 'web3_clientVersion'
  2325. }),
  2326. new Property({
  2327. name: 'version.network',
  2328. getter: 'net_version',
  2329. inputFormatter: utils.toDecimal
  2330. }),
  2331. new Property({
  2332. name: 'version.ethereum',
  2333. getter: 'eth_protocolVersion',
  2334. inputFormatter: utils.toDecimal
  2335. }),
  2336. new Property({
  2337. name: 'version.whisper',
  2338. getter: 'shh_version',
  2339. inputFormatter: utils.toDecimal
  2340. })
  2341. ];
  2342. };
  2343. Web3.prototype.isConnected = function(){
  2344. return (this.currentProvider && this.currentProvider.isConnected());
  2345. };
  2346. Web3.prototype.createBatch = function () {
  2347. return new Batch(this);
  2348. };
  2349. module.exports = Web3;
  2350. },{"./utils/sha3":19,"./utils/utils":20,"./version.json":21,"./web3/batch":24,"./web3/extend":28,"./web3/httpprovider":32,"./web3/iban":33,"./web3/ipcprovider":34,"./web3/methods/db":37,"./web3/methods/eth":38,"./web3/methods/net":39,"./web3/methods/personal":40,"./web3/methods/shh":41,"./web3/property":44,"./web3/requestmanager":45,"./web3/settings":46}],23:[function(require,module,exports){
  2351. /*
  2352. This file is part of web3.js.
  2353. web3.js is free software: you can redistribute it and/or modify
  2354. it under the terms of the GNU Lesser General Public License as published by
  2355. the Free Software Foundation, either version 3 of the License, or
  2356. (at your option) any later version.
  2357. web3.js is distributed in the hope that it will be useful,
  2358. but WITHOUT ANY WARRANTY; without even the implied warranty of
  2359. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  2360. GNU Lesser General Public License for more details.
  2361. You should have received a copy of the GNU Lesser General Public License
  2362. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  2363. */
  2364. /**
  2365. * @file allevents.js
  2366. * @author Marek Kotewicz <marek@ethdev.com>
  2367. * @date 2014
  2368. */
  2369. var sha3 = require('../utils/sha3');
  2370. var SolidityEvent = require('./event');
  2371. var formatters = require('./formatters');
  2372. var utils = require('../utils/utils');
  2373. var Filter = require('./filter');
  2374. var watches = require('./methods/watches');
  2375. var AllSolidityEvents = function (requestManager, json, address) {
  2376. this._requestManager = requestManager;
  2377. this._json = json;
  2378. this._address = address;
  2379. };
  2380. AllSolidityEvents.prototype.encode = function (options) {
  2381. options = options || {};
  2382. var result = {};
  2383. ['fromBlock', 'toBlock'].filter(function (f) {
  2384. return options[f] !== undefined;
  2385. }).forEach(function (f) {
  2386. result[f] = formatters.inputBlockNumberFormatter(options[f]);
  2387. });
  2388. result.address = this._address;
  2389. return result;
  2390. };
  2391. AllSolidityEvents.prototype.decode = function (data) {
  2392. data.data = data.data || '';
  2393. data.topics = data.topics || [];
  2394. var eventTopic = data.topics[0].slice(2);
  2395. var match = this._json.filter(function (j) {
  2396. return eventTopic === sha3(utils.transformToFullName(j));
  2397. })[0];
  2398. if (!match) { // cannot find matching event?
  2399. console.warn('cannot find event for log');
  2400. return data;
  2401. }
  2402. var event = new SolidityEvent(this._requestManager, match, this._address);
  2403. return event.decode(data);
  2404. };
  2405. AllSolidityEvents.prototype.execute = function (options, callback) {
  2406. if (utils.isFunction(arguments[arguments.length - 1])) {
  2407. callback = arguments[arguments.length - 1];
  2408. if(arguments.length === 1)
  2409. options = null;
  2410. }
  2411. var o = this.encode(options);
  2412. var formatter = this.decode.bind(this);
  2413. return new Filter(this._requestManager, o, watches.eth(), formatter, callback);
  2414. };
  2415. AllSolidityEvents.prototype.attachToContract = function (contract) {
  2416. var execute = this.execute.bind(this);
  2417. contract.allEvents = execute;
  2418. };
  2419. module.exports = AllSolidityEvents;
  2420. },{"../utils/sha3":19,"../utils/utils":20,"./event":27,"./filter":29,"./formatters":30,"./methods/watches":42}],24:[function(require,module,exports){
  2421. /*
  2422. This file is part of web3.js.
  2423. web3.js is free software: you can redistribute it and/or modify
  2424. it under the terms of the GNU Lesser General Public License as published by
  2425. the Free Software Foundation, either version 3 of the License, or
  2426. (at your option) any later version.
  2427. web3.js is distributed in the hope that it will be useful,
  2428. but WITHOUT ANY WARRANTY; without even the implied warranty of
  2429. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  2430. GNU Lesser General Public License for more details.
  2431. You should have received a copy of the GNU Lesser General Public License
  2432. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  2433. */
  2434. /**
  2435. * @file batch.js
  2436. * @author Marek Kotewicz <marek@ethdev.com>
  2437. * @date 2015
  2438. */
  2439. var Jsonrpc = require('./jsonrpc');
  2440. var errors = require('./errors');
  2441. var Batch = function (web3) {
  2442. this.requestManager = web3._requestManager;
  2443. this.requests = [];
  2444. };
  2445. /**
  2446. * Should be called to add create new request to batch request
  2447. *
  2448. * @method add
  2449. * @param {Object} jsonrpc requet object
  2450. */
  2451. Batch.prototype.add = function (request) {
  2452. this.requests.push(request);
  2453. };
  2454. /**
  2455. * Should be called to execute batch request
  2456. *
  2457. * @method execute
  2458. */
  2459. Batch.prototype.execute = function () {
  2460. var requests = this.requests;
  2461. this.requestManager.sendBatch(requests, function (err, results) {
  2462. results = results || [];
  2463. requests.map(function (request, index) {
  2464. return results[index] || {};
  2465. }).forEach(function (result, index) {
  2466. if (requests[index].callback) {
  2467. if (!Jsonrpc.getInstance().isValidResponse(result)) {
  2468. return requests[index].callback(errors.InvalidResponse(result));
  2469. }
  2470. requests[index].callback(null, (requests[index].format ? requests[index].format(result.result) : result.result));
  2471. }
  2472. });
  2473. });
  2474. };
  2475. module.exports = Batch;
  2476. },{"./errors":26,"./jsonrpc":35}],25:[function(require,module,exports){
  2477. /*
  2478. This file is part of web3.js.
  2479. web3.js is free software: you can redistribute it and/or modify
  2480. it under the terms of the GNU Lesser General Public License as published by
  2481. the Free Software Foundation, either version 3 of the License, or
  2482. (at your option) any later version.
  2483. web3.js is distributed in the hope that it will be useful,
  2484. but WITHOUT ANY WARRANTY; without even the implied warranty of
  2485. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  2486. GNU Lesser General Public License for more details.
  2487. You should have received a copy of the GNU Lesser General Public License
  2488. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  2489. */
  2490. /**
  2491. * @file contract.js
  2492. * @author Marek Kotewicz <marek@ethdev.com>
  2493. * @date 2014
  2494. */
  2495. var utils = require('../utils/utils');
  2496. var coder = require('../solidity/coder');
  2497. var SolidityEvent = require('./event');
  2498. var SolidityFunction = require('./function');
  2499. var AllEvents = require('./allevents');
  2500. /**
  2501. * Should be called to encode constructor params
  2502. *
  2503. * @method encodeConstructorParams
  2504. * @param {Array} abi
  2505. * @param {Array} constructor params
  2506. */
  2507. var encodeConstructorParams = function (abi, params) {
  2508. return abi.filter(function (json) {
  2509. return json.type === 'constructor' && json.inputs.length === params.length;
  2510. }).map(function (json) {
  2511. return json.inputs.map(function (input) {
  2512. return input.type;
  2513. });
  2514. }).map(function (types) {
  2515. return coder.encodeParams(types, params);
  2516. })[0] || '';
  2517. };
  2518. /**
  2519. * Should be called to add functions to contract object
  2520. *
  2521. * @method addFunctionsToContract
  2522. * @param {Contract} contract
  2523. * @param {Array} abi
  2524. */
  2525. var addFunctionsToContract = function (contract) {
  2526. contract.abi.filter(function (json) {
  2527. return json.type === 'function';
  2528. }).map(function (json) {
  2529. return new SolidityFunction(contract._eth, json, contract.address);
  2530. }).forEach(function (f) {
  2531. f.attachToContract(contract);
  2532. });
  2533. };
  2534. /**
  2535. * Should be called to add events to contract object
  2536. *
  2537. * @method addEventsToContract
  2538. * @param {Contract} contract
  2539. * @param {Array} abi
  2540. */
  2541. var addEventsToContract = function (contract) {
  2542. var events = contract.abi.filter(function (json) {
  2543. return json.type === 'event';
  2544. });
  2545. var All = new AllEvents(contract._eth._requestManager, events, contract.address);
  2546. All.attachToContract(contract);
  2547. events.map(function (json) {
  2548. return new SolidityEvent(contract._eth._requestManager, json, contract.address);
  2549. }).forEach(function (e) {
  2550. e.attachToContract(contract);
  2551. });
  2552. };
  2553. /**
  2554. * Should be called to check if the contract gets properly deployed on the blockchain.
  2555. *
  2556. * @method checkForContractAddress
  2557. * @param {Object} contract
  2558. * @param {Function} callback
  2559. * @returns {Undefined}
  2560. */
  2561. var checkForContractAddress = function(contract, callback){
  2562. var count = 0,
  2563. callbackFired = false;
  2564. // wait for receipt
  2565. var filter = contract._eth.filter('latest', function(e){
  2566. if (!e && !callbackFired) {
  2567. count++;
  2568. // stop watching after 50 blocks (timeout)
  2569. if (count > 50) {
  2570. filter.stopWatching();
  2571. callbackFired = true;
  2572. if (callback)
  2573. callback(new Error('Contract transaction couldn\'t be found after 50 blocks'));
  2574. else
  2575. throw new Error('Contract transaction couldn\'t be found after 50 blocks');
  2576. } else {
  2577. contract._eth.getTransactionReceipt(contract.transactionHash, function(e, receipt){
  2578. if(receipt && !callbackFired) {
  2579. contract._eth.getCode(receipt.contractAddress, function(e, code){
  2580. /*jshint maxcomplexity: 6 */
  2581. if(callbackFired || !code)
  2582. return;
  2583. filter.stopWatching();
  2584. callbackFired = true;
  2585. if(code.length > 2) {
  2586. // console.log('Contract code deployed!');
  2587. contract.address = receipt.contractAddress;
  2588. // attach events and methods again after we have
  2589. addFunctionsToContract(contract);
  2590. addEventsToContract(contract);
  2591. // call callback for the second time
  2592. if(callback)
  2593. callback(null, contract);
  2594. } else {
  2595. if(callback)
  2596. callback(new Error('The contract code couldn\'t be stored, please check your gas amount.'));
  2597. else
  2598. throw new Error('The contract code couldn\'t be stored, please check your gas amount.');
  2599. }
  2600. });
  2601. }
  2602. });
  2603. }
  2604. }
  2605. });
  2606. };
  2607. /**
  2608. * Should be called to create new ContractFactory instance
  2609. *
  2610. * @method ContractFactory
  2611. * @param {Array} abi
  2612. */
  2613. var ContractFactory = function (eth, abi) {
  2614. this.eth = eth;
  2615. this.abi = abi;
  2616. /**
  2617. * Should be called to create new contract on a blockchain
  2618. *
  2619. * @method new
  2620. * @param {Any} contract constructor param1 (optional)
  2621. * @param {Any} contract constructor param2 (optional)
  2622. * @param {Object} contract transaction object (required)
  2623. * @param {Function} callback
  2624. * @returns {Contract} returns contract instance
  2625. */
  2626. this.new = function () {
  2627. var contract = new Contract(this.eth, this.abi);
  2628. // parse arguments
  2629. var options = {}; // required!
  2630. var callback;
  2631. var args = Array.prototype.slice.call(arguments);
  2632. if (utils.isFunction(args[args.length - 1])) {
  2633. callback = args.pop();
  2634. }
  2635. var last = args[args.length - 1];
  2636. if (utils.isObject(last) && !utils.isArray(last)) {
  2637. options = args.pop();
  2638. }
  2639. var bytes = encodeConstructorParams(this.abi, args);
  2640. options.data += bytes;
  2641. if (callback) {
  2642. // wait for the contract address adn check if the code was deployed
  2643. this.eth.sendTransaction(options, function (err, hash) {
  2644. if (err) {
  2645. callback(err);
  2646. } else {
  2647. // add the transaction hash
  2648. contract.transactionHash = hash;
  2649. // call callback for the first time
  2650. callback(null, contract);
  2651. checkForContractAddress(contract, callback);
  2652. }
  2653. });
  2654. } else {
  2655. var hash = this.eth.sendTransaction(options);
  2656. // add the transaction hash
  2657. contract.transactionHash = hash;
  2658. checkForContractAddress(contract);
  2659. }
  2660. return contract;
  2661. };
  2662. this.new.getData = this.getData.bind(this);
  2663. };
  2664. /**
  2665. * Should be called to create new ContractFactory
  2666. *
  2667. * @method contract
  2668. * @param {Array} abi
  2669. * @returns {ContractFactory} new contract factory
  2670. */
  2671. //var contract = function (abi) {
  2672. //return new ContractFactory(abi);
  2673. //};
  2674. /**
  2675. * Should be called to get access to existing contract on a blockchain
  2676. *
  2677. * @method at
  2678. * @param {Address} contract address (required)
  2679. * @param {Function} callback {optional)
  2680. * @returns {Contract} returns contract if no callback was passed,
  2681. * otherwise calls callback function (err, contract)
  2682. */
  2683. ContractFactory.prototype.at = function (address, callback) {
  2684. var contract = new Contract(this.eth, this.abi, address);
  2685. // this functions are not part of prototype,
  2686. // because we dont want to spoil the interface
  2687. addFunctionsToContract(contract);
  2688. addEventsToContract(contract);
  2689. if (callback) {
  2690. callback(null, contract);
  2691. }
  2692. return contract;
  2693. };
  2694. /**
  2695. * Gets the data, which is data to deploy plus constructor params
  2696. *
  2697. * @method getData
  2698. */
  2699. ContractFactory.prototype.getData = function () {
  2700. var options = {}; // required!
  2701. var args = Array.prototype.slice.call(arguments);
  2702. var last = args[args.length - 1];
  2703. if (utils.isObject(last) && !utils.isArray(last)) {
  2704. options = args.pop();
  2705. }
  2706. var bytes = encodeConstructorParams(this.abi, args);
  2707. options.data += bytes;
  2708. return options.data;
  2709. };
  2710. /**
  2711. * Should be called to create new contract instance
  2712. *
  2713. * @method Contract
  2714. * @param {Array} abi
  2715. * @param {Address} contract address
  2716. */
  2717. var Contract = function (eth, abi, address) {
  2718. this._eth = eth;
  2719. this.transactionHash = null;
  2720. this.address = address;
  2721. this.abi = abi;
  2722. };
  2723. module.exports = ContractFactory;
  2724. },{"../solidity/coder":7,"../utils/utils":20,"./allevents":23,"./event":27,"./function":31}],26:[function(require,module,exports){
  2725. /*
  2726. This file is part of web3.js.
  2727. web3.js is free software: you can redistribute it and/or modify
  2728. it under the terms of the GNU Lesser General Public License as published by
  2729. the Free Software Foundation, either version 3 of the License, or
  2730. (at your option) any later version.
  2731. web3.js is distributed in the hope that it will be useful,
  2732. but WITHOUT ANY WARRANTY; without even the implied warranty of
  2733. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  2734. GNU Lesser General Public License for more details.
  2735. You should have received a copy of the GNU Lesser General Public License
  2736. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  2737. */
  2738. /**
  2739. * @file errors.js
  2740. * @author Marek Kotewicz <marek@ethdev.com>
  2741. * @date 2015
  2742. */
  2743. module.exports = {
  2744. InvalidNumberOfParams: function () {
  2745. return new Error('Invalid number of input parameters');
  2746. },
  2747. InvalidConnection: function (host){
  2748. return new Error('CONNECTION ERROR: Couldn\'t connect to node '+ host +'.');
  2749. },
  2750. InvalidProvider: function () {
  2751. return new Error('Provider not set or invalid');
  2752. },
  2753. InvalidResponse: function (result){
  2754. var message = !!result && !!result.error && !!result.error.message ? result.error.message : 'Invalid JSON RPC response: ' + JSON.stringify(result);
  2755. return new Error(message);
  2756. }
  2757. };
  2758. },{}],27:[function(require,module,exports){
  2759. /*
  2760. This file is part of web3.js.
  2761. web3.js is free software: you can redistribute it and/or modify
  2762. it under the terms of the GNU Lesser General Public License as published by
  2763. the Free Software Foundation, either version 3 of the License, or
  2764. (at your option) any later version.
  2765. web3.js is distributed in the hope that it will be useful,
  2766. but WITHOUT ANY WARRANTY; without even the implied warranty of
  2767. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  2768. GNU Lesser General Public License for more details.
  2769. You should have received a copy of the GNU Lesser General Public License
  2770. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  2771. */
  2772. /**
  2773. * @file event.js
  2774. * @author Marek Kotewicz <marek@ethdev.com>
  2775. * @date 2014
  2776. */
  2777. var utils = require('../utils/utils');
  2778. var coder = require('../solidity/coder');
  2779. var formatters = require('./formatters');
  2780. var sha3 = require('../utils/sha3');
  2781. var Filter = require('./filter');
  2782. var watches = require('./methods/watches');
  2783. /**
  2784. * This prototype should be used to create event filters
  2785. */
  2786. var SolidityEvent = function (requestManager, json, address) {
  2787. this._requestManager = requestManager;
  2788. this._params = json.inputs;
  2789. this._name = utils.transformToFullName(json);
  2790. this._address = address;
  2791. this._anonymous = json.anonymous;
  2792. };
  2793. /**
  2794. * Should be used to get filtered param types
  2795. *
  2796. * @method types
  2797. * @param {Bool} decide if returned typed should be indexed
  2798. * @return {Array} array of types
  2799. */
  2800. SolidityEvent.prototype.types = function (indexed) {
  2801. return this._params.filter(function (i) {
  2802. return i.indexed === indexed;
  2803. }).map(function (i) {
  2804. return i.type;
  2805. });
  2806. };
  2807. /**
  2808. * Should be used to get event display name
  2809. *
  2810. * @method displayName
  2811. * @return {String} event display name
  2812. */
  2813. SolidityEvent.prototype.displayName = function () {
  2814. return utils.extractDisplayName(this._name);
  2815. };
  2816. /**
  2817. * Should be used to get event type name
  2818. *
  2819. * @method typeName
  2820. * @return {String} event type name
  2821. */
  2822. SolidityEvent.prototype.typeName = function () {
  2823. return utils.extractTypeName(this._name);
  2824. };
  2825. /**
  2826. * Should be used to get event signature
  2827. *
  2828. * @method signature
  2829. * @return {String} event signature
  2830. */
  2831. SolidityEvent.prototype.signature = function () {
  2832. return sha3(this._name);
  2833. };
  2834. /**
  2835. * Should be used to encode indexed params and options to one final object
  2836. *
  2837. * @method encode
  2838. * @param {Object} indexed
  2839. * @param {Object} options
  2840. * @return {Object} everything combined together and encoded
  2841. */
  2842. SolidityEvent.prototype.encode = function (indexed, options) {
  2843. indexed = indexed || {};
  2844. options = options || {};
  2845. var result = {};
  2846. ['fromBlock', 'toBlock'].filter(function (f) {
  2847. return options[f] !== undefined;
  2848. }).forEach(function (f) {
  2849. result[f] = formatters.inputBlockNumberFormatter(options[f]);
  2850. });
  2851. result.topics = [];
  2852. result.address = this._address;
  2853. if (!this._anonymous) {
  2854. result.topics.push('0x' + this.signature());
  2855. }
  2856. var indexedTopics = this._params.filter(function (i) {
  2857. return i.indexed === true;
  2858. }).map(function (i) {
  2859. var value = indexed[i.name];
  2860. if (value === undefined || value === null) {
  2861. return null;
  2862. }
  2863. if (utils.isArray(value)) {
  2864. return value.map(function (v) {
  2865. return '0x' + coder.encodeParam(i.type, v);
  2866. });
  2867. }
  2868. return '0x' + coder.encodeParam(i.type, value);
  2869. });
  2870. result.topics = result.topics.concat(indexedTopics);
  2871. return result;
  2872. };
  2873. /**
  2874. * Should be used to decode indexed params and options
  2875. *
  2876. * @method decode
  2877. * @param {Object} data
  2878. * @return {Object} result object with decoded indexed && not indexed params
  2879. */
  2880. SolidityEvent.prototype.decode = function (data) {
  2881. data.data = data.data || '';
  2882. data.topics = data.topics || [];
  2883. var argTopics = this._anonymous ? data.topics : data.topics.slice(1);
  2884. var indexedData = argTopics.map(function (topics) { return topics.slice(2); }).join("");
  2885. var indexedParams = coder.decodeParams(this.types(true), indexedData);
  2886. var notIndexedData = data.data.slice(2);
  2887. var notIndexedParams = coder.decodeParams(this.types(false), notIndexedData);
  2888. var result = formatters.outputLogFormatter(data);
  2889. result.event = this.displayName();
  2890. result.address = data.address;
  2891. result.args = this._params.reduce(function (acc, current) {
  2892. acc[current.name] = current.indexed ? indexedParams.shift() : notIndexedParams.shift();
  2893. return acc;
  2894. }, {});
  2895. delete result.data;
  2896. delete result.topics;
  2897. return result;
  2898. };
  2899. /**
  2900. * Should be used to create new filter object from event
  2901. *
  2902. * @method execute
  2903. * @param {Object} indexed
  2904. * @param {Object} options
  2905. * @return {Object} filter object
  2906. */
  2907. SolidityEvent.prototype.execute = function (indexed, options, callback) {
  2908. if (utils.isFunction(arguments[arguments.length - 1])) {
  2909. callback = arguments[arguments.length - 1];
  2910. if(arguments.length === 2)
  2911. options = null;
  2912. if(arguments.length === 1) {
  2913. options = null;
  2914. indexed = {};
  2915. }
  2916. }
  2917. var o = this.encode(indexed, options);
  2918. var formatter = this.decode.bind(this);
  2919. return new Filter(this._requestManager, o, watches.eth(), formatter, callback);
  2920. };
  2921. /**
  2922. * Should be used to attach event to contract object
  2923. *
  2924. * @method attachToContract
  2925. * @param {Contract}
  2926. */
  2927. SolidityEvent.prototype.attachToContract = function (contract) {
  2928. var execute = this.execute.bind(this);
  2929. var displayName = this.displayName();
  2930. if (!contract[displayName]) {
  2931. contract[displayName] = execute;
  2932. }
  2933. contract[displayName][this.typeName()] = this.execute.bind(this, contract);
  2934. };
  2935. module.exports = SolidityEvent;
  2936. },{"../solidity/coder":7,"../utils/sha3":19,"../utils/utils":20,"./filter":29,"./formatters":30,"./methods/watches":42}],28:[function(require,module,exports){
  2937. var formatters = require('./formatters');
  2938. var utils = require('./../utils/utils');
  2939. var Method = require('./method');
  2940. var Property = require('./property');
  2941. // TODO: refactor, so the input params are not altered.
  2942. // it's necessary to make same 'extension' work with multiple providers
  2943. var extend = function (web3) {
  2944. /* jshint maxcomplexity:5 */
  2945. var ex = function (extension) {
  2946. var extendedObject;
  2947. if (extension.property) {
  2948. if (!web3[extension.property]) {
  2949. web3[extension.property] = {};
  2950. }
  2951. extendedObject = web3[extension.property];
  2952. } else {
  2953. extendedObject = web3;
  2954. }
  2955. if (extension.methods) {
  2956. extension.methods.forEach(function (method) {
  2957. method.attachToObject(extendedObject);
  2958. method.setRequestManager(web3._requestManager);
  2959. });
  2960. }
  2961. if (extension.properties) {
  2962. extension.properties.forEach(function (property) {
  2963. property.attachToObject(extendedObject);
  2964. property.setRequestManager(web3._requestManager);
  2965. });
  2966. }
  2967. };
  2968. ex.formatters = formatters;
  2969. ex.utils = utils;
  2970. ex.Method = Method;
  2971. ex.Property = Property;
  2972. return ex;
  2973. };
  2974. module.exports = extend;
  2975. },{"./../utils/utils":20,"./formatters":30,"./method":36,"./property":44}],29:[function(require,module,exports){
  2976. /*
  2977. This file is part of web3.js.
  2978. web3.js is free software: you can redistribute it and/or modify
  2979. it under the terms of the GNU Lesser General Public License as published by
  2980. the Free Software Foundation, either version 3 of the License, or
  2981. (at your option) any later version.
  2982. web3.js is distributed in the hope that it will be useful,
  2983. but WITHOUT ANY WARRANTY; without even the implied warranty of
  2984. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  2985. GNU Lesser General Public License for more details.
  2986. You should have received a copy of the GNU Lesser General Public License
  2987. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  2988. */
  2989. /** @file filter.js
  2990. * @authors:
  2991. * Jeffrey Wilcke <jeff@ethdev.com>
  2992. * Marek Kotewicz <marek@ethdev.com>
  2993. * Marian Oancea <marian@ethdev.com>
  2994. * Fabian Vogelsteller <fabian@ethdev.com>
  2995. * Gav Wood <g@ethdev.com>
  2996. * @date 2014
  2997. */
  2998. var formatters = require('./formatters');
  2999. var utils = require('../utils/utils');
  3000. /**
  3001. * Converts a given topic to a hex string, but also allows null values.
  3002. *
  3003. * @param {Mixed} value
  3004. * @return {String}
  3005. */
  3006. var toTopic = function(value){
  3007. if(value === null || typeof value === 'undefined')
  3008. return null;
  3009. value = String(value);
  3010. if(value.indexOf('0x') === 0)
  3011. return value;
  3012. else
  3013. return utils.fromUtf8(value);
  3014. };
  3015. /// This method should be called on options object, to verify deprecated properties && lazy load dynamic ones
  3016. /// @param should be string or object
  3017. /// @returns options string or object
  3018. var getOptions = function (options) {
  3019. if (utils.isString(options)) {
  3020. return options;
  3021. }
  3022. options = options || {};
  3023. // make sure topics, get converted to hex
  3024. options.topics = options.topics || [];
  3025. options.topics = options.topics.map(function(topic){
  3026. return (utils.isArray(topic)) ? topic.map(toTopic) : toTopic(topic);
  3027. });
  3028. return {
  3029. topics: options.topics,
  3030. from: options.from,
  3031. to: options.to,
  3032. address: options.address,
  3033. fromBlock: formatters.inputBlockNumberFormatter(options.fromBlock),
  3034. toBlock: formatters.inputBlockNumberFormatter(options.toBlock)
  3035. };
  3036. };
  3037. /**
  3038. Adds the callback and sets up the methods, to iterate over the results.
  3039. @method getLogsAtStart
  3040. @param {Object} self
  3041. @param {funciton}
  3042. */
  3043. var getLogsAtStart = function(self, callback){
  3044. // call getFilterLogs for the first watch callback start
  3045. if (!utils.isString(self.options)) {
  3046. self.get(function (err, messages) {
  3047. // don't send all the responses to all the watches again... just to self one
  3048. if (err) {
  3049. callback(err);
  3050. }
  3051. if(utils.isArray(messages)) {
  3052. messages.forEach(function (message) {
  3053. callback(null, message);
  3054. });
  3055. }
  3056. });
  3057. }
  3058. };
  3059. /**
  3060. Adds the callback and sets up the methods, to iterate over the results.
  3061. @method pollFilter
  3062. @param {Object} self
  3063. */
  3064. var pollFilter = function(self) {
  3065. var onMessage = function (error, messages) {
  3066. if (error) {
  3067. return self.callbacks.forEach(function (callback) {
  3068. callback(error);
  3069. });
  3070. }
  3071. if(utils.isArray(messages)) {
  3072. messages.forEach(function (message) {
  3073. message = self.formatter ? self.formatter(message) : message;
  3074. self.callbacks.forEach(function (callback) {
  3075. callback(null, message);
  3076. });
  3077. });
  3078. }
  3079. };
  3080. self.requestManager.startPolling({
  3081. method: self.implementation.poll.call,
  3082. params: [self.filterId],
  3083. }, self.filterId, onMessage, self.stopWatching.bind(self));
  3084. };
  3085. var Filter = function (requestManager, options, methods, formatter, callback) {
  3086. var self = this;
  3087. var implementation = {};
  3088. methods.forEach(function (method) {
  3089. method.setRequestManager(requestManager);
  3090. method.attachToObject(implementation);
  3091. });
  3092. this.requestManager = requestManager;
  3093. this.options = getOptions(options);
  3094. this.implementation = implementation;
  3095. this.filterId = null;
  3096. this.callbacks = [];
  3097. this.getLogsCallbacks = [];
  3098. this.pollFilters = [];
  3099. this.formatter = formatter;
  3100. this.implementation.newFilter(this.options, function(error, id){
  3101. if(error) {
  3102. self.callbacks.forEach(function(cb){
  3103. cb(error);
  3104. });
  3105. } else {
  3106. self.filterId = id;
  3107. // check if there are get pending callbacks as a consequence
  3108. // of calling get() with filterId unassigned.
  3109. self.getLogsCallbacks.forEach(function (cb){
  3110. self.get(cb);
  3111. });
  3112. self.getLogsCallbacks = [];
  3113. // get filter logs for the already existing watch calls
  3114. self.callbacks.forEach(function(cb){
  3115. getLogsAtStart(self, cb);
  3116. });
  3117. if(self.callbacks.length > 0)
  3118. pollFilter(self);
  3119. // start to watch immediately
  3120. if(typeof callback === 'function') {
  3121. return self.watch(callback);
  3122. }
  3123. }
  3124. });
  3125. return this;
  3126. };
  3127. Filter.prototype.watch = function (callback) {
  3128. this.callbacks.push(callback);
  3129. if(this.filterId) {
  3130. getLogsAtStart(this, callback);
  3131. pollFilter(this);
  3132. }
  3133. return this;
  3134. };
  3135. Filter.prototype.stopWatching = function () {
  3136. this.requestManager.stopPolling(this.filterId);
  3137. // remove filter async
  3138. this.implementation.uninstallFilter(this.filterId, function(){});
  3139. this.callbacks = [];
  3140. };
  3141. Filter.prototype.get = function (callback) {
  3142. var self = this;
  3143. if (utils.isFunction(callback)) {
  3144. if (this.filterId === null) {
  3145. // If filterId is not set yet, call it back
  3146. // when newFilter() assigns it.
  3147. this.getLogsCallbacks.push(callback);
  3148. } else {
  3149. this.implementation.getLogs(this.filterId, function(err, res){
  3150. if (err) {
  3151. callback(err);
  3152. } else {
  3153. callback(null, res.map(function (log) {
  3154. return self.formatter ? self.formatter(log) : log;
  3155. }));
  3156. }
  3157. });
  3158. }
  3159. } else {
  3160. if (this.filterId === null) {
  3161. throw new Error('Filter ID Error: filter().get() can\'t be chained synchronous, please provide a callback for the get() method.');
  3162. }
  3163. var logs = this.implementation.getLogs(this.filterId);
  3164. return logs.map(function (log) {
  3165. return self.formatter ? self.formatter(log) : log;
  3166. });
  3167. }
  3168. return this;
  3169. };
  3170. module.exports = Filter;
  3171. },{"../utils/utils":20,"./formatters":30}],30:[function(require,module,exports){
  3172. /*
  3173. This file is part of web3.js.
  3174. web3.js is free software: you can redistribute it and/or modify
  3175. it under the terms of the GNU Lesser General Public License as published by
  3176. the Free Software Foundation, either version 3 of the License, or
  3177. (at your option) any later version.
  3178. web3.js is distributed in the hope that it will be useful,
  3179. but WITHOUT ANY WARRANTY; without even the implied warranty of
  3180. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  3181. GNU Lesser General Public License for more details.
  3182. You should have received a copy of the GNU Lesser General Public License
  3183. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  3184. */
  3185. /**
  3186. * @file formatters.js
  3187. * @author Marek Kotewicz <marek@ethdev.com>
  3188. * @author Fabian Vogelsteller <fabian@ethdev.com>
  3189. * @date 2015
  3190. */
  3191. var utils = require('../utils/utils');
  3192. var config = require('../utils/config');
  3193. var Iban = require('./iban');
  3194. /**
  3195. * Should the format output to a big number
  3196. *
  3197. * @method outputBigNumberFormatter
  3198. * @param {String|Number|BigNumber}
  3199. * @returns {BigNumber} object
  3200. */
  3201. var outputBigNumberFormatter = function (number) {
  3202. return utils.toBigNumber(number);
  3203. };
  3204. var isPredefinedBlockNumber = function (blockNumber) {
  3205. return blockNumber === 'latest' || blockNumber === 'pending' || blockNumber === 'earliest';
  3206. };
  3207. var inputDefaultBlockNumberFormatter = function (blockNumber) {
  3208. if (blockNumber === undefined) {
  3209. return config.defaultBlock;
  3210. }
  3211. return inputBlockNumberFormatter(blockNumber);
  3212. };
  3213. var inputBlockNumberFormatter = function (blockNumber) {
  3214. if (blockNumber === undefined) {
  3215. return undefined;
  3216. } else if (isPredefinedBlockNumber(blockNumber)) {
  3217. return blockNumber;
  3218. }
  3219. return utils.toHex(blockNumber);
  3220. };
  3221. /**
  3222. * Formats the input of a transaction and converts all values to HEX
  3223. *
  3224. * @method inputCallFormatter
  3225. * @param {Object} transaction options
  3226. * @returns object
  3227. */
  3228. var inputCallFormatter = function (options){
  3229. options.from = options.from || config.defaultAccount;
  3230. if (options.from) {
  3231. options.from = inputAddressFormatter(options.from);
  3232. }
  3233. if (options.to) { // it might be contract creation
  3234. options.to = inputAddressFormatter(options.to);
  3235. }
  3236. ['gasPrice', 'gas', 'value', 'nonce'].filter(function (key) {
  3237. return options[key] !== undefined;
  3238. }).forEach(function(key){
  3239. options[key] = utils.fromDecimal(options[key]);
  3240. });
  3241. return options;
  3242. };
  3243. /**
  3244. * Formats the input of a transaction and converts all values to HEX
  3245. *
  3246. * @method inputTransactionFormatter
  3247. * @param {Object} transaction options
  3248. * @returns object
  3249. */
  3250. var inputTransactionFormatter = function (options){
  3251. options.from = options.from || config.defaultAccount;
  3252. options.from = inputAddressFormatter(options.from);
  3253. if (options.to) { // it might be contract creation
  3254. options.to = inputAddressFormatter(options.to);
  3255. }
  3256. ['gasPrice', 'gas', 'value', 'nonce'].filter(function (key) {
  3257. return options[key] !== undefined;
  3258. }).forEach(function(key){
  3259. options[key] = utils.fromDecimal(options[key]);
  3260. });
  3261. return options;
  3262. };
  3263. /**
  3264. * Formats the output of a transaction to its proper values
  3265. *
  3266. * @method outputTransactionFormatter
  3267. * @param {Object} tx
  3268. * @returns {Object}
  3269. */
  3270. var outputTransactionFormatter = function (tx){
  3271. if(tx.blockNumber !== null)
  3272. tx.blockNumber = utils.toDecimal(tx.blockNumber);
  3273. if(tx.transactionIndex !== null)
  3274. tx.transactionIndex = utils.toDecimal(tx.transactionIndex);
  3275. tx.nonce = utils.toDecimal(tx.nonce);
  3276. tx.gas = utils.toDecimal(tx.gas);
  3277. tx.gasPrice = utils.toBigNumber(tx.gasPrice);
  3278. tx.value = utils.toBigNumber(tx.value);
  3279. return tx;
  3280. };
  3281. /**
  3282. * Formats the output of a transaction receipt to its proper values
  3283. *
  3284. * @method outputTransactionReceiptFormatter
  3285. * @param {Object} receipt
  3286. * @returns {Object}
  3287. */
  3288. var outputTransactionReceiptFormatter = function (receipt){
  3289. if(receipt.blockNumber !== null)
  3290. receipt.blockNumber = utils.toDecimal(receipt.blockNumber);
  3291. if(receipt.transactionIndex !== null)
  3292. receipt.transactionIndex = utils.toDecimal(receipt.transactionIndex);
  3293. receipt.cumulativeGasUsed = utils.toDecimal(receipt.cumulativeGasUsed);
  3294. receipt.gasUsed = utils.toDecimal(receipt.gasUsed);
  3295. if(utils.isArray(receipt.logs)) {
  3296. receipt.logs = receipt.logs.map(function(log){
  3297. return outputLogFormatter(log);
  3298. });
  3299. }
  3300. return receipt;
  3301. };
  3302. /**
  3303. * Formats the output of a block to its proper values
  3304. *
  3305. * @method outputBlockFormatter
  3306. * @param {Object} block
  3307. * @returns {Object}
  3308. */
  3309. var outputBlockFormatter = function(block) {
  3310. // transform to number
  3311. block.gasLimit = utils.toDecimal(block.gasLimit);
  3312. block.gasUsed = utils.toDecimal(block.gasUsed);
  3313. block.size = utils.toDecimal(block.size);
  3314. block.timestamp = utils.toDecimal(block.timestamp);
  3315. if(block.number !== null)
  3316. block.number = utils.toDecimal(block.number);
  3317. block.difficulty = utils.toBigNumber(block.difficulty);
  3318. block.totalDifficulty = utils.toBigNumber(block.totalDifficulty);
  3319. if (utils.isArray(block.transactions)) {
  3320. block.transactions.forEach(function(item){
  3321. if(!utils.isString(item))
  3322. return outputTransactionFormatter(item);
  3323. });
  3324. }
  3325. return block;
  3326. };
  3327. /**
  3328. * Formats the output of a log
  3329. *
  3330. * @method outputLogFormatter
  3331. * @param {Object} log object
  3332. * @returns {Object} log
  3333. */
  3334. var outputLogFormatter = function(log) {
  3335. if(log.blockNumber !== null)
  3336. log.blockNumber = utils.toDecimal(log.blockNumber);
  3337. if(log.transactionIndex !== null)
  3338. log.transactionIndex = utils.toDecimal(log.transactionIndex);
  3339. if(log.logIndex !== null)
  3340. log.logIndex = utils.toDecimal(log.logIndex);
  3341. return log;
  3342. };
  3343. /**
  3344. * Formats the input of a whisper post and converts all values to HEX
  3345. *
  3346. * @method inputPostFormatter
  3347. * @param {Object} transaction object
  3348. * @returns {Object}
  3349. */
  3350. var inputPostFormatter = function(post) {
  3351. // post.payload = utils.toHex(post.payload);
  3352. post.ttl = utils.fromDecimal(post.ttl);
  3353. post.workToProve = utils.fromDecimal(post.workToProve);
  3354. post.priority = utils.fromDecimal(post.priority);
  3355. // fallback
  3356. if (!utils.isArray(post.topics)) {
  3357. post.topics = post.topics ? [post.topics] : [];
  3358. }
  3359. // format the following options
  3360. post.topics = post.topics.map(function(topic){
  3361. // convert only if not hex
  3362. return (topic.indexOf('0x') === 0) ? topic : utils.fromUtf8(topic);
  3363. });
  3364. return post;
  3365. };
  3366. /**
  3367. * Formats the output of a received post message
  3368. *
  3369. * @method outputPostFormatter
  3370. * @param {Object}
  3371. * @returns {Object}
  3372. */
  3373. var outputPostFormatter = function(post){
  3374. post.expiry = utils.toDecimal(post.expiry);
  3375. post.sent = utils.toDecimal(post.sent);
  3376. post.ttl = utils.toDecimal(post.ttl);
  3377. post.workProved = utils.toDecimal(post.workProved);
  3378. // post.payloadRaw = post.payload;
  3379. // post.payload = utils.toAscii(post.payload);
  3380. // if (utils.isJson(post.payload)) {
  3381. // post.payload = JSON.parse(post.payload);
  3382. // }
  3383. // format the following options
  3384. if (!post.topics) {
  3385. post.topics = [];
  3386. }
  3387. post.topics = post.topics.map(function(topic){
  3388. return utils.toAscii(topic);
  3389. });
  3390. return post;
  3391. };
  3392. var inputAddressFormatter = function (address) {
  3393. var iban = new Iban(address);
  3394. if (iban.isValid() && iban.isDirect()) {
  3395. return '0x' + iban.address();
  3396. } else if (utils.isStrictAddress(address)) {
  3397. return address;
  3398. } else if (utils.isAddress(address)) {
  3399. return '0x' + address;
  3400. }
  3401. throw new Error('invalid address');
  3402. };
  3403. var outputSyncingFormatter = function(result) {
  3404. result.startingBlock = utils.toDecimal(result.startingBlock);
  3405. result.currentBlock = utils.toDecimal(result.currentBlock);
  3406. result.highestBlock = utils.toDecimal(result.highestBlock);
  3407. if (result.knownStates !== undefined) {
  3408. result.knownStates = utils.toDecimal(result.knownStates);
  3409. }
  3410. if (result.pulledStates !== undefined) {
  3411. result.pulledStates = utils.toDecimal(result.pulledStates);
  3412. }
  3413. return result;
  3414. };
  3415. module.exports = {
  3416. inputDefaultBlockNumberFormatter: inputDefaultBlockNumberFormatter,
  3417. inputBlockNumberFormatter: inputBlockNumberFormatter,
  3418. inputCallFormatter: inputCallFormatter,
  3419. inputTransactionFormatter: inputTransactionFormatter,
  3420. inputAddressFormatter: inputAddressFormatter,
  3421. inputPostFormatter: inputPostFormatter,
  3422. outputBigNumberFormatter: outputBigNumberFormatter,
  3423. outputTransactionFormatter: outputTransactionFormatter,
  3424. outputTransactionReceiptFormatter: outputTransactionReceiptFormatter,
  3425. outputBlockFormatter: outputBlockFormatter,
  3426. outputLogFormatter: outputLogFormatter,
  3427. outputPostFormatter: outputPostFormatter,
  3428. outputSyncingFormatter: outputSyncingFormatter
  3429. };
  3430. },{"../utils/config":18,"../utils/utils":20,"./iban":33}],31:[function(require,module,exports){
  3431. /*
  3432. This file is part of web3.js.
  3433. web3.js is free software: you can redistribute it and/or modify
  3434. it under the terms of the GNU Lesser General Public License as published by
  3435. the Free Software Foundation, either version 3 of the License, or
  3436. (at your option) any later version.
  3437. web3.js is distributed in the hope that it will be useful,
  3438. but WITHOUT ANY WARRANTY; without even the implied warranty of
  3439. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  3440. GNU Lesser General Public License for more details.
  3441. You should have received a copy of the GNU Lesser General Public License
  3442. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  3443. */
  3444. /**
  3445. * @file function.js
  3446. * @author Marek Kotewicz <marek@ethdev.com>
  3447. * @date 2015
  3448. */
  3449. var coder = require('../solidity/coder');
  3450. var utils = require('../utils/utils');
  3451. var formatters = require('./formatters');
  3452. var sha3 = require('../utils/sha3');
  3453. /**
  3454. * This prototype should be used to call/sendTransaction to solidity functions
  3455. */
  3456. var SolidityFunction = function (eth, json, address) {
  3457. this._eth = eth;
  3458. this._inputTypes = json.inputs.map(function (i) {
  3459. return i.type;
  3460. });
  3461. this._outputTypes = json.outputs.map(function (i) {
  3462. return i.type;
  3463. });
  3464. this._constant = json.constant;
  3465. this._name = utils.transformToFullName(json);
  3466. this._address = address;
  3467. };
  3468. SolidityFunction.prototype.extractCallback = function (args) {
  3469. if (utils.isFunction(args[args.length - 1])) {
  3470. return args.pop(); // modify the args array!
  3471. }
  3472. };
  3473. SolidityFunction.prototype.extractDefaultBlock = function (args) {
  3474. if (args.length > this._inputTypes.length && !utils.isObject(args[args.length -1])) {
  3475. return formatters.inputDefaultBlockNumberFormatter(args.pop()); // modify the args array!
  3476. }
  3477. };
  3478. /**
  3479. * Should be used to create payload from arguments
  3480. *
  3481. * @method toPayload
  3482. * @param {Array} solidity function params
  3483. * @param {Object} optional payload options
  3484. */
  3485. SolidityFunction.prototype.toPayload = function (args) {
  3486. var options = {};
  3487. if (args.length > this._inputTypes.length && utils.isObject(args[args.length -1])) {
  3488. options = args[args.length - 1];
  3489. }
  3490. options.to = this._address;
  3491. options.data = '0x' + this.signature() + coder.encodeParams(this._inputTypes, args);
  3492. return options;
  3493. };
  3494. /**
  3495. * Should be used to get function signature
  3496. *
  3497. * @method signature
  3498. * @return {String} function signature
  3499. */
  3500. SolidityFunction.prototype.signature = function () {
  3501. return sha3(this._name).slice(0, 8);
  3502. };
  3503. SolidityFunction.prototype.unpackOutput = function (output) {
  3504. if (!output) {
  3505. return;
  3506. }
  3507. output = output.length >= 2 ? output.slice(2) : output;
  3508. var result = coder.decodeParams(this._outputTypes, output);
  3509. return result.length === 1 ? result[0] : result;
  3510. };
  3511. /**
  3512. * Calls a contract function.
  3513. *
  3514. * @method call
  3515. * @param {...Object} Contract function arguments
  3516. * @param {function} If the last argument is a function, the contract function
  3517. * call will be asynchronous, and the callback will be passed the
  3518. * error and result.
  3519. * @return {String} output bytes
  3520. */
  3521. SolidityFunction.prototype.call = function () {
  3522. var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; });
  3523. var callback = this.extractCallback(args);
  3524. var defaultBlock = this.extractDefaultBlock(args);
  3525. var payload = this.toPayload(args);
  3526. if (!callback) {
  3527. var output = this._eth.call(payload, defaultBlock);
  3528. return this.unpackOutput(output);
  3529. }
  3530. var self = this;
  3531. this._eth.call(payload, defaultBlock, function (error, output) {
  3532. callback(error, self.unpackOutput(output));
  3533. });
  3534. };
  3535. /**
  3536. * Should be used to sendTransaction to solidity function
  3537. *
  3538. * @method sendTransaction
  3539. */
  3540. SolidityFunction.prototype.sendTransaction = function () {
  3541. var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; });
  3542. var callback = this.extractCallback(args);
  3543. var payload = this.toPayload(args);
  3544. if (!callback) {
  3545. return this._eth.sendTransaction(payload);
  3546. }
  3547. this._eth.sendTransaction(payload, callback);
  3548. };
  3549. /**
  3550. * Should be used to estimateGas of solidity function
  3551. *
  3552. * @method estimateGas
  3553. */
  3554. SolidityFunction.prototype.estimateGas = function () {
  3555. var args = Array.prototype.slice.call(arguments);
  3556. var callback = this.extractCallback(args);
  3557. var payload = this.toPayload(args);
  3558. if (!callback) {
  3559. return this._eth.estimateGas(payload);
  3560. }
  3561. this._eth.estimateGas(payload, callback);
  3562. };
  3563. /**
  3564. * Return the encoded data of the call
  3565. *
  3566. * @method getData
  3567. * @return {String} the encoded data
  3568. */
  3569. SolidityFunction.prototype.getData = function () {
  3570. var args = Array.prototype.slice.call(arguments);
  3571. var payload = this.toPayload(args);
  3572. return payload.data;
  3573. };
  3574. /**
  3575. * Should be used to get function display name
  3576. *
  3577. * @method displayName
  3578. * @return {String} display name of the function
  3579. */
  3580. SolidityFunction.prototype.displayName = function () {
  3581. return utils.extractDisplayName(this._name);
  3582. };
  3583. /**
  3584. * Should be used to get function type name
  3585. *
  3586. * @method typeName
  3587. * @return {String} type name of the function
  3588. */
  3589. SolidityFunction.prototype.typeName = function () {
  3590. return utils.extractTypeName(this._name);
  3591. };
  3592. /**
  3593. * Should be called to get rpc requests from solidity function
  3594. *
  3595. * @method request
  3596. * @returns {Object}
  3597. */
  3598. SolidityFunction.prototype.request = function () {
  3599. var args = Array.prototype.slice.call(arguments);
  3600. var callback = this.extractCallback(args);
  3601. var payload = this.toPayload(args);
  3602. var format = this.unpackOutput.bind(this);
  3603. return {
  3604. method: this._constant ? 'eth_call' : 'eth_sendTransaction',
  3605. callback: callback,
  3606. params: [payload],
  3607. format: format
  3608. };
  3609. };
  3610. /**
  3611. * Should be called to execute function
  3612. *
  3613. * @method execute
  3614. */
  3615. SolidityFunction.prototype.execute = function () {
  3616. var transaction = !this._constant;
  3617. // send transaction
  3618. if (transaction) {
  3619. return this.sendTransaction.apply(this, Array.prototype.slice.call(arguments));
  3620. }
  3621. // call
  3622. return this.call.apply(this, Array.prototype.slice.call(arguments));
  3623. };
  3624. /**
  3625. * Should be called to attach function to contract
  3626. *
  3627. * @method attachToContract
  3628. * @param {Contract}
  3629. */
  3630. SolidityFunction.prototype.attachToContract = function (contract) {
  3631. var execute = this.execute.bind(this);
  3632. execute.request = this.request.bind(this);
  3633. execute.call = this.call.bind(this);
  3634. execute.sendTransaction = this.sendTransaction.bind(this);
  3635. execute.estimateGas = this.estimateGas.bind(this);
  3636. execute.getData = this.getData.bind(this);
  3637. var displayName = this.displayName();
  3638. if (!contract[displayName]) {
  3639. contract[displayName] = execute;
  3640. }
  3641. contract[displayName][this.typeName()] = execute; // circular!!!!
  3642. };
  3643. module.exports = SolidityFunction;
  3644. },{"../solidity/coder":7,"../utils/sha3":19,"../utils/utils":20,"./formatters":30}],32:[function(require,module,exports){
  3645. /*
  3646. This file is part of web3.js.
  3647. web3.js is free software: you can redistribute it and/or modify
  3648. it under the terms of the GNU Lesser General Public License as published by
  3649. the Free Software Foundation, either version 3 of the License, or
  3650. (at your option) any later version.
  3651. web3.js is distributed in the hope that it will be useful,
  3652. but WITHOUT ANY WARRANTY; without even the implied warranty of
  3653. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  3654. GNU Lesser General Public License for more details.
  3655. You should have received a copy of the GNU Lesser General Public License
  3656. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  3657. */
  3658. /** @file httpprovider.js
  3659. * @authors:
  3660. * Marek Kotewicz <marek@ethdev.com>
  3661. * Marian Oancea <marian@ethdev.com>
  3662. * Fabian Vogelsteller <fabian@ethdev.com>
  3663. * @date 2015
  3664. */
  3665. "use strict";
  3666. var errors = require('./errors');
  3667. // workaround to use httpprovider in different envs
  3668. var XMLHttpRequest; // jshint ignore: line
  3669. // meteor server environment
  3670. if (typeof Meteor !== 'undefined' && Meteor.isServer) { // jshint ignore: line
  3671. XMLHttpRequest = Npm.require('xmlhttprequest').XMLHttpRequest; // jshint ignore: line
  3672. // browser
  3673. } else if (typeof window !== 'undefined' && window.XMLHttpRequest) {
  3674. XMLHttpRequest = window.XMLHttpRequest; // jshint ignore: line
  3675. // node
  3676. } else {
  3677. XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; // jshint ignore: line
  3678. }
  3679. /**
  3680. * HttpProvider should be used to send rpc calls over http
  3681. */
  3682. var HttpProvider = function (host) {
  3683. this.host = host || 'http://localhost:8545';
  3684. };
  3685. /**
  3686. * Should be called to prepare new XMLHttpRequest
  3687. *
  3688. * @method prepareRequest
  3689. * @param {Boolean} true if request should be async
  3690. * @return {XMLHttpRequest} object
  3691. */
  3692. HttpProvider.prototype.prepareRequest = function (async) {
  3693. var request = new XMLHttpRequest();
  3694. request.open('POST', this.host, async);
  3695. request.setRequestHeader('Content-Type','application/json');
  3696. return request;
  3697. };
  3698. /**
  3699. * Should be called to make sync request
  3700. *
  3701. * @method send
  3702. * @param {Object} payload
  3703. * @return {Object} result
  3704. */
  3705. HttpProvider.prototype.send = function (payload) {
  3706. var request = this.prepareRequest(false);
  3707. try {
  3708. request.send(JSON.stringify(payload));
  3709. } catch(error) {
  3710. throw errors.InvalidConnection(this.host);
  3711. }
  3712. var result = request.responseText;
  3713. try {
  3714. result = JSON.parse(result);
  3715. } catch(e) {
  3716. throw errors.InvalidResponse(request.responseText);
  3717. }
  3718. return result;
  3719. };
  3720. /**
  3721. * Should be used to make async request
  3722. *
  3723. * @method sendAsync
  3724. * @param {Object} payload
  3725. * @param {Function} callback triggered on end with (err, result)
  3726. */
  3727. HttpProvider.prototype.sendAsync = function (payload, callback) {
  3728. var request = this.prepareRequest(true);
  3729. request.onreadystatechange = function() {
  3730. if (request.readyState === 4) {
  3731. var result = request.responseText;
  3732. var error = null;
  3733. try {
  3734. result = JSON.parse(result);
  3735. } catch(e) {
  3736. error = errors.InvalidResponse(request.responseText);
  3737. }
  3738. callback(error, result);
  3739. }
  3740. };
  3741. try {
  3742. request.send(JSON.stringify(payload));
  3743. } catch(error) {
  3744. callback(errors.InvalidConnection(this.host));
  3745. }
  3746. };
  3747. /**
  3748. * Synchronously tries to make Http request
  3749. *
  3750. * @method isConnected
  3751. * @return {Boolean} returns true if request haven't failed. Otherwise false
  3752. */
  3753. HttpProvider.prototype.isConnected = function() {
  3754. try {
  3755. this.send({
  3756. id: 9999999999,
  3757. jsonrpc: '2.0',
  3758. method: 'net_listening',
  3759. params: []
  3760. });
  3761. return true;
  3762. } catch(e) {
  3763. return false;
  3764. }
  3765. };
  3766. module.exports = HttpProvider;
  3767. },{"./errors":26,"xmlhttprequest":17}],33:[function(require,module,exports){
  3768. /*
  3769. This file is part of web3.js.
  3770. web3.js is free software: you can redistribute it and/or modify
  3771. it under the terms of the GNU Lesser General Public License as published by
  3772. the Free Software Foundation, either version 3 of the License, or
  3773. (at your option) any later version.
  3774. web3.js is distributed in the hope that it will be useful,
  3775. but WITHOUT ANY WARRANTY; without even the implied warranty of
  3776. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  3777. GNU Lesser General Public License for more details.
  3778. You should have received a copy of the GNU Lesser General Public License
  3779. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  3780. */
  3781. /**
  3782. * @file iban.js
  3783. * @author Marek Kotewicz <marek@ethdev.com>
  3784. * @date 2015
  3785. */
  3786. var BigNumber = require('bignumber.js');
  3787. var padLeft = function (string, bytes) {
  3788. var result = string;
  3789. while (result.length < bytes * 2) {
  3790. result = '00' + result;
  3791. }
  3792. return result;
  3793. };
  3794. /**
  3795. * Prepare an IBAN for mod 97 computation by moving the first 4 chars to the end and transforming the letters to
  3796. * numbers (A = 10, B = 11, ..., Z = 35), as specified in ISO13616.
  3797. *
  3798. * @method iso13616Prepare
  3799. * @param {String} iban the IBAN
  3800. * @returns {String} the prepared IBAN
  3801. */
  3802. var iso13616Prepare = function (iban) {
  3803. var A = 'A'.charCodeAt(0);
  3804. var Z = 'Z'.charCodeAt(0);
  3805. iban = iban.toUpperCase();
  3806. iban = iban.substr(4) + iban.substr(0,4);
  3807. return iban.split('').map(function(n){
  3808. var code = n.charCodeAt(0);
  3809. if (code >= A && code <= Z){
  3810. // A = 10, B = 11, ... Z = 35
  3811. return code - A + 10;
  3812. } else {
  3813. return n;
  3814. }
  3815. }).join('');
  3816. };
  3817. /**
  3818. * Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064.
  3819. *
  3820. * @method mod9710
  3821. * @param {String} iban
  3822. * @returns {Number}
  3823. */
  3824. var mod9710 = function (iban) {
  3825. var remainder = iban,
  3826. block;
  3827. while (remainder.length > 2){
  3828. block = remainder.slice(0, 9);
  3829. remainder = parseInt(block, 10) % 97 + remainder.slice(block.length);
  3830. }
  3831. return parseInt(remainder, 10) % 97;
  3832. };
  3833. /**
  3834. * This prototype should be used to create iban object from iban correct string
  3835. *
  3836. * @param {String} iban
  3837. */
  3838. var Iban = function (iban) {
  3839. this._iban = iban;
  3840. };
  3841. /**
  3842. * This method should be used to create iban object from ethereum address
  3843. *
  3844. * @method fromAddress
  3845. * @param {String} address
  3846. * @return {Iban} the IBAN object
  3847. */
  3848. Iban.fromAddress = function (address) {
  3849. var asBn = new BigNumber(address, 16);
  3850. var base36 = asBn.toString(36);
  3851. var padded = padLeft(base36, 15);
  3852. return Iban.fromBban(padded.toUpperCase());
  3853. };
  3854. /**
  3855. * Convert the passed BBAN to an IBAN for this country specification.
  3856. * Please note that <i>"generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account"</i>.
  3857. * This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits
  3858. *
  3859. * @method fromBban
  3860. * @param {String} bban the BBAN to convert to IBAN
  3861. * @returns {Iban} the IBAN object
  3862. */
  3863. Iban.fromBban = function (bban) {
  3864. var countryCode = 'XE';
  3865. var remainder = mod9710(iso13616Prepare(countryCode + '00' + bban));
  3866. var checkDigit = ('0' + (98 - remainder)).slice(-2);
  3867. return new Iban(countryCode + checkDigit + bban);
  3868. };
  3869. /**
  3870. * Should be used to create IBAN object for given institution and identifier
  3871. *
  3872. * @method createIndirect
  3873. * @param {Object} options, required options are "institution" and "identifier"
  3874. * @return {Iban} the IBAN object
  3875. */
  3876. Iban.createIndirect = function (options) {
  3877. return Iban.fromBban('ETH' + options.institution + options.identifier);
  3878. };
  3879. /**
  3880. * Thos method should be used to check if given string is valid iban object
  3881. *
  3882. * @method isValid
  3883. * @param {String} iban string
  3884. * @return {Boolean} true if it is valid IBAN
  3885. */
  3886. Iban.isValid = function (iban) {
  3887. var i = new Iban(iban);
  3888. return i.isValid();
  3889. };
  3890. /**
  3891. * Should be called to check if iban is correct
  3892. *
  3893. * @method isValid
  3894. * @returns {Boolean} true if it is, otherwise false
  3895. */
  3896. Iban.prototype.isValid = function () {
  3897. return /^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(this._iban) &&
  3898. mod9710(iso13616Prepare(this._iban)) === 1;
  3899. };
  3900. /**
  3901. * Should be called to check if iban number is direct
  3902. *
  3903. * @method isDirect
  3904. * @returns {Boolean} true if it is, otherwise false
  3905. */
  3906. Iban.prototype.isDirect = function () {
  3907. return this._iban.length === 34 || this._iban.length === 35;
  3908. };
  3909. /**
  3910. * Should be called to check if iban number if indirect
  3911. *
  3912. * @method isIndirect
  3913. * @returns {Boolean} true if it is, otherwise false
  3914. */
  3915. Iban.prototype.isIndirect = function () {
  3916. return this._iban.length === 20;
  3917. };
  3918. /**
  3919. * Should be called to get iban checksum
  3920. * Uses the mod-97-10 checksumming protocol (ISO/IEC 7064:2003)
  3921. *
  3922. * @method checksum
  3923. * @returns {String} checksum
  3924. */
  3925. Iban.prototype.checksum = function () {
  3926. return this._iban.substr(2, 2);
  3927. };
  3928. /**
  3929. * Should be called to get institution identifier
  3930. * eg. XREG
  3931. *
  3932. * @method institution
  3933. * @returns {String} institution identifier
  3934. */
  3935. Iban.prototype.institution = function () {
  3936. return this.isIndirect() ? this._iban.substr(7, 4) : '';
  3937. };
  3938. /**
  3939. * Should be called to get client identifier within institution
  3940. * eg. GAVOFYORK
  3941. *
  3942. * @method client
  3943. * @returns {String} client identifier
  3944. */
  3945. Iban.prototype.client = function () {
  3946. return this.isIndirect() ? this._iban.substr(11) : '';
  3947. };
  3948. /**
  3949. * Should be called to get client direct address
  3950. *
  3951. * @method address
  3952. * @returns {String} client direct address
  3953. */
  3954. Iban.prototype.address = function () {
  3955. if (this.isDirect()) {
  3956. var base36 = this._iban.substr(4);
  3957. var asBn = new BigNumber(base36, 36);
  3958. return padLeft(asBn.toString(16), 20);
  3959. }
  3960. return '';
  3961. };
  3962. Iban.prototype.toString = function () {
  3963. return this._iban;
  3964. };
  3965. module.exports = Iban;
  3966. },{"bignumber.js":"bignumber.js"}],34:[function(require,module,exports){
  3967. /*
  3968. This file is part of web3.js.
  3969. web3.js is free software: you can redistribute it and/or modify
  3970. it under the terms of the GNU Lesser General Public License as published by
  3971. the Free Software Foundation, either version 3 of the License, or
  3972. (at your option) any later version.
  3973. web3.js is distributed in the hope that it will be useful,
  3974. but WITHOUT ANY WARRANTY; without even the implied warranty of
  3975. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  3976. GNU Lesser General Public License for more details.
  3977. You should have received a copy of the GNU Lesser General Public License
  3978. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  3979. */
  3980. /** @file ipcprovider.js
  3981. * @authors:
  3982. * Fabian Vogelsteller <fabian@ethdev.com>
  3983. * @date 2015
  3984. */
  3985. "use strict";
  3986. var utils = require('../utils/utils');
  3987. var errors = require('./errors');
  3988. var IpcProvider = function (path, net) {
  3989. var _this = this;
  3990. this.responseCallbacks = {};
  3991. this.path = path;
  3992. this.connection = net.connect({path: this.path});
  3993. this.connection.on('error', function(e){
  3994. console.error('IPC Connection Error', e);
  3995. _this._timeout();
  3996. });
  3997. this.connection.on('end', function(){
  3998. _this._timeout();
  3999. });
  4000. // LISTEN FOR CONNECTION RESPONSES
  4001. this.connection.on('data', function(data) {
  4002. /*jshint maxcomplexity: 6 */
  4003. _this._parseResponse(data.toString()).forEach(function(result){
  4004. var id = null;
  4005. // get the id which matches the returned id
  4006. if(utils.isArray(result)) {
  4007. result.forEach(function(load){
  4008. if(_this.responseCallbacks[load.id])
  4009. id = load.id;
  4010. });
  4011. } else {
  4012. id = result.id;
  4013. }
  4014. // fire the callback
  4015. if(_this.responseCallbacks[id]) {
  4016. _this.responseCallbacks[id](null, result);
  4017. delete _this.responseCallbacks[id];
  4018. }
  4019. });
  4020. });
  4021. };
  4022. /**
  4023. Will parse the response and make an array out of it.
  4024. @method _parseResponse
  4025. @param {String} data
  4026. */
  4027. IpcProvider.prototype._parseResponse = function(data) {
  4028. var _this = this,
  4029. returnValues = [];
  4030. // DE-CHUNKER
  4031. var dechunkedData = data
  4032. .replace(/\}[\n\r]?\{/g,'}|--|{') // }{
  4033. .replace(/\}\][\n\r]?\[\{/g,'}]|--|[{') // }][{
  4034. .replace(/\}[\n\r]?\[\{/g,'}|--|[{') // }[{
  4035. .replace(/\}\][\n\r]?\{/g,'}]|--|{') // }]{
  4036. .split('|--|');
  4037. dechunkedData.forEach(function(data){
  4038. // prepend the last chunk
  4039. if(_this.lastChunk)
  4040. data = _this.lastChunk + data;
  4041. var result = null;
  4042. try {
  4043. result = JSON.parse(data);
  4044. } catch(e) {
  4045. _this.lastChunk = data;
  4046. // start timeout to cancel all requests
  4047. clearTimeout(_this.lastChunkTimeout);
  4048. _this.lastChunkTimeout = setTimeout(function(){
  4049. _this._timeout();
  4050. throw errors.InvalidResponse(data);
  4051. }, 1000 * 15);
  4052. return;
  4053. }
  4054. // cancel timeout and set chunk to null
  4055. clearTimeout(_this.lastChunkTimeout);
  4056. _this.lastChunk = null;
  4057. if(result)
  4058. returnValues.push(result);
  4059. });
  4060. return returnValues;
  4061. };
  4062. /**
  4063. Get the adds a callback to the responseCallbacks object,
  4064. which will be called if a response matching the response Id will arrive.
  4065. @method _addResponseCallback
  4066. */
  4067. IpcProvider.prototype._addResponseCallback = function(payload, callback) {
  4068. var id = payload.id || payload[0].id;
  4069. var method = payload.method || payload[0].method;
  4070. this.responseCallbacks[id] = callback;
  4071. this.responseCallbacks[id].method = method;
  4072. };
  4073. /**
  4074. Timeout all requests when the end/error event is fired
  4075. @method _timeout
  4076. */
  4077. IpcProvider.prototype._timeout = function() {
  4078. for(var key in this.responseCallbacks) {
  4079. if(this.responseCallbacks.hasOwnProperty(key)){
  4080. this.responseCallbacks[key](errors.InvalidConnection('on IPC'));
  4081. delete this.responseCallbacks[key];
  4082. }
  4083. }
  4084. };
  4085. /**
  4086. Check if the current connection is still valid.
  4087. @method isConnected
  4088. */
  4089. IpcProvider.prototype.isConnected = function() {
  4090. var _this = this;
  4091. // try reconnect, when connection is gone
  4092. if(!_this.connection.writable)
  4093. _this.connection.connect({path: _this.path});
  4094. return !!this.connection.writable;
  4095. };
  4096. IpcProvider.prototype.send = function (payload) {
  4097. if(this.connection.writeSync) {
  4098. var result;
  4099. // try reconnect, when connection is gone
  4100. if(!this.connection.writable)
  4101. this.connection.connect({path: this.path});
  4102. var data = this.connection.writeSync(JSON.stringify(payload));
  4103. try {
  4104. result = JSON.parse(data);
  4105. } catch(e) {
  4106. throw errors.InvalidResponse(data);
  4107. }
  4108. return result;
  4109. } else {
  4110. throw new Error('You tried to send "'+ payload.method +'" synchronously. Synchronous requests are not supported by the IPC provider.');
  4111. }
  4112. };
  4113. IpcProvider.prototype.sendAsync = function (payload, callback) {
  4114. // try reconnect, when connection is gone
  4115. if(!this.connection.writable)
  4116. this.connection.connect({path: this.path});
  4117. this.connection.write(JSON.stringify(payload));
  4118. this._addResponseCallback(payload, callback);
  4119. };
  4120. module.exports = IpcProvider;
  4121. },{"../utils/utils":20,"./errors":26}],35:[function(require,module,exports){
  4122. /*
  4123. This file is part of web3.js.
  4124. web3.js is free software: you can redistribute it and/or modify
  4125. it under the terms of the GNU Lesser General Public License as published by
  4126. the Free Software Foundation, either version 3 of the License, or
  4127. (at your option) any later version.
  4128. web3.js is distributed in the hope that it will be useful,
  4129. but WITHOUT ANY WARRANTY; without even the implied warranty of
  4130. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  4131. GNU Lesser General Public License for more details.
  4132. You should have received a copy of the GNU Lesser General Public License
  4133. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  4134. */
  4135. /** @file jsonrpc.js
  4136. * @authors:
  4137. * Marek Kotewicz <marek@ethdev.com>
  4138. * @date 2015
  4139. */
  4140. var Jsonrpc = function () {
  4141. // singleton pattern
  4142. if (arguments.callee._singletonInstance) {
  4143. return arguments.callee._singletonInstance;
  4144. }
  4145. arguments.callee._singletonInstance = this;
  4146. this.messageId = 1;
  4147. };
  4148. /**
  4149. * @return {Jsonrpc} singleton
  4150. */
  4151. Jsonrpc.getInstance = function () {
  4152. var instance = new Jsonrpc();
  4153. return instance;
  4154. };
  4155. /**
  4156. * Should be called to valid json create payload object
  4157. *
  4158. * @method toPayload
  4159. * @param {Function} method of jsonrpc call, required
  4160. * @param {Array} params, an array of method params, optional
  4161. * @returns {Object} valid jsonrpc payload object
  4162. */
  4163. Jsonrpc.prototype.toPayload = function (method, params) {
  4164. if (!method)
  4165. console.error('jsonrpc method should be specified!');
  4166. return {
  4167. jsonrpc: '2.0',
  4168. method: method,
  4169. params: params || [],
  4170. id: this.messageId++
  4171. };
  4172. };
  4173. /**
  4174. * Should be called to check if jsonrpc response is valid
  4175. *
  4176. * @method isValidResponse
  4177. * @param {Object}
  4178. * @returns {Boolean} true if response is valid, otherwise false
  4179. */
  4180. Jsonrpc.prototype.isValidResponse = function (response) {
  4181. return !!response &&
  4182. !response.error &&
  4183. response.jsonrpc === '2.0' &&
  4184. typeof response.id === 'number' &&
  4185. response.result !== undefined; // only undefined is not valid json object
  4186. };
  4187. /**
  4188. * Should be called to create batch payload object
  4189. *
  4190. * @method toBatchPayload
  4191. * @param {Array} messages, an array of objects with method (required) and params (optional) fields
  4192. * @returns {Array} batch payload
  4193. */
  4194. Jsonrpc.prototype.toBatchPayload = function (messages) {
  4195. var self = this;
  4196. return messages.map(function (message) {
  4197. return self.toPayload(message.method, message.params);
  4198. });
  4199. };
  4200. module.exports = Jsonrpc;
  4201. },{}],36:[function(require,module,exports){
  4202. /*
  4203. This file is part of web3.js.
  4204. web3.js is free software: you can redistribute it and/or modify
  4205. it under the terms of the GNU Lesser General Public License as published by
  4206. the Free Software Foundation, either version 3 of the License, or
  4207. (at your option) any later version.
  4208. web3.js is distributed in the hope that it will be useful,
  4209. but WITHOUT ANY WARRANTY; without even the implied warranty of
  4210. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  4211. GNU Lesser General Public License for more details.
  4212. You should have received a copy of the GNU Lesser General Public License
  4213. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  4214. */
  4215. /**
  4216. * @file method.js
  4217. * @author Marek Kotewicz <marek@ethdev.com>
  4218. * @date 2015
  4219. */
  4220. var utils = require('../utils/utils');
  4221. var errors = require('./errors');
  4222. var Method = function (options) {
  4223. this.name = options.name;
  4224. this.call = options.call;
  4225. this.params = options.params || 0;
  4226. this.inputFormatter = options.inputFormatter;
  4227. this.outputFormatter = options.outputFormatter;
  4228. this.requestManager = null;
  4229. };
  4230. Method.prototype.setRequestManager = function (rm) {
  4231. this.requestManager = rm;
  4232. };
  4233. /**
  4234. * Should be used to determine name of the jsonrpc method based on arguments
  4235. *
  4236. * @method getCall
  4237. * @param {Array} arguments
  4238. * @return {String} name of jsonrpc method
  4239. */
  4240. Method.prototype.getCall = function (args) {
  4241. return utils.isFunction(this.call) ? this.call(args) : this.call;
  4242. };
  4243. /**
  4244. * Should be used to extract callback from array of arguments. Modifies input param
  4245. *
  4246. * @method extractCallback
  4247. * @param {Array} arguments
  4248. * @return {Function|Null} callback, if exists
  4249. */
  4250. Method.prototype.extractCallback = function (args) {
  4251. if (utils.isFunction(args[args.length - 1])) {
  4252. return args.pop(); // modify the args array!
  4253. }
  4254. };
  4255. /**
  4256. * Should be called to check if the number of arguments is correct
  4257. *
  4258. * @method validateArgs
  4259. * @param {Array} arguments
  4260. * @throws {Error} if it is not
  4261. */
  4262. Method.prototype.validateArgs = function (args) {
  4263. if (args.length !== this.params) {
  4264. throw errors.InvalidNumberOfParams();
  4265. }
  4266. };
  4267. /**
  4268. * Should be called to format input args of method
  4269. *
  4270. * @method formatInput
  4271. * @param {Array}
  4272. * @return {Array}
  4273. */
  4274. Method.prototype.formatInput = function (args) {
  4275. if (!this.inputFormatter) {
  4276. return args;
  4277. }
  4278. return this.inputFormatter.map(function (formatter, index) {
  4279. return formatter ? formatter(args[index]) : args[index];
  4280. });
  4281. };
  4282. /**
  4283. * Should be called to format output(result) of method
  4284. *
  4285. * @method formatOutput
  4286. * @param {Object}
  4287. * @return {Object}
  4288. */
  4289. Method.prototype.formatOutput = function (result) {
  4290. return this.outputFormatter && result ? this.outputFormatter(result) : result;
  4291. };
  4292. /**
  4293. * Should create payload from given input args
  4294. *
  4295. * @method toPayload
  4296. * @param {Array} args
  4297. * @return {Object}
  4298. */
  4299. Method.prototype.toPayload = function (args) {
  4300. var call = this.getCall(args);
  4301. var callback = this.extractCallback(args);
  4302. var params = this.formatInput(args);
  4303. this.validateArgs(params);
  4304. return {
  4305. method: call,
  4306. params: params,
  4307. callback: callback
  4308. };
  4309. };
  4310. Method.prototype.attachToObject = function (obj) {
  4311. var func = this.buildCall();
  4312. func.call = this.call; // TODO!!! that's ugly. filter.js uses it
  4313. var name = this.name.split('.');
  4314. if (name.length > 1) {
  4315. obj[name[0]] = obj[name[0]] || {};
  4316. obj[name[0]][name[1]] = func;
  4317. } else {
  4318. obj[name[0]] = func;
  4319. }
  4320. };
  4321. Method.prototype.buildCall = function() {
  4322. var method = this;
  4323. var send = function () {
  4324. var payload = method.toPayload(Array.prototype.slice.call(arguments));
  4325. if (payload.callback) {
  4326. return method.requestManager.sendAsync(payload, function (err, result) {
  4327. payload.callback(err, method.formatOutput(result));
  4328. });
  4329. }
  4330. return method.formatOutput(method.requestManager.send(payload));
  4331. };
  4332. send.request = this.request.bind(this);
  4333. return send;
  4334. };
  4335. /**
  4336. * Should be called to create pure JSONRPC request which can be used in batch request
  4337. *
  4338. * @method request
  4339. * @param {...} params
  4340. * @return {Object} jsonrpc request
  4341. */
  4342. Method.prototype.request = function () {
  4343. var payload = this.toPayload(Array.prototype.slice.call(arguments));
  4344. payload.format = this.formatOutput.bind(this);
  4345. return payload;
  4346. };
  4347. module.exports = Method;
  4348. },{"../utils/utils":20,"./errors":26}],37:[function(require,module,exports){
  4349. /*
  4350. This file is part of web3.js.
  4351. web3.js is free software: you can redistribute it and/or modify
  4352. it under the terms of the GNU Lesser General Public License as published by
  4353. the Free Software Foundation, either version 3 of the License, or
  4354. (at your option) any later version.
  4355. web3.js is distributed in the hope that it will be useful,
  4356. but WITHOUT ANY WARRANTY; without even the implied warranty of
  4357. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  4358. GNU Lesser General Public License for more details.
  4359. You should have received a copy of the GNU Lesser General Public License
  4360. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  4361. */
  4362. /** @file db.js
  4363. * @authors:
  4364. * Marek Kotewicz <marek@ethdev.com>
  4365. * @date 2015
  4366. */
  4367. var Method = require('../method');
  4368. var DB = function (web3) {
  4369. this._requestManager = web3._requestManager;
  4370. var self = this;
  4371. methods().forEach(function(method) {
  4372. method.attachToObject(self);
  4373. method.setRequestManager(web3._requestManager);
  4374. });
  4375. };
  4376. var methods = function () {
  4377. var putString = new Method({
  4378. name: 'putString',
  4379. call: 'db_putString',
  4380. params: 3
  4381. });
  4382. var getString = new Method({
  4383. name: 'getString',
  4384. call: 'db_getString',
  4385. params: 2
  4386. });
  4387. var putHex = new Method({
  4388. name: 'putHex',
  4389. call: 'db_putHex',
  4390. params: 3
  4391. });
  4392. var getHex = new Method({
  4393. name: 'getHex',
  4394. call: 'db_getHex',
  4395. params: 2
  4396. });
  4397. return [
  4398. putString, getString, putHex, getHex
  4399. ];
  4400. };
  4401. module.exports = DB;
  4402. },{"../method":36}],38:[function(require,module,exports){
  4403. /*
  4404. This file is part of web3.js.
  4405. web3.js is free software: you can redistribute it and/or modify
  4406. it under the terms of the GNU Lesser General Public License as published by
  4407. the Free Software Foundation, either version 3 of the License, or
  4408. (at your option) any later version.
  4409. web3.js is distributed in the hope that it will be useful,
  4410. but WITHOUT ANY WARRANTY; without even the implied warranty of
  4411. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  4412. GNU Lesser General Public License for more details.
  4413. You should have received a copy of the GNU Lesser General Public License
  4414. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  4415. */
  4416. /**
  4417. * @file eth.js
  4418. * @author Marek Kotewicz <marek@ethdev.com>
  4419. * @author Fabian Vogelsteller <fabian@ethdev.com>
  4420. * @date 2015
  4421. */
  4422. "use strict";
  4423. var formatters = require('../formatters');
  4424. var utils = require('../../utils/utils');
  4425. var Method = require('../method');
  4426. var Property = require('../property');
  4427. var c = require('../../utils/config');
  4428. var Contract = require('../contract');
  4429. var watches = require('./watches');
  4430. var Filter = require('../filter');
  4431. var IsSyncing = require('../syncing');
  4432. var namereg = require('../namereg');
  4433. var Iban = require('../iban');
  4434. var transfer = require('../transfer');
  4435. var blockCall = function (args) {
  4436. return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? "eth_getBlockByHash" : "eth_getBlockByNumber";
  4437. };
  4438. var transactionFromBlockCall = function (args) {
  4439. return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getTransactionByBlockHashAndIndex' : 'eth_getTransactionByBlockNumberAndIndex';
  4440. };
  4441. var uncleCall = function (args) {
  4442. return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleByBlockHashAndIndex' : 'eth_getUncleByBlockNumberAndIndex';
  4443. };
  4444. var getBlockTransactionCountCall = function (args) {
  4445. return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getBlockTransactionCountByHash' : 'eth_getBlockTransactionCountByNumber';
  4446. };
  4447. var uncleCountCall = function (args) {
  4448. return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleCountByBlockHash' : 'eth_getUncleCountByBlockNumber';
  4449. };
  4450. function Eth(web3) {
  4451. this._requestManager = web3._requestManager;
  4452. var self = this;
  4453. methods().forEach(function(method) {
  4454. method.attachToObject(self);
  4455. method.setRequestManager(self._requestManager);
  4456. });
  4457. properties().forEach(function(p) {
  4458. p.attachToObject(self);
  4459. p.setRequestManager(self._requestManager);
  4460. });
  4461. this.iban = Iban;
  4462. this.sendIBANTransaction = transfer.bind(null, this);
  4463. }
  4464. Object.defineProperty(Eth.prototype, 'defaultBlock', {
  4465. get: function () {
  4466. return c.defaultBlock;
  4467. },
  4468. set: function (val) {
  4469. c.defaultBlock = val;
  4470. return val;
  4471. }
  4472. });
  4473. Object.defineProperty(Eth.prototype, 'defaultAccount', {
  4474. get: function () {
  4475. return c.defaultAccount;
  4476. },
  4477. set: function (val) {
  4478. c.defaultAccount = val;
  4479. return val;
  4480. }
  4481. });
  4482. var methods = function () {
  4483. var getBalance = new Method({
  4484. name: 'getBalance',
  4485. call: 'eth_getBalance',
  4486. params: 2,
  4487. inputFormatter: [formatters.inputAddressFormatter, formatters.inputDefaultBlockNumberFormatter],
  4488. outputFormatter: formatters.outputBigNumberFormatter
  4489. });
  4490. var getStorageAt = new Method({
  4491. name: 'getStorageAt',
  4492. call: 'eth_getStorageAt',
  4493. params: 3,
  4494. inputFormatter: [null, utils.toHex, formatters.inputDefaultBlockNumberFormatter]
  4495. });
  4496. var getCode = new Method({
  4497. name: 'getCode',
  4498. call: 'eth_getCode',
  4499. params: 2,
  4500. inputFormatter: [formatters.inputAddressFormatter, formatters.inputDefaultBlockNumberFormatter]
  4501. });
  4502. var getBlock = new Method({
  4503. name: 'getBlock',
  4504. call: blockCall,
  4505. params: 2,
  4506. inputFormatter: [formatters.inputBlockNumberFormatter, function (val) { return !!val; }],
  4507. outputFormatter: formatters.outputBlockFormatter
  4508. });
  4509. var getUncle = new Method({
  4510. name: 'getUncle',
  4511. call: uncleCall,
  4512. params: 2,
  4513. inputFormatter: [formatters.inputBlockNumberFormatter, utils.toHex],
  4514. outputFormatter: formatters.outputBlockFormatter,
  4515. });
  4516. var getCompilers = new Method({
  4517. name: 'getCompilers',
  4518. call: 'eth_getCompilers',
  4519. params: 0
  4520. });
  4521. var getBlockTransactionCount = new Method({
  4522. name: 'getBlockTransactionCount',
  4523. call: getBlockTransactionCountCall,
  4524. params: 1,
  4525. inputFormatter: [formatters.inputBlockNumberFormatter],
  4526. outputFormatter: utils.toDecimal
  4527. });
  4528. var getBlockUncleCount = new Method({
  4529. name: 'getBlockUncleCount',
  4530. call: uncleCountCall,
  4531. params: 1,
  4532. inputFormatter: [formatters.inputBlockNumberFormatter],
  4533. outputFormatter: utils.toDecimal
  4534. });
  4535. var getTransaction = new Method({
  4536. name: 'getTransaction',
  4537. call: 'eth_getTransactionByHash',
  4538. params: 1,
  4539. outputFormatter: formatters.outputTransactionFormatter
  4540. });
  4541. var getTransactionFromBlock = new Method({
  4542. name: 'getTransactionFromBlock',
  4543. call: transactionFromBlockCall,
  4544. params: 2,
  4545. inputFormatter: [formatters.inputBlockNumberFormatter, utils.toHex],
  4546. outputFormatter: formatters.outputTransactionFormatter
  4547. });
  4548. var getTransactionReceipt = new Method({
  4549. name: 'getTransactionReceipt',
  4550. call: 'eth_getTransactionReceipt',
  4551. params: 1,
  4552. outputFormatter: formatters.outputTransactionReceiptFormatter
  4553. });
  4554. var getTransactionCount = new Method({
  4555. name: 'getTransactionCount',
  4556. call: 'eth_getTransactionCount',
  4557. params: 2,
  4558. inputFormatter: [null, formatters.inputDefaultBlockNumberFormatter],
  4559. outputFormatter: utils.toDecimal
  4560. });
  4561. var sendRawTransaction = new Method({
  4562. name: 'sendRawTransaction',
  4563. call: 'eth_sendRawTransaction',
  4564. params: 1,
  4565. inputFormatter: [null]
  4566. });
  4567. var sendTransaction = new Method({
  4568. name: 'sendTransaction',
  4569. call: 'eth_sendTransaction',
  4570. params: 1,
  4571. inputFormatter: [formatters.inputTransactionFormatter]
  4572. });
  4573. var sign = new Method({
  4574. name: 'sign',
  4575. call: 'eth_sign',
  4576. params: 2,
  4577. inputFormatter: [formatters.inputAddressFormatter, null]
  4578. });
  4579. var call = new Method({
  4580. name: 'call',
  4581. call: 'eth_call',
  4582. params: 2,
  4583. inputFormatter: [formatters.inputCallFormatter, formatters.inputDefaultBlockNumberFormatter]
  4584. });
  4585. var estimateGas = new Method({
  4586. name: 'estimateGas',
  4587. call: 'eth_estimateGas',
  4588. params: 1,
  4589. inputFormatter: [formatters.inputCallFormatter],
  4590. outputFormatter: utils.toDecimal
  4591. });
  4592. var compileSolidity = new Method({
  4593. name: 'compile.solidity',
  4594. call: 'eth_compileSolidity',
  4595. params: 1
  4596. });
  4597. var compileLLL = new Method({
  4598. name: 'compile.lll',
  4599. call: 'eth_compileLLL',
  4600. params: 1
  4601. });
  4602. var compileSerpent = new Method({
  4603. name: 'compile.serpent',
  4604. call: 'eth_compileSerpent',
  4605. params: 1
  4606. });
  4607. var submitWork = new Method({
  4608. name: 'submitWork',
  4609. call: 'eth_submitWork',
  4610. params: 3
  4611. });
  4612. var getWork = new Method({
  4613. name: 'getWork',
  4614. call: 'eth_getWork',
  4615. params: 0
  4616. });
  4617. return [
  4618. getBalance,
  4619. getStorageAt,
  4620. getCode,
  4621. getBlock,
  4622. getUncle,
  4623. getCompilers,
  4624. getBlockTransactionCount,
  4625. getBlockUncleCount,
  4626. getTransaction,
  4627. getTransactionFromBlock,
  4628. getTransactionReceipt,
  4629. getTransactionCount,
  4630. call,
  4631. estimateGas,
  4632. sendRawTransaction,
  4633. sendTransaction,
  4634. sign,
  4635. compileSolidity,
  4636. compileLLL,
  4637. compileSerpent,
  4638. submitWork,
  4639. getWork
  4640. ];
  4641. };
  4642. var properties = function () {
  4643. return [
  4644. new Property({
  4645. name: 'coinbase',
  4646. getter: 'eth_coinbase'
  4647. }),
  4648. new Property({
  4649. name: 'mining',
  4650. getter: 'eth_mining'
  4651. }),
  4652. new Property({
  4653. name: 'hashrate',
  4654. getter: 'eth_hashrate',
  4655. outputFormatter: utils.toDecimal
  4656. }),
  4657. new Property({
  4658. name: 'syncing',
  4659. getter: 'eth_syncing',
  4660. outputFormatter: formatters.outputSyncingFormatter
  4661. }),
  4662. new Property({
  4663. name: 'gasPrice',
  4664. getter: 'eth_gasPrice',
  4665. outputFormatter: formatters.outputBigNumberFormatter
  4666. }),
  4667. new Property({
  4668. name: 'accounts',
  4669. getter: 'eth_accounts'
  4670. }),
  4671. new Property({
  4672. name: 'blockNumber',
  4673. getter: 'eth_blockNumber',
  4674. outputFormatter: utils.toDecimal
  4675. })
  4676. ];
  4677. };
  4678. Eth.prototype.contract = function (abi) {
  4679. var factory = new Contract(this, abi);
  4680. return factory;
  4681. };
  4682. Eth.prototype.filter = function (fil, callback) {
  4683. return new Filter(this._requestManager, fil, watches.eth(), formatters.outputLogFormatter, callback);
  4684. };
  4685. Eth.prototype.namereg = function () {
  4686. return this.contract(namereg.global.abi).at(namereg.global.address);
  4687. };
  4688. Eth.prototype.icapNamereg = function () {
  4689. return this.contract(namereg.icap.abi).at(namereg.icap.address);
  4690. };
  4691. Eth.prototype.isSyncing = function (callback) {
  4692. return new IsSyncing(this._requestManager, callback);
  4693. };
  4694. module.exports = Eth;
  4695. },{"../../utils/config":18,"../../utils/utils":20,"../contract":25,"../filter":29,"../formatters":30,"../iban":33,"../method":36,"../namereg":43,"../property":44,"../syncing":47,"../transfer":48,"./watches":42}],39:[function(require,module,exports){
  4696. /*
  4697. This file is part of web3.js.
  4698. web3.js is free software: you can redistribute it and/or modify
  4699. it under the terms of the GNU Lesser General Public License as published by
  4700. the Free Software Foundation, either version 3 of the License, or
  4701. (at your option) any later version.
  4702. web3.js is distributed in the hope that it will be useful,
  4703. but WITHOUT ANY WARRANTY; without even the implied warranty of
  4704. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  4705. GNU Lesser General Public License for more details.
  4706. You should have received a copy of the GNU Lesser General Public License
  4707. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  4708. */
  4709. /** @file eth.js
  4710. * @authors:
  4711. * Marek Kotewicz <marek@ethdev.com>
  4712. * @date 2015
  4713. */
  4714. var utils = require('../../utils/utils');
  4715. var Property = require('../property');
  4716. var Net = function (web3) {
  4717. this._requestManager = web3._requestManager;
  4718. var self = this;
  4719. properties().forEach(function(p) {
  4720. p.attachToObject(self);
  4721. p.setRequestManager(web3._requestManager);
  4722. });
  4723. };
  4724. /// @returns an array of objects describing web3.eth api properties
  4725. var properties = function () {
  4726. return [
  4727. new Property({
  4728. name: 'listening',
  4729. getter: 'net_listening'
  4730. }),
  4731. new Property({
  4732. name: 'peerCount',
  4733. getter: 'net_peerCount',
  4734. outputFormatter: utils.toDecimal
  4735. })
  4736. ];
  4737. };
  4738. module.exports = Net;
  4739. },{"../../utils/utils":20,"../property":44}],40:[function(require,module,exports){
  4740. /*
  4741. This file is part of web3.js.
  4742. web3.js is free software: you can redistribute it and/or modify
  4743. it under the terms of the GNU Lesser General Public License as published by
  4744. the Free Software Foundation, either version 3 of the License, or
  4745. (at your option) any later version.
  4746. web3.js is distributed in the hope that it will be useful,
  4747. but WITHOUT ANY WARRANTY; without even the implied warranty of
  4748. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  4749. GNU Lesser General Public License for more details.
  4750. You should have received a copy of the GNU Lesser General Public License
  4751. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  4752. */
  4753. /**
  4754. * @file eth.js
  4755. * @author Marek Kotewicz <marek@ethdev.com>
  4756. * @author Fabian Vogelsteller <fabian@ethdev.com>
  4757. * @date 2015
  4758. */
  4759. "use strict";
  4760. var Method = require('../method');
  4761. var Property = require('../property');
  4762. var formatters = require('../formatters');
  4763. function Personal(web3) {
  4764. this._requestManager = web3._requestManager;
  4765. var self = this;
  4766. methods().forEach(function(method) {
  4767. method.attachToObject(self);
  4768. method.setRequestManager(self._requestManager);
  4769. });
  4770. properties().forEach(function(p) {
  4771. p.attachToObject(self);
  4772. p.setRequestManager(self._requestManager);
  4773. });
  4774. }
  4775. var methods = function () {
  4776. var newAccount = new Method({
  4777. name: 'newAccount',
  4778. call: 'personal_newAccount',
  4779. params: 1,
  4780. inputFormatter: [null]
  4781. });
  4782. var unlockAccount = new Method({
  4783. name: 'unlockAccount',
  4784. call: 'personal_unlockAccount',
  4785. params: 3,
  4786. inputFormatter: [formatters.inputAddressFormatter, null, null]
  4787. });
  4788. var lockAccount = new Method({
  4789. name: 'lockAccount',
  4790. call: 'personal_lockAccount',
  4791. params: 1,
  4792. inputFormatter: [formatters.inputAddressFormatter]
  4793. });
  4794. return [
  4795. newAccount,
  4796. unlockAccount,
  4797. lockAccount
  4798. ];
  4799. };
  4800. var properties = function () {
  4801. return [
  4802. new Property({
  4803. name: 'listAccounts',
  4804. getter: 'personal_listAccounts'
  4805. })
  4806. ];
  4807. };
  4808. module.exports = Personal;
  4809. },{"../formatters":30,"../method":36,"../property":44}],41:[function(require,module,exports){
  4810. /*
  4811. This file is part of web3.js.
  4812. web3.js is free software: you can redistribute it and/or modify
  4813. it under the terms of the GNU Lesser General Public License as published by
  4814. the Free Software Foundation, either version 3 of the License, or
  4815. (at your option) any later version.
  4816. web3.js is distributed in the hope that it will be useful,
  4817. but WITHOUT ANY WARRANTY; without even the implied warranty of
  4818. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  4819. GNU Lesser General Public License for more details.
  4820. You should have received a copy of the GNU Lesser General Public License
  4821. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  4822. */
  4823. /** @file shh.js
  4824. * @authors:
  4825. * Marek Kotewicz <marek@ethdev.com>
  4826. * @date 2015
  4827. */
  4828. var Method = require('../method');
  4829. var formatters = require('../formatters');
  4830. var Filter = require('../filter');
  4831. var watches = require('./watches');
  4832. var Shh = function (web3) {
  4833. this._requestManager = web3._requestManager;
  4834. var self = this;
  4835. methods().forEach(function(method) {
  4836. method.attachToObject(self);
  4837. method.setRequestManager(self._requestManager);
  4838. });
  4839. };
  4840. Shh.prototype.filter = function (fil, callback) {
  4841. return new Filter(this._requestManager, fil, watches.shh(), formatters.outputPostFormatter, callback);
  4842. };
  4843. var methods = function () {
  4844. var post = new Method({
  4845. name: 'post',
  4846. call: 'shh_post',
  4847. params: 1,
  4848. inputFormatter: [formatters.inputPostFormatter]
  4849. });
  4850. var newIdentity = new Method({
  4851. name: 'newIdentity',
  4852. call: 'shh_newIdentity',
  4853. params: 0
  4854. });
  4855. var hasIdentity = new Method({
  4856. name: 'hasIdentity',
  4857. call: 'shh_hasIdentity',
  4858. params: 1
  4859. });
  4860. var newGroup = new Method({
  4861. name: 'newGroup',
  4862. call: 'shh_newGroup',
  4863. params: 0
  4864. });
  4865. var addToGroup = new Method({
  4866. name: 'addToGroup',
  4867. call: 'shh_addToGroup',
  4868. params: 0
  4869. });
  4870. return [
  4871. post,
  4872. newIdentity,
  4873. hasIdentity,
  4874. newGroup,
  4875. addToGroup
  4876. ];
  4877. };
  4878. module.exports = Shh;
  4879. },{"../filter":29,"../formatters":30,"../method":36,"./watches":42}],42:[function(require,module,exports){
  4880. /*
  4881. This file is part of web3.js.
  4882. web3.js is free software: you can redistribute it and/or modify
  4883. it under the terms of the GNU Lesser General Public License as published by
  4884. the Free Software Foundation, either version 3 of the License, or
  4885. (at your option) any later version.
  4886. web3.js is distributed in the hope that it will be useful,
  4887. but WITHOUT ANY WARRANTY; without even the implied warranty of
  4888. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  4889. GNU Lesser General Public License for more details.
  4890. You should have received a copy of the GNU Lesser General Public License
  4891. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  4892. */
  4893. /** @file watches.js
  4894. * @authors:
  4895. * Marek Kotewicz <marek@ethdev.com>
  4896. * @date 2015
  4897. */
  4898. var Method = require('../method');
  4899. /// @returns an array of objects describing web3.eth.filter api methods
  4900. var eth = function () {
  4901. var newFilterCall = function (args) {
  4902. var type = args[0];
  4903. switch(type) {
  4904. case 'latest':
  4905. args.shift();
  4906. this.params = 0;
  4907. return 'eth_newBlockFilter';
  4908. case 'pending':
  4909. args.shift();
  4910. this.params = 0;
  4911. return 'eth_newPendingTransactionFilter';
  4912. default:
  4913. return 'eth_newFilter';
  4914. }
  4915. };
  4916. var newFilter = new Method({
  4917. name: 'newFilter',
  4918. call: newFilterCall,
  4919. params: 1
  4920. });
  4921. var uninstallFilter = new Method({
  4922. name: 'uninstallFilter',
  4923. call: 'eth_uninstallFilter',
  4924. params: 1
  4925. });
  4926. var getLogs = new Method({
  4927. name: 'getLogs',
  4928. call: 'eth_getFilterLogs',
  4929. params: 1
  4930. });
  4931. var poll = new Method({
  4932. name: 'poll',
  4933. call: 'eth_getFilterChanges',
  4934. params: 1
  4935. });
  4936. return [
  4937. newFilter,
  4938. uninstallFilter,
  4939. getLogs,
  4940. poll
  4941. ];
  4942. };
  4943. /// @returns an array of objects describing web3.shh.watch api methods
  4944. var shh = function () {
  4945. var newFilter = new Method({
  4946. name: 'newFilter',
  4947. call: 'shh_newFilter',
  4948. params: 1
  4949. });
  4950. var uninstallFilter = new Method({
  4951. name: 'uninstallFilter',
  4952. call: 'shh_uninstallFilter',
  4953. params: 1
  4954. });
  4955. var getLogs = new Method({
  4956. name: 'getLogs',
  4957. call: 'shh_getMessages',
  4958. params: 1
  4959. });
  4960. var poll = new Method({
  4961. name: 'poll',
  4962. call: 'shh_getFilterChanges',
  4963. params: 1
  4964. });
  4965. return [
  4966. newFilter,
  4967. uninstallFilter,
  4968. getLogs,
  4969. poll
  4970. ];
  4971. };
  4972. module.exports = {
  4973. eth: eth,
  4974. shh: shh
  4975. };
  4976. },{"../method":36}],43:[function(require,module,exports){
  4977. /*
  4978. This file is part of web3.js.
  4979. web3.js is free software: you can redistribute it and/or modify
  4980. it under the terms of the GNU Lesser General Public License as published by
  4981. the Free Software Foundation, either version 3 of the License, or
  4982. (at your option) any later version.
  4983. web3.js is distributed in the hope that it will be useful,
  4984. but WITHOUT ANY WARRANTY; without even the implied warranty of
  4985. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  4986. GNU Lesser General Public License for more details.
  4987. You should have received a copy of the GNU Lesser General Public License
  4988. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  4989. */
  4990. /**
  4991. * @file namereg.js
  4992. * @author Marek Kotewicz <marek@ethdev.com>
  4993. * @date 2015
  4994. */
  4995. var globalRegistrarAbi = require('../contracts/GlobalRegistrar.json');
  4996. var icapRegistrarAbi= require('../contracts/ICAPRegistrar.json');
  4997. var globalNameregAddress = '0xc6d9d2cd449a754c494264e1809c50e34d64562b';
  4998. var icapNameregAddress = '0xa1a111bc074c9cfa781f0c38e63bd51c91b8af00';
  4999. module.exports = {
  5000. global: {
  5001. abi: globalRegistrarAbi,
  5002. address: globalNameregAddress
  5003. },
  5004. icap: {
  5005. abi: icapRegistrarAbi,
  5006. address: icapNameregAddress
  5007. }
  5008. };
  5009. },{"../contracts/GlobalRegistrar.json":1,"../contracts/ICAPRegistrar.json":2}],44:[function(require,module,exports){
  5010. /*
  5011. This file is part of web3.js.
  5012. web3.js is free software: you can redistribute it and/or modify
  5013. it under the terms of the GNU Lesser General Public License as published by
  5014. the Free Software Foundation, either version 3 of the License, or
  5015. (at your option) any later version.
  5016. web3.js is distributed in the hope that it will be useful,
  5017. but WITHOUT ANY WARRANTY; without even the implied warranty of
  5018. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  5019. GNU Lesser General Public License for more details.
  5020. You should have received a copy of the GNU Lesser General Public License
  5021. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  5022. */
  5023. /**
  5024. * @file property.js
  5025. * @author Fabian Vogelsteller <fabian@frozeman.de>
  5026. * @author Marek Kotewicz <marek@ethdev.com>
  5027. * @date 2015
  5028. */
  5029. var utils = require('../utils/utils');
  5030. var Property = function (options) {
  5031. this.name = options.name;
  5032. this.getter = options.getter;
  5033. this.setter = options.setter;
  5034. this.outputFormatter = options.outputFormatter;
  5035. this.inputFormatter = options.inputFormatter;
  5036. this.requestManager = null;
  5037. };
  5038. Property.prototype.setRequestManager = function (rm) {
  5039. this.requestManager = rm;
  5040. };
  5041. /**
  5042. * Should be called to format input args of method
  5043. *
  5044. * @method formatInput
  5045. * @param {Array}
  5046. * @return {Array}
  5047. */
  5048. Property.prototype.formatInput = function (arg) {
  5049. return this.inputFormatter ? this.inputFormatter(arg) : arg;
  5050. };
  5051. /**
  5052. * Should be called to format output(result) of method
  5053. *
  5054. * @method formatOutput
  5055. * @param {Object}
  5056. * @return {Object}
  5057. */
  5058. Property.prototype.formatOutput = function (result) {
  5059. return this.outputFormatter && result !== null ? this.outputFormatter(result) : result;
  5060. };
  5061. /**
  5062. * Should be used to extract callback from array of arguments. Modifies input param
  5063. *
  5064. * @method extractCallback
  5065. * @param {Array} arguments
  5066. * @return {Function|Null} callback, if exists
  5067. */
  5068. Property.prototype.extractCallback = function (args) {
  5069. if (utils.isFunction(args[args.length - 1])) {
  5070. return args.pop(); // modify the args array!
  5071. }
  5072. };
  5073. /**
  5074. * Should attach function to method
  5075. *
  5076. * @method attachToObject
  5077. * @param {Object}
  5078. * @param {Function}
  5079. */
  5080. Property.prototype.attachToObject = function (obj) {
  5081. var proto = {
  5082. get: this.buildGet(),
  5083. enumerable: true
  5084. };
  5085. var names = this.name.split('.');
  5086. var name = names[0];
  5087. if (names.length > 1) {
  5088. obj[names[0]] = obj[names[0]] || {};
  5089. obj = obj[names[0]];
  5090. name = names[1];
  5091. }
  5092. Object.defineProperty(obj, name, proto);
  5093. obj[asyncGetterName(name)] = this.buildAsyncGet();
  5094. };
  5095. var asyncGetterName = function (name) {
  5096. return 'get' + name.charAt(0).toUpperCase() + name.slice(1);
  5097. };
  5098. Property.prototype.buildGet = function () {
  5099. var property = this;
  5100. return function get() {
  5101. return property.formatOutput(property.requestManager.send({
  5102. method: property.getter
  5103. }));
  5104. };
  5105. };
  5106. Property.prototype.buildAsyncGet = function () {
  5107. var property = this;
  5108. var get = function (callback) {
  5109. property.requestManager.sendAsync({
  5110. method: property.getter
  5111. }, function (err, result) {
  5112. callback(err, property.formatOutput(result));
  5113. });
  5114. };
  5115. get.request = this.request.bind(this);
  5116. return get;
  5117. };
  5118. /**
  5119. * Should be called to create pure JSONRPC request which can be used in batch request
  5120. *
  5121. * @method request
  5122. * @param {...} params
  5123. * @return {Object} jsonrpc request
  5124. */
  5125. Property.prototype.request = function () {
  5126. var payload = {
  5127. method: this.getter,
  5128. params: [],
  5129. callback: this.extractCallback(Array.prototype.slice.call(arguments))
  5130. };
  5131. payload.format = this.formatOutput.bind(this);
  5132. return payload;
  5133. };
  5134. module.exports = Property;
  5135. },{"../utils/utils":20}],45:[function(require,module,exports){
  5136. /*
  5137. This file is part of web3.js.
  5138. web3.js is free software: you can redistribute it and/or modify
  5139. it under the terms of the GNU Lesser General Public License as published by
  5140. the Free Software Foundation, either version 3 of the License, or
  5141. (at your option) any later version.
  5142. web3.js is distributed in the hope that it will be useful,
  5143. but WITHOUT ANY WARRANTY; without even the implied warranty of
  5144. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  5145. GNU Lesser General Public License for more details.
  5146. You should have received a copy of the GNU Lesser General Public License
  5147. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  5148. */
  5149. /**
  5150. * @file requestmanager.js
  5151. * @author Jeffrey Wilcke <jeff@ethdev.com>
  5152. * @author Marek Kotewicz <marek@ethdev.com>
  5153. * @author Marian Oancea <marian@ethdev.com>
  5154. * @author Fabian Vogelsteller <fabian@ethdev.com>
  5155. * @author Gav Wood <g@ethdev.com>
  5156. * @date 2014
  5157. */
  5158. var Jsonrpc = require('./jsonrpc');
  5159. var utils = require('../utils/utils');
  5160. var c = require('../utils/config');
  5161. var errors = require('./errors');
  5162. /**
  5163. * It's responsible for passing messages to providers
  5164. * It's also responsible for polling the ethereum node for incoming messages
  5165. * Default poll timeout is 1 second
  5166. * Singleton
  5167. */
  5168. var RequestManager = function (provider) {
  5169. this.provider = provider;
  5170. this.polls = {};
  5171. this.timeout = null;
  5172. };
  5173. /**
  5174. * Should be used to synchronously send request
  5175. *
  5176. * @method send
  5177. * @param {Object} data
  5178. * @return {Object}
  5179. */
  5180. RequestManager.prototype.send = function (data) {
  5181. if (!this.provider) {
  5182. console.error(errors.InvalidProvider());
  5183. return null;
  5184. }
  5185. var payload = Jsonrpc.getInstance().toPayload(data.method, data.params);
  5186. var result = this.provider.send(payload);
  5187. if (!Jsonrpc.getInstance().isValidResponse(result)) {
  5188. throw errors.InvalidResponse(result);
  5189. }
  5190. return result.result;
  5191. };
  5192. /**
  5193. * Should be used to asynchronously send request
  5194. *
  5195. * @method sendAsync
  5196. * @param {Object} data
  5197. * @param {Function} callback
  5198. */
  5199. RequestManager.prototype.sendAsync = function (data, callback) {
  5200. if (!this.provider) {
  5201. return callback(errors.InvalidProvider());
  5202. }
  5203. var payload = Jsonrpc.getInstance().toPayload(data.method, data.params);
  5204. this.provider.sendAsync(payload, function (err, result) {
  5205. if (err) {
  5206. return callback(err);
  5207. }
  5208. if (!Jsonrpc.getInstance().isValidResponse(result)) {
  5209. return callback(errors.InvalidResponse(result));
  5210. }
  5211. callback(null, result.result);
  5212. });
  5213. };
  5214. /**
  5215. * Should be called to asynchronously send batch request
  5216. *
  5217. * @method sendBatch
  5218. * @param {Array} batch data
  5219. * @param {Function} callback
  5220. */
  5221. RequestManager.prototype.sendBatch = function (data, callback) {
  5222. if (!this.provider) {
  5223. return callback(errors.InvalidProvider());
  5224. }
  5225. var payload = Jsonrpc.getInstance().toBatchPayload(data);
  5226. this.provider.sendAsync(payload, function (err, results) {
  5227. if (err) {
  5228. return callback(err);
  5229. }
  5230. if (!utils.isArray(results)) {
  5231. return callback(errors.InvalidResponse(results));
  5232. }
  5233. callback(err, results);
  5234. });
  5235. };
  5236. /**
  5237. * Should be used to set provider of request manager
  5238. *
  5239. * @method setProvider
  5240. * @param {Object}
  5241. */
  5242. RequestManager.prototype.setProvider = function (p) {
  5243. this.provider = p;
  5244. };
  5245. /**
  5246. * Should be used to start polling
  5247. *
  5248. * @method startPolling
  5249. * @param {Object} data
  5250. * @param {Number} pollId
  5251. * @param {Function} callback
  5252. * @param {Function} uninstall
  5253. *
  5254. * @todo cleanup number of params
  5255. */
  5256. RequestManager.prototype.startPolling = function (data, pollId, callback, uninstall) {
  5257. this.polls[pollId] = {data: data, id: pollId, callback: callback, uninstall: uninstall};
  5258. // start polling
  5259. if (!this.timeout) {
  5260. this.poll();
  5261. }
  5262. };
  5263. /**
  5264. * Should be used to stop polling for filter with given id
  5265. *
  5266. * @method stopPolling
  5267. * @param {Number} pollId
  5268. */
  5269. RequestManager.prototype.stopPolling = function (pollId) {
  5270. delete this.polls[pollId];
  5271. // stop polling
  5272. if(Object.keys(this.polls).length === 0 && this.timeout) {
  5273. clearTimeout(this.timeout);
  5274. this.timeout = null;
  5275. }
  5276. };
  5277. /**
  5278. * Should be called to reset the polling mechanism of the request manager
  5279. *
  5280. * @method reset
  5281. */
  5282. RequestManager.prototype.reset = function (keepIsSyncing) {
  5283. /*jshint maxcomplexity:5 */
  5284. for (var key in this.polls) {
  5285. // remove all polls, except sync polls,
  5286. // they need to be removed manually by calling syncing.stopWatching()
  5287. if(!keepIsSyncing || key.indexOf('syncPoll_') === -1) {
  5288. this.polls[key].uninstall();
  5289. delete this.polls[key];
  5290. }
  5291. }
  5292. // stop polling
  5293. if(Object.keys(this.polls).length === 0 && this.timeout) {
  5294. clearTimeout(this.timeout);
  5295. this.timeout = null;
  5296. }
  5297. };
  5298. /**
  5299. * Should be called to poll for changes on filter with given id
  5300. *
  5301. * @method poll
  5302. */
  5303. RequestManager.prototype.poll = function () {
  5304. /*jshint maxcomplexity: 6 */
  5305. this.timeout = setTimeout(this.poll.bind(this), c.ETH_POLLING_TIMEOUT);
  5306. if (Object.keys(this.polls).length === 0) {
  5307. return;
  5308. }
  5309. if (!this.provider) {
  5310. console.error(errors.InvalidProvider());
  5311. return;
  5312. }
  5313. var pollsData = [];
  5314. var pollsIds = [];
  5315. for (var key in this.polls) {
  5316. pollsData.push(this.polls[key].data);
  5317. pollsIds.push(key);
  5318. }
  5319. if (pollsData.length === 0) {
  5320. return;
  5321. }
  5322. var payload = Jsonrpc.getInstance().toBatchPayload(pollsData);
  5323. // map the request id to they poll id
  5324. var pollsIdMap = {};
  5325. payload.forEach(function(load, index){
  5326. pollsIdMap[load.id] = pollsIds[index];
  5327. });
  5328. var self = this;
  5329. this.provider.sendAsync(payload, function (error, results) {
  5330. // TODO: console log?
  5331. if (error) {
  5332. return;
  5333. }
  5334. if (!utils.isArray(results)) {
  5335. throw errors.InvalidResponse(results);
  5336. }
  5337. results.map(function (result) {
  5338. var id = pollsIdMap[result.id];
  5339. // make sure the filter is still installed after arrival of the request
  5340. if (self.polls[id]) {
  5341. result.callback = self.polls[id].callback;
  5342. return result;
  5343. } else
  5344. return false;
  5345. }).filter(function (result) {
  5346. return !!result;
  5347. }).filter(function (result) {
  5348. var valid = Jsonrpc.getInstance().isValidResponse(result);
  5349. if (!valid) {
  5350. result.callback(errors.InvalidResponse(result));
  5351. }
  5352. return valid;
  5353. }).forEach(function (result) {
  5354. result.callback(null, result.result);
  5355. });
  5356. });
  5357. };
  5358. module.exports = RequestManager;
  5359. },{"../utils/config":18,"../utils/utils":20,"./errors":26,"./jsonrpc":35}],46:[function(require,module,exports){
  5360. var Settings = function () {
  5361. this.defaultBlock = 'latest';
  5362. this.defaultAccount = undefined;
  5363. };
  5364. module.exports = Settings;
  5365. },{}],47:[function(require,module,exports){
  5366. /*
  5367. This file is part of web3.js.
  5368. web3.js is free software: you can redistribute it and/or modify
  5369. it under the terms of the GNU Lesser General Public License as published by
  5370. the Free Software Foundation, either version 3 of the License, or
  5371. (at your option) any later version.
  5372. web3.js is distributed in the hope that it will be useful,
  5373. but WITHOUT ANY WARRANTY; without even the implied warranty of
  5374. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  5375. GNU Lesser General Public License for more details.
  5376. You should have received a copy of the GNU Lesser General Public License
  5377. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  5378. */
  5379. /** @file syncing.js
  5380. * @authors:
  5381. * Fabian Vogelsteller <fabian@ethdev.com>
  5382. * @date 2015
  5383. */
  5384. var formatters = require('./formatters');
  5385. var utils = require('../utils/utils');
  5386. var count = 1;
  5387. /**
  5388. Adds the callback and sets up the methods, to iterate over the results.
  5389. @method pollSyncing
  5390. @param {Object} self
  5391. */
  5392. var pollSyncing = function(self) {
  5393. var onMessage = function (error, sync) {
  5394. if (error) {
  5395. return self.callbacks.forEach(function (callback) {
  5396. callback(error);
  5397. });
  5398. }
  5399. if(utils.isObject(sync) && sync.startingBlock)
  5400. sync = formatters.outputSyncingFormatter(sync);
  5401. self.callbacks.forEach(function (callback) {
  5402. if (self.lastSyncState !== sync) {
  5403. // call the callback with true first so the app can stop anything, before receiving the sync data
  5404. if(!self.lastSyncState && utils.isObject(sync))
  5405. callback(null, true);
  5406. // call on the next CPU cycle, so the actions of the sync stop can be processes first
  5407. setTimeout(function() {
  5408. callback(null, sync);
  5409. }, 0);
  5410. self.lastSyncState = sync;
  5411. }
  5412. });
  5413. };
  5414. self.requestManager.startPolling({
  5415. method: 'eth_syncing',
  5416. params: [],
  5417. }, self.pollId, onMessage, self.stopWatching.bind(self));
  5418. };
  5419. var IsSyncing = function (requestManager, callback) {
  5420. this.requestManager = requestManager;
  5421. this.pollId = 'syncPoll_'+ count++;
  5422. this.callbacks = [];
  5423. this.addCallback(callback);
  5424. this.lastSyncState = false;
  5425. pollSyncing(this);
  5426. return this;
  5427. };
  5428. IsSyncing.prototype.addCallback = function (callback) {
  5429. if(callback)
  5430. this.callbacks.push(callback);
  5431. return this;
  5432. };
  5433. IsSyncing.prototype.stopWatching = function () {
  5434. this.requestManager.stopPolling(this.pollId);
  5435. this.callbacks = [];
  5436. };
  5437. module.exports = IsSyncing;
  5438. },{"../utils/utils":20,"./formatters":30}],48:[function(require,module,exports){
  5439. /*
  5440. This file is part of web3.js.
  5441. web3.js is free software: you can redistribute it and/or modify
  5442. it under the terms of the GNU Lesser General Public License as published by
  5443. the Free Software Foundation, either version 3 of the License, or
  5444. (at your option) any later version.
  5445. web3.js is distributed in the hope that it will be useful,
  5446. but WITHOUT ANY WARRANTY; without even the implied warranty of
  5447. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  5448. GNU Lesser General Public License for more details.
  5449. You should have received a copy of the GNU Lesser General Public License
  5450. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  5451. */
  5452. /**
  5453. * @file transfer.js
  5454. * @author Marek Kotewicz <marek@ethdev.com>
  5455. * @date 2015
  5456. */
  5457. var Iban = require('./iban');
  5458. var exchangeAbi = require('../contracts/SmartExchange.json');
  5459. /**
  5460. * Should be used to make Iban transfer
  5461. *
  5462. * @method transfer
  5463. * @param {String} from
  5464. * @param {String} to iban
  5465. * @param {Value} value to be tranfered
  5466. * @param {Function} callback, callback
  5467. */
  5468. var transfer = function (eth, from, to, value, callback) {
  5469. var iban = new Iban(to);
  5470. if (!iban.isValid()) {
  5471. throw new Error('invalid iban address');
  5472. }
  5473. if (iban.isDirect()) {
  5474. return transferToAddress(eth, from, iban.address(), value, callback);
  5475. }
  5476. if (!callback) {
  5477. var address = eth.icapNamereg().addr(iban.institution());
  5478. return deposit(eth, from, address, value, iban.client());
  5479. }
  5480. eth.icapNamereg().addr(iban.institution(), function (err, address) {
  5481. return deposit(eth, from, address, value, iban.client(), callback);
  5482. });
  5483. };
  5484. /**
  5485. * Should be used to transfer funds to certain address
  5486. *
  5487. * @method transferToAddress
  5488. * @param {String} from
  5489. * @param {String} to
  5490. * @param {Value} value to be tranfered
  5491. * @param {Function} callback, callback
  5492. */
  5493. var transferToAddress = function (eth, from, to, value, callback) {
  5494. return eth.sendTransaction({
  5495. address: to,
  5496. from: from,
  5497. value: value
  5498. }, callback);
  5499. };
  5500. /**
  5501. * Should be used to deposit funds to generic Exchange contract (must implement deposit(bytes32) method!)
  5502. *
  5503. * @method deposit
  5504. * @param {String} from
  5505. * @param {String} to
  5506. * @param {Value} value to be transfered
  5507. * @param {String} client unique identifier
  5508. * @param {Function} callback, callback
  5509. */
  5510. var deposit = function (eth, from, to, value, client, callback) {
  5511. var abi = exchangeAbi;
  5512. return eth.contract(abi).at(to).deposit(client, {
  5513. from: from,
  5514. value: value
  5515. }, callback);
  5516. };
  5517. module.exports = transfer;
  5518. },{"../contracts/SmartExchange.json":3,"./iban":33}],49:[function(require,module,exports){
  5519. },{}],50:[function(require,module,exports){
  5520. ;(function (root, factory, undef) {
  5521. if (typeof exports === "object") {
  5522. // CommonJS
  5523. module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core"));
  5524. }
  5525. else if (typeof define === "function" && define.amd) {
  5526. // AMD
  5527. define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
  5528. }
  5529. else {
  5530. // Global (browser)
  5531. factory(root.CryptoJS);
  5532. }
  5533. }(this, function (CryptoJS) {
  5534. (function () {
  5535. // Shortcuts
  5536. var C = CryptoJS;
  5537. var C_lib = C.lib;
  5538. var BlockCipher = C_lib.BlockCipher;
  5539. var C_algo = C.algo;
  5540. // Lookup tables
  5541. var SBOX = [];
  5542. var INV_SBOX = [];
  5543. var SUB_MIX_0 = [];
  5544. var SUB_MIX_1 = [];
  5545. var SUB_MIX_2 = [];
  5546. var SUB_MIX_3 = [];
  5547. var INV_SUB_MIX_0 = [];
  5548. var INV_SUB_MIX_1 = [];
  5549. var INV_SUB_MIX_2 = [];
  5550. var INV_SUB_MIX_3 = [];
  5551. // Compute lookup tables
  5552. (function () {
  5553. // Compute double table
  5554. var d = [];
  5555. for (var i = 0; i < 256; i++) {
  5556. if (i < 128) {
  5557. d[i] = i << 1;
  5558. } else {
  5559. d[i] = (i << 1) ^ 0x11b;
  5560. }
  5561. }
  5562. // Walk GF(2^8)
  5563. var x = 0;
  5564. var xi = 0;
  5565. for (var i = 0; i < 256; i++) {
  5566. // Compute sbox
  5567. var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
  5568. sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
  5569. SBOX[x] = sx;
  5570. INV_SBOX[sx] = x;
  5571. // Compute multiplication
  5572. var x2 = d[x];
  5573. var x4 = d[x2];
  5574. var x8 = d[x4];
  5575. // Compute sub bytes, mix columns tables
  5576. var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
  5577. SUB_MIX_0[x] = (t << 24) | (t >>> 8);
  5578. SUB_MIX_1[x] = (t << 16) | (t >>> 16);
  5579. SUB_MIX_2[x] = (t << 8) | (t >>> 24);
  5580. SUB_MIX_3[x] = t;
  5581. // Compute inv sub bytes, inv mix columns tables
  5582. var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
  5583. INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
  5584. INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
  5585. INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24);
  5586. INV_SUB_MIX_3[sx] = t;
  5587. // Compute next counter
  5588. if (!x) {
  5589. x = xi = 1;
  5590. } else {
  5591. x = x2 ^ d[d[d[x8 ^ x2]]];
  5592. xi ^= d[d[xi]];
  5593. }
  5594. }
  5595. }());
  5596. // Precomputed Rcon lookup
  5597. var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
  5598. /**
  5599. * AES block cipher algorithm.
  5600. */
  5601. var AES = C_algo.AES = BlockCipher.extend({
  5602. _doReset: function () {
  5603. // Shortcuts
  5604. var key = this._key;
  5605. var keyWords = key.words;
  5606. var keySize = key.sigBytes / 4;
  5607. // Compute number of rounds
  5608. var nRounds = this._nRounds = keySize + 6
  5609. // Compute number of key schedule rows
  5610. var ksRows = (nRounds + 1) * 4;
  5611. // Compute key schedule
  5612. var keySchedule = this._keySchedule = [];
  5613. for (var ksRow = 0; ksRow < ksRows; ksRow++) {
  5614. if (ksRow < keySize) {
  5615. keySchedule[ksRow] = keyWords[ksRow];
  5616. } else {
  5617. var t = keySchedule[ksRow - 1];
  5618. if (!(ksRow % keySize)) {
  5619. // Rot word
  5620. t = (t << 8) | (t >>> 24);
  5621. // Sub word
  5622. t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
  5623. // Mix Rcon
  5624. t ^= RCON[(ksRow / keySize) | 0] << 24;
  5625. } else if (keySize > 6 && ksRow % keySize == 4) {
  5626. // Sub word
  5627. t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
  5628. }
  5629. keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
  5630. }
  5631. }
  5632. // Compute inv key schedule
  5633. var invKeySchedule = this._invKeySchedule = [];
  5634. for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  5635. var ksRow = ksRows - invKsRow;
  5636. if (invKsRow % 4) {
  5637. var t = keySchedule[ksRow];
  5638. } else {
  5639. var t = keySchedule[ksRow - 4];
  5640. }
  5641. if (invKsRow < 4 || ksRow <= 4) {
  5642. invKeySchedule[invKsRow] = t;
  5643. } else {
  5644. invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
  5645. INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]];
  5646. }
  5647. }
  5648. },
  5649. encryptBlock: function (M, offset) {
  5650. this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
  5651. },
  5652. decryptBlock: function (M, offset) {
  5653. // Swap 2nd and 4th rows
  5654. var t = M[offset + 1];
  5655. M[offset + 1] = M[offset + 3];
  5656. M[offset + 3] = t;
  5657. this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
  5658. // Inv swap 2nd and 4th rows
  5659. var t = M[offset + 1];
  5660. M[offset + 1] = M[offset + 3];
  5661. M[offset + 3] = t;
  5662. },
  5663. _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
  5664. // Shortcut
  5665. var nRounds = this._nRounds;
  5666. // Get input, add round key
  5667. var s0 = M[offset] ^ keySchedule[0];
  5668. var s1 = M[offset + 1] ^ keySchedule[1];
  5669. var s2 = M[offset + 2] ^ keySchedule[2];
  5670. var s3 = M[offset + 3] ^ keySchedule[3];
  5671. // Key schedule row counter
  5672. var ksRow = 4;
  5673. // Rounds
  5674. for (var round = 1; round < nRounds; round++) {
  5675. // Shift rows, sub bytes, mix columns, add round key
  5676. var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++];
  5677. var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++];
  5678. var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++];
  5679. var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++];
  5680. // Update state
  5681. s0 = t0;
  5682. s1 = t1;
  5683. s2 = t2;
  5684. s3 = t3;
  5685. }
  5686. // Shift rows, sub bytes, add round key
  5687. var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
  5688. var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
  5689. var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
  5690. var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
  5691. // Set output
  5692. M[offset] = t0;
  5693. M[offset + 1] = t1;
  5694. M[offset + 2] = t2;
  5695. M[offset + 3] = t3;
  5696. },
  5697. keySize: 256/32
  5698. });
  5699. /**
  5700. * Shortcut functions to the cipher's object interface.
  5701. *
  5702. * @example
  5703. *
  5704. * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
  5705. * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);
  5706. */
  5707. C.AES = BlockCipher._createHelper(AES);
  5708. }());
  5709. return CryptoJS.AES;
  5710. }));
  5711. },{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],51:[function(require,module,exports){
  5712. ;(function (root, factory) {
  5713. if (typeof exports === "object") {
  5714. // CommonJS
  5715. module.exports = exports = factory(require("./core"));
  5716. }
  5717. else if (typeof define === "function" && define.amd) {
  5718. // AMD
  5719. define(["./core"], factory);
  5720. }
  5721. else {
  5722. // Global (browser)
  5723. factory(root.CryptoJS);
  5724. }
  5725. }(this, function (CryptoJS) {
  5726. /**
  5727. * Cipher core components.
  5728. */
  5729. CryptoJS.lib.Cipher || (function (undefined) {
  5730. // Shortcuts
  5731. var C = CryptoJS;
  5732. var C_lib = C.lib;
  5733. var Base = C_lib.Base;
  5734. var WordArray = C_lib.WordArray;
  5735. var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
  5736. var C_enc = C.enc;
  5737. var Utf8 = C_enc.Utf8;
  5738. var Base64 = C_enc.Base64;
  5739. var C_algo = C.algo;
  5740. var EvpKDF = C_algo.EvpKDF;
  5741. /**
  5742. * Abstract base cipher template.
  5743. *
  5744. * @property {number} keySize This cipher's key size. Default: 4 (128 bits)
  5745. * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
  5746. * @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
  5747. * @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
  5748. */
  5749. var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
  5750. /**
  5751. * Configuration options.
  5752. *
  5753. * @property {WordArray} iv The IV to use for this operation.
  5754. */
  5755. cfg: Base.extend(),
  5756. /**
  5757. * Creates this cipher in encryption mode.
  5758. *
  5759. * @param {WordArray} key The key.
  5760. * @param {Object} cfg (Optional) The configuration options to use for this operation.
  5761. *
  5762. * @return {Cipher} A cipher instance.
  5763. *
  5764. * @static
  5765. *
  5766. * @example
  5767. *
  5768. * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
  5769. */
  5770. createEncryptor: function (key, cfg) {
  5771. return this.create(this._ENC_XFORM_MODE, key, cfg);
  5772. },
  5773. /**
  5774. * Creates this cipher in decryption mode.
  5775. *
  5776. * @param {WordArray} key The key.
  5777. * @param {Object} cfg (Optional) The configuration options to use for this operation.
  5778. *
  5779. * @return {Cipher} A cipher instance.
  5780. *
  5781. * @static
  5782. *
  5783. * @example
  5784. *
  5785. * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
  5786. */
  5787. createDecryptor: function (key, cfg) {
  5788. return this.create(this._DEC_XFORM_MODE, key, cfg);
  5789. },
  5790. /**
  5791. * Initializes a newly created cipher.
  5792. *
  5793. * @param {number} xformMode Either the encryption or decryption transormation mode constant.
  5794. * @param {WordArray} key The key.
  5795. * @param {Object} cfg (Optional) The configuration options to use for this operation.
  5796. *
  5797. * @example
  5798. *
  5799. * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
  5800. */
  5801. init: function (xformMode, key, cfg) {
  5802. // Apply config defaults
  5803. this.cfg = this.cfg.extend(cfg);
  5804. // Store transform mode and key
  5805. this._xformMode = xformMode;
  5806. this._key = key;
  5807. // Set initial values
  5808. this.reset();
  5809. },
  5810. /**
  5811. * Resets this cipher to its initial state.
  5812. *
  5813. * @example
  5814. *
  5815. * cipher.reset();
  5816. */
  5817. reset: function () {
  5818. // Reset data buffer
  5819. BufferedBlockAlgorithm.reset.call(this);
  5820. // Perform concrete-cipher logic
  5821. this._doReset();
  5822. },
  5823. /**
  5824. * Adds data to be encrypted or decrypted.
  5825. *
  5826. * @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
  5827. *
  5828. * @return {WordArray} The data after processing.
  5829. *
  5830. * @example
  5831. *
  5832. * var encrypted = cipher.process('data');
  5833. * var encrypted = cipher.process(wordArray);
  5834. */
  5835. process: function (dataUpdate) {
  5836. // Append
  5837. this._append(dataUpdate);
  5838. // Process available blocks
  5839. return this._process();
  5840. },
  5841. /**
  5842. * Finalizes the encryption or decryption process.
  5843. * Note that the finalize operation is effectively a destructive, read-once operation.
  5844. *
  5845. * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
  5846. *
  5847. * @return {WordArray} The data after final processing.
  5848. *
  5849. * @example
  5850. *
  5851. * var encrypted = cipher.finalize();
  5852. * var encrypted = cipher.finalize('data');
  5853. * var encrypted = cipher.finalize(wordArray);
  5854. */
  5855. finalize: function (dataUpdate) {
  5856. // Final data update
  5857. if (dataUpdate) {
  5858. this._append(dataUpdate);
  5859. }
  5860. // Perform concrete-cipher logic
  5861. var finalProcessedData = this._doFinalize();
  5862. return finalProcessedData;
  5863. },
  5864. keySize: 128/32,
  5865. ivSize: 128/32,
  5866. _ENC_XFORM_MODE: 1,
  5867. _DEC_XFORM_MODE: 2,
  5868. /**
  5869. * Creates shortcut functions to a cipher's object interface.
  5870. *
  5871. * @param {Cipher} cipher The cipher to create a helper for.
  5872. *
  5873. * @return {Object} An object with encrypt and decrypt shortcut functions.
  5874. *
  5875. * @static
  5876. *
  5877. * @example
  5878. *
  5879. * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
  5880. */
  5881. _createHelper: (function () {
  5882. function selectCipherStrategy(key) {
  5883. if (typeof key == 'string') {
  5884. return PasswordBasedCipher;
  5885. } else {
  5886. return SerializableCipher;
  5887. }
  5888. }
  5889. return function (cipher) {
  5890. return {
  5891. encrypt: function (message, key, cfg) {
  5892. return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
  5893. },
  5894. decrypt: function (ciphertext, key, cfg) {
  5895. return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
  5896. }
  5897. };
  5898. };
  5899. }())
  5900. });
  5901. /**
  5902. * Abstract base stream cipher template.
  5903. *
  5904. * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits)
  5905. */
  5906. var StreamCipher = C_lib.StreamCipher = Cipher.extend({
  5907. _doFinalize: function () {
  5908. // Process partial blocks
  5909. var finalProcessedBlocks = this._process(!!'flush');
  5910. return finalProcessedBlocks;
  5911. },
  5912. blockSize: 1
  5913. });
  5914. /**
  5915. * Mode namespace.
  5916. */
  5917. var C_mode = C.mode = {};
  5918. /**
  5919. * Abstract base block cipher mode template.
  5920. */
  5921. var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
  5922. /**
  5923. * Creates this mode for encryption.
  5924. *
  5925. * @param {Cipher} cipher A block cipher instance.
  5926. * @param {Array} iv The IV words.
  5927. *
  5928. * @static
  5929. *
  5930. * @example
  5931. *
  5932. * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
  5933. */
  5934. createEncryptor: function (cipher, iv) {
  5935. return this.Encryptor.create(cipher, iv);
  5936. },
  5937. /**
  5938. * Creates this mode for decryption.
  5939. *
  5940. * @param {Cipher} cipher A block cipher instance.
  5941. * @param {Array} iv The IV words.
  5942. *
  5943. * @static
  5944. *
  5945. * @example
  5946. *
  5947. * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
  5948. */
  5949. createDecryptor: function (cipher, iv) {
  5950. return this.Decryptor.create(cipher, iv);
  5951. },
  5952. /**
  5953. * Initializes a newly created mode.
  5954. *
  5955. * @param {Cipher} cipher A block cipher instance.
  5956. * @param {Array} iv The IV words.
  5957. *
  5958. * @example
  5959. *
  5960. * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
  5961. */
  5962. init: function (cipher, iv) {
  5963. this._cipher = cipher;
  5964. this._iv = iv;
  5965. }
  5966. });
  5967. /**
  5968. * Cipher Block Chaining mode.
  5969. */
  5970. var CBC = C_mode.CBC = (function () {
  5971. /**
  5972. * Abstract base CBC mode.
  5973. */
  5974. var CBC = BlockCipherMode.extend();
  5975. /**
  5976. * CBC encryptor.
  5977. */
  5978. CBC.Encryptor = CBC.extend({
  5979. /**
  5980. * Processes the data block at offset.
  5981. *
  5982. * @param {Array} words The data words to operate on.
  5983. * @param {number} offset The offset where the block starts.
  5984. *
  5985. * @example
  5986. *
  5987. * mode.processBlock(data.words, offset);
  5988. */
  5989. processBlock: function (words, offset) {
  5990. // Shortcuts
  5991. var cipher = this._cipher;
  5992. var blockSize = cipher.blockSize;
  5993. // XOR and encrypt
  5994. xorBlock.call(this, words, offset, blockSize);
  5995. cipher.encryptBlock(words, offset);
  5996. // Remember this block to use with next block
  5997. this._prevBlock = words.slice(offset, offset + blockSize);
  5998. }
  5999. });
  6000. /**
  6001. * CBC decryptor.
  6002. */
  6003. CBC.Decryptor = CBC.extend({
  6004. /**
  6005. * Processes the data block at offset.
  6006. *
  6007. * @param {Array} words The data words to operate on.
  6008. * @param {number} offset The offset where the block starts.
  6009. *
  6010. * @example
  6011. *
  6012. * mode.processBlock(data.words, offset);
  6013. */
  6014. processBlock: function (words, offset) {
  6015. // Shortcuts
  6016. var cipher = this._cipher;
  6017. var blockSize = cipher.blockSize;
  6018. // Remember this block to use with next block
  6019. var thisBlock = words.slice(offset, offset + blockSize);
  6020. // Decrypt and XOR
  6021. cipher.decryptBlock(words, offset);
  6022. xorBlock.call(this, words, offset, blockSize);
  6023. // This block becomes the previous block
  6024. this._prevBlock = thisBlock;
  6025. }
  6026. });
  6027. function xorBlock(words, offset, blockSize) {
  6028. // Shortcut
  6029. var iv = this._iv;
  6030. // Choose mixing block
  6031. if (iv) {
  6032. var block = iv;
  6033. // Remove IV for subsequent blocks
  6034. this._iv = undefined;
  6035. } else {
  6036. var block = this._prevBlock;
  6037. }
  6038. // XOR blocks
  6039. for (var i = 0; i < blockSize; i++) {
  6040. words[offset + i] ^= block[i];
  6041. }
  6042. }
  6043. return CBC;
  6044. }());
  6045. /**
  6046. * Padding namespace.
  6047. */
  6048. var C_pad = C.pad = {};
  6049. /**
  6050. * PKCS #5/7 padding strategy.
  6051. */
  6052. var Pkcs7 = C_pad.Pkcs7 = {
  6053. /**
  6054. * Pads data using the algorithm defined in PKCS #5/7.
  6055. *
  6056. * @param {WordArray} data The data to pad.
  6057. * @param {number} blockSize The multiple that the data should be padded to.
  6058. *
  6059. * @static
  6060. *
  6061. * @example
  6062. *
  6063. * CryptoJS.pad.Pkcs7.pad(wordArray, 4);
  6064. */
  6065. pad: function (data, blockSize) {
  6066. // Shortcut
  6067. var blockSizeBytes = blockSize * 4;
  6068. // Count padding bytes
  6069. var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
  6070. // Create padding word
  6071. var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes;
  6072. // Create padding
  6073. var paddingWords = [];
  6074. for (var i = 0; i < nPaddingBytes; i += 4) {
  6075. paddingWords.push(paddingWord);
  6076. }
  6077. var padding = WordArray.create(paddingWords, nPaddingBytes);
  6078. // Add padding
  6079. data.concat(padding);
  6080. },
  6081. /**
  6082. * Unpads data that had been padded using the algorithm defined in PKCS #5/7.
  6083. *
  6084. * @param {WordArray} data The data to unpad.
  6085. *
  6086. * @static
  6087. *
  6088. * @example
  6089. *
  6090. * CryptoJS.pad.Pkcs7.unpad(wordArray);
  6091. */
  6092. unpad: function (data) {
  6093. // Get number of padding bytes from last byte
  6094. var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
  6095. // Remove padding
  6096. data.sigBytes -= nPaddingBytes;
  6097. }
  6098. };
  6099. /**
  6100. * Abstract base block cipher template.
  6101. *
  6102. * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
  6103. */
  6104. var BlockCipher = C_lib.BlockCipher = Cipher.extend({
  6105. /**
  6106. * Configuration options.
  6107. *
  6108. * @property {Mode} mode The block mode to use. Default: CBC
  6109. * @property {Padding} padding The padding strategy to use. Default: Pkcs7
  6110. */
  6111. cfg: Cipher.cfg.extend({
  6112. mode: CBC,
  6113. padding: Pkcs7
  6114. }),
  6115. reset: function () {
  6116. // Reset cipher
  6117. Cipher.reset.call(this);
  6118. // Shortcuts
  6119. var cfg = this.cfg;
  6120. var iv = cfg.iv;
  6121. var mode = cfg.mode;
  6122. // Reset block mode
  6123. if (this._xformMode == this._ENC_XFORM_MODE) {
  6124. var modeCreator = mode.createEncryptor;
  6125. } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
  6126. var modeCreator = mode.createDecryptor;
  6127. // Keep at least one block in the buffer for unpadding
  6128. this._minBufferSize = 1;
  6129. }
  6130. this._mode = modeCreator.call(mode, this, iv && iv.words);
  6131. },
  6132. _doProcessBlock: function (words, offset) {
  6133. this._mode.processBlock(words, offset);
  6134. },
  6135. _doFinalize: function () {
  6136. // Shortcut
  6137. var padding = this.cfg.padding;
  6138. // Finalize
  6139. if (this._xformMode == this._ENC_XFORM_MODE) {
  6140. // Pad data
  6141. padding.pad(this._data, this.blockSize);
  6142. // Process final blocks
  6143. var finalProcessedBlocks = this._process(!!'flush');
  6144. } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
  6145. // Process final blocks
  6146. var finalProcessedBlocks = this._process(!!'flush');
  6147. // Unpad data
  6148. padding.unpad(finalProcessedBlocks);
  6149. }
  6150. return finalProcessedBlocks;
  6151. },
  6152. blockSize: 128/32
  6153. });
  6154. /**
  6155. * A collection of cipher parameters.
  6156. *
  6157. * @property {WordArray} ciphertext The raw ciphertext.
  6158. * @property {WordArray} key The key to this ciphertext.
  6159. * @property {WordArray} iv The IV used in the ciphering operation.
  6160. * @property {WordArray} salt The salt used with a key derivation function.
  6161. * @property {Cipher} algorithm The cipher algorithm.
  6162. * @property {Mode} mode The block mode used in the ciphering operation.
  6163. * @property {Padding} padding The padding scheme used in the ciphering operation.
  6164. * @property {number} blockSize The block size of the cipher.
  6165. * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string.
  6166. */
  6167. var CipherParams = C_lib.CipherParams = Base.extend({
  6168. /**
  6169. * Initializes a newly created cipher params object.
  6170. *
  6171. * @param {Object} cipherParams An object with any of the possible cipher parameters.
  6172. *
  6173. * @example
  6174. *
  6175. * var cipherParams = CryptoJS.lib.CipherParams.create({
  6176. * ciphertext: ciphertextWordArray,
  6177. * key: keyWordArray,
  6178. * iv: ivWordArray,
  6179. * salt: saltWordArray,
  6180. * algorithm: CryptoJS.algo.AES,
  6181. * mode: CryptoJS.mode.CBC,
  6182. * padding: CryptoJS.pad.PKCS7,
  6183. * blockSize: 4,
  6184. * formatter: CryptoJS.format.OpenSSL
  6185. * });
  6186. */
  6187. init: function (cipherParams) {
  6188. this.mixIn(cipherParams);
  6189. },
  6190. /**
  6191. * Converts this cipher params object to a string.
  6192. *
  6193. * @param {Format} formatter (Optional) The formatting strategy to use.
  6194. *
  6195. * @return {string} The stringified cipher params.
  6196. *
  6197. * @throws Error If neither the formatter nor the default formatter is set.
  6198. *
  6199. * @example
  6200. *
  6201. * var string = cipherParams + '';
  6202. * var string = cipherParams.toString();
  6203. * var string = cipherParams.toString(CryptoJS.format.OpenSSL);
  6204. */
  6205. toString: function (formatter) {
  6206. return (formatter || this.formatter).stringify(this);
  6207. }
  6208. });
  6209. /**
  6210. * Format namespace.
  6211. */
  6212. var C_format = C.format = {};
  6213. /**
  6214. * OpenSSL formatting strategy.
  6215. */
  6216. var OpenSSLFormatter = C_format.OpenSSL = {
  6217. /**
  6218. * Converts a cipher params object to an OpenSSL-compatible string.
  6219. *
  6220. * @param {CipherParams} cipherParams The cipher params object.
  6221. *
  6222. * @return {string} The OpenSSL-compatible string.
  6223. *
  6224. * @static
  6225. *
  6226. * @example
  6227. *
  6228. * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
  6229. */
  6230. stringify: function (cipherParams) {
  6231. // Shortcuts
  6232. var ciphertext = cipherParams.ciphertext;
  6233. var salt = cipherParams.salt;
  6234. // Format
  6235. if (salt) {
  6236. var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext);
  6237. } else {
  6238. var wordArray = ciphertext;
  6239. }
  6240. return wordArray.toString(Base64);
  6241. },
  6242. /**
  6243. * Converts an OpenSSL-compatible string to a cipher params object.
  6244. *
  6245. * @param {string} openSSLStr The OpenSSL-compatible string.
  6246. *
  6247. * @return {CipherParams} The cipher params object.
  6248. *
  6249. * @static
  6250. *
  6251. * @example
  6252. *
  6253. * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
  6254. */
  6255. parse: function (openSSLStr) {
  6256. // Parse base64
  6257. var ciphertext = Base64.parse(openSSLStr);
  6258. // Shortcut
  6259. var ciphertextWords = ciphertext.words;
  6260. // Test for salt
  6261. if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) {
  6262. // Extract salt
  6263. var salt = WordArray.create(ciphertextWords.slice(2, 4));
  6264. // Remove salt from ciphertext
  6265. ciphertextWords.splice(0, 4);
  6266. ciphertext.sigBytes -= 16;
  6267. }
  6268. return CipherParams.create({ ciphertext: ciphertext, salt: salt });
  6269. }
  6270. };
  6271. /**
  6272. * A cipher wrapper that returns ciphertext as a serializable cipher params object.
  6273. */
  6274. var SerializableCipher = C_lib.SerializableCipher = Base.extend({
  6275. /**
  6276. * Configuration options.
  6277. *
  6278. * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
  6279. */
  6280. cfg: Base.extend({
  6281. format: OpenSSLFormatter
  6282. }),
  6283. /**
  6284. * Encrypts a message.
  6285. *
  6286. * @param {Cipher} cipher The cipher algorithm to use.
  6287. * @param {WordArray|string} message The message to encrypt.
  6288. * @param {WordArray} key The key.
  6289. * @param {Object} cfg (Optional) The configuration options to use for this operation.
  6290. *
  6291. * @return {CipherParams} A cipher params object.
  6292. *
  6293. * @static
  6294. *
  6295. * @example
  6296. *
  6297. * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
  6298. * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
  6299. * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
  6300. */
  6301. encrypt: function (cipher, message, key, cfg) {
  6302. // Apply config defaults
  6303. cfg = this.cfg.extend(cfg);
  6304. // Encrypt
  6305. var encryptor = cipher.createEncryptor(key, cfg);
  6306. var ciphertext = encryptor.finalize(message);
  6307. // Shortcut
  6308. var cipherCfg = encryptor.cfg;
  6309. // Create and return serializable cipher params
  6310. return CipherParams.create({
  6311. ciphertext: ciphertext,
  6312. key: key,
  6313. iv: cipherCfg.iv,
  6314. algorithm: cipher,
  6315. mode: cipherCfg.mode,
  6316. padding: cipherCfg.padding,
  6317. blockSize: cipher.blockSize,
  6318. formatter: cfg.format
  6319. });
  6320. },
  6321. /**
  6322. * Decrypts serialized ciphertext.
  6323. *
  6324. * @param {Cipher} cipher The cipher algorithm to use.
  6325. * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
  6326. * @param {WordArray} key The key.
  6327. * @param {Object} cfg (Optional) The configuration options to use for this operation.
  6328. *
  6329. * @return {WordArray} The plaintext.
  6330. *
  6331. * @static
  6332. *
  6333. * @example
  6334. *
  6335. * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
  6336. * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
  6337. */
  6338. decrypt: function (cipher, ciphertext, key, cfg) {
  6339. // Apply config defaults
  6340. cfg = this.cfg.extend(cfg);
  6341. // Convert string to CipherParams
  6342. ciphertext = this._parse(ciphertext, cfg.format);
  6343. // Decrypt
  6344. var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
  6345. return plaintext;
  6346. },
  6347. /**
  6348. * Converts serialized ciphertext to CipherParams,
  6349. * else assumed CipherParams already and returns ciphertext unchanged.
  6350. *
  6351. * @param {CipherParams|string} ciphertext The ciphertext.
  6352. * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
  6353. *
  6354. * @return {CipherParams} The unserialized ciphertext.
  6355. *
  6356. * @static
  6357. *
  6358. * @example
  6359. *
  6360. * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
  6361. */
  6362. _parse: function (ciphertext, format) {
  6363. if (typeof ciphertext == 'string') {
  6364. return format.parse(ciphertext, this);
  6365. } else {
  6366. return ciphertext;
  6367. }
  6368. }
  6369. });
  6370. /**
  6371. * Key derivation function namespace.
  6372. */
  6373. var C_kdf = C.kdf = {};
  6374. /**
  6375. * OpenSSL key derivation function.
  6376. */
  6377. var OpenSSLKdf = C_kdf.OpenSSL = {
  6378. /**
  6379. * Derives a key and IV from a password.
  6380. *
  6381. * @param {string} password The password to derive from.
  6382. * @param {number} keySize The size in words of the key to generate.
  6383. * @param {number} ivSize The size in words of the IV to generate.
  6384. * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
  6385. *
  6386. * @return {CipherParams} A cipher params object with the key, IV, and salt.
  6387. *
  6388. * @static
  6389. *
  6390. * @example
  6391. *
  6392. * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
  6393. * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
  6394. */
  6395. execute: function (password, keySize, ivSize, salt) {
  6396. // Generate random salt
  6397. if (!salt) {
  6398. salt = WordArray.random(64/8);
  6399. }
  6400. // Derive key and IV
  6401. var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
  6402. // Separate key and IV
  6403. var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
  6404. key.sigBytes = keySize * 4;
  6405. // Return params
  6406. return CipherParams.create({ key: key, iv: iv, salt: salt });
  6407. }
  6408. };
  6409. /**
  6410. * A serializable cipher wrapper that derives the key from a password,
  6411. * and returns ciphertext as a serializable cipher params object.
  6412. */
  6413. var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
  6414. /**
  6415. * Configuration options.
  6416. *
  6417. * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
  6418. */
  6419. cfg: SerializableCipher.cfg.extend({
  6420. kdf: OpenSSLKdf
  6421. }),
  6422. /**
  6423. * Encrypts a message using a password.
  6424. *
  6425. * @param {Cipher} cipher The cipher algorithm to use.
  6426. * @param {WordArray|string} message The message to encrypt.
  6427. * @param {string} password The password.
  6428. * @param {Object} cfg (Optional) The configuration options to use for this operation.
  6429. *
  6430. * @return {CipherParams} A cipher params object.
  6431. *
  6432. * @static
  6433. *
  6434. * @example
  6435. *
  6436. * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
  6437. * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
  6438. */
  6439. encrypt: function (cipher, message, password, cfg) {
  6440. // Apply config defaults
  6441. cfg = this.cfg.extend(cfg);
  6442. // Derive key and other params
  6443. var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize);
  6444. // Add IV to config
  6445. cfg.iv = derivedParams.iv;
  6446. // Encrypt
  6447. var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);
  6448. // Mix in derived params
  6449. ciphertext.mixIn(derivedParams);
  6450. return ciphertext;
  6451. },
  6452. /**
  6453. * Decrypts serialized ciphertext using a password.
  6454. *
  6455. * @param {Cipher} cipher The cipher algorithm to use.
  6456. * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
  6457. * @param {string} password The password.
  6458. * @param {Object} cfg (Optional) The configuration options to use for this operation.
  6459. *
  6460. * @return {WordArray} The plaintext.
  6461. *
  6462. * @static
  6463. *
  6464. * @example
  6465. *
  6466. * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
  6467. * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
  6468. */
  6469. decrypt: function (cipher, ciphertext, password, cfg) {
  6470. // Apply config defaults
  6471. cfg = this.cfg.extend(cfg);
  6472. // Convert string to CipherParams
  6473. ciphertext = this._parse(ciphertext, cfg.format);
  6474. // Derive key and other params
  6475. var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt);
  6476. // Add IV to config
  6477. cfg.iv = derivedParams.iv;
  6478. // Decrypt
  6479. var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
  6480. return plaintext;
  6481. }
  6482. });
  6483. }());
  6484. }));
  6485. },{"./core":52}],52:[function(require,module,exports){
  6486. ;(function (root, factory) {
  6487. if (typeof exports === "object") {
  6488. // CommonJS
  6489. module.exports = exports = factory();
  6490. }
  6491. else if (typeof define === "function" && define.amd) {
  6492. // AMD
  6493. define([], factory);
  6494. }
  6495. else {
  6496. // Global (browser)
  6497. root.CryptoJS = factory();
  6498. }
  6499. }(this, function () {
  6500. /**
  6501. * CryptoJS core components.
  6502. */
  6503. var CryptoJS = CryptoJS || (function (Math, undefined) {
  6504. /**
  6505. * CryptoJS namespace.
  6506. */
  6507. var C = {};
  6508. /**
  6509. * Library namespace.
  6510. */
  6511. var C_lib = C.lib = {};
  6512. /**
  6513. * Base object for prototypal inheritance.
  6514. */
  6515. var Base = C_lib.Base = (function () {
  6516. function F() {}
  6517. return {
  6518. /**
  6519. * Creates a new object that inherits from this object.
  6520. *
  6521. * @param {Object} overrides Properties to copy into the new object.
  6522. *
  6523. * @return {Object} The new object.
  6524. *
  6525. * @static
  6526. *
  6527. * @example
  6528. *
  6529. * var MyType = CryptoJS.lib.Base.extend({
  6530. * field: 'value',
  6531. *
  6532. * method: function () {
  6533. * }
  6534. * });
  6535. */
  6536. extend: function (overrides) {
  6537. // Spawn
  6538. F.prototype = this;
  6539. var subtype = new F();
  6540. // Augment
  6541. if (overrides) {
  6542. subtype.mixIn(overrides);
  6543. }
  6544. // Create default initializer
  6545. if (!subtype.hasOwnProperty('init')) {
  6546. subtype.init = function () {
  6547. subtype.$super.init.apply(this, arguments);
  6548. };
  6549. }
  6550. // Initializer's prototype is the subtype object
  6551. subtype.init.prototype = subtype;
  6552. // Reference supertype
  6553. subtype.$super = this;
  6554. return subtype;
  6555. },
  6556. /**
  6557. * Extends this object and runs the init method.
  6558. * Arguments to create() will be passed to init().
  6559. *
  6560. * @return {Object} The new object.
  6561. *
  6562. * @static
  6563. *
  6564. * @example
  6565. *
  6566. * var instance = MyType.create();
  6567. */
  6568. create: function () {
  6569. var instance = this.extend();
  6570. instance.init.apply(instance, arguments);
  6571. return instance;
  6572. },
  6573. /**
  6574. * Initializes a newly created object.
  6575. * Override this method to add some logic when your objects are created.
  6576. *
  6577. * @example
  6578. *
  6579. * var MyType = CryptoJS.lib.Base.extend({
  6580. * init: function () {
  6581. * // ...
  6582. * }
  6583. * });
  6584. */
  6585. init: function () {
  6586. },
  6587. /**
  6588. * Copies properties into this object.
  6589. *
  6590. * @param {Object} properties The properties to mix in.
  6591. *
  6592. * @example
  6593. *
  6594. * MyType.mixIn({
  6595. * field: 'value'
  6596. * });
  6597. */
  6598. mixIn: function (properties) {
  6599. for (var propertyName in properties) {
  6600. if (properties.hasOwnProperty(propertyName)) {
  6601. this[propertyName] = properties[propertyName];
  6602. }
  6603. }
  6604. // IE won't copy toString using the loop above
  6605. if (properties.hasOwnProperty('toString')) {
  6606. this.toString = properties.toString;
  6607. }
  6608. },
  6609. /**
  6610. * Creates a copy of this object.
  6611. *
  6612. * @return {Object} The clone.
  6613. *
  6614. * @example
  6615. *
  6616. * var clone = instance.clone();
  6617. */
  6618. clone: function () {
  6619. return this.init.prototype.extend(this);
  6620. }
  6621. };
  6622. }());
  6623. /**
  6624. * An array of 32-bit words.
  6625. *
  6626. * @property {Array} words The array of 32-bit words.
  6627. * @property {number} sigBytes The number of significant bytes in this word array.
  6628. */
  6629. var WordArray = C_lib.WordArray = Base.extend({
  6630. /**
  6631. * Initializes a newly created word array.
  6632. *
  6633. * @param {Array} words (Optional) An array of 32-bit words.
  6634. * @param {number} sigBytes (Optional) The number of significant bytes in the words.
  6635. *
  6636. * @example
  6637. *
  6638. * var wordArray = CryptoJS.lib.WordArray.create();
  6639. * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
  6640. * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
  6641. */
  6642. init: function (words, sigBytes) {
  6643. words = this.words = words || [];
  6644. if (sigBytes != undefined) {
  6645. this.sigBytes = sigBytes;
  6646. } else {
  6647. this.sigBytes = words.length * 4;
  6648. }
  6649. },
  6650. /**
  6651. * Converts this word array to a string.
  6652. *
  6653. * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
  6654. *
  6655. * @return {string} The stringified word array.
  6656. *
  6657. * @example
  6658. *
  6659. * var string = wordArray + '';
  6660. * var string = wordArray.toString();
  6661. * var string = wordArray.toString(CryptoJS.enc.Utf8);
  6662. */
  6663. toString: function (encoder) {
  6664. return (encoder || Hex).stringify(this);
  6665. },
  6666. /**
  6667. * Concatenates a word array to this word array.
  6668. *
  6669. * @param {WordArray} wordArray The word array to append.
  6670. *
  6671. * @return {WordArray} This word array.
  6672. *
  6673. * @example
  6674. *
  6675. * wordArray1.concat(wordArray2);
  6676. */
  6677. concat: function (wordArray) {
  6678. // Shortcuts
  6679. var thisWords = this.words;
  6680. var thatWords = wordArray.words;
  6681. var thisSigBytes = this.sigBytes;
  6682. var thatSigBytes = wordArray.sigBytes;
  6683. // Clamp excess bits
  6684. this.clamp();
  6685. // Concat
  6686. if (thisSigBytes % 4) {
  6687. // Copy one byte at a time
  6688. for (var i = 0; i < thatSigBytes; i++) {
  6689. var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
  6690. thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
  6691. }
  6692. } else {
  6693. // Copy one word at a time
  6694. for (var i = 0; i < thatSigBytes; i += 4) {
  6695. thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
  6696. }
  6697. }
  6698. this.sigBytes += thatSigBytes;
  6699. // Chainable
  6700. return this;
  6701. },
  6702. /**
  6703. * Removes insignificant bits.
  6704. *
  6705. * @example
  6706. *
  6707. * wordArray.clamp();
  6708. */
  6709. clamp: function () {
  6710. // Shortcuts
  6711. var words = this.words;
  6712. var sigBytes = this.sigBytes;
  6713. // Clamp
  6714. words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
  6715. words.length = Math.ceil(sigBytes / 4);
  6716. },
  6717. /**
  6718. * Creates a copy of this word array.
  6719. *
  6720. * @return {WordArray} The clone.
  6721. *
  6722. * @example
  6723. *
  6724. * var clone = wordArray.clone();
  6725. */
  6726. clone: function () {
  6727. var clone = Base.clone.call(this);
  6728. clone.words = this.words.slice(0);
  6729. return clone;
  6730. },
  6731. /**
  6732. * Creates a word array filled with random bytes.
  6733. *
  6734. * @param {number} nBytes The number of random bytes to generate.
  6735. *
  6736. * @return {WordArray} The random word array.
  6737. *
  6738. * @static
  6739. *
  6740. * @example
  6741. *
  6742. * var wordArray = CryptoJS.lib.WordArray.random(16);
  6743. */
  6744. random: function (nBytes) {
  6745. var words = [];
  6746. var r = (function (m_w) {
  6747. var m_w = m_w;
  6748. var m_z = 0x3ade68b1;
  6749. var mask = 0xffffffff;
  6750. return function () {
  6751. m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
  6752. m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
  6753. var result = ((m_z << 0x10) + m_w) & mask;
  6754. result /= 0x100000000;
  6755. result += 0.5;
  6756. return result * (Math.random() > .5 ? 1 : -1);
  6757. }
  6758. });
  6759. for (var i = 0, rcache; i < nBytes; i += 4) {
  6760. var _r = r((rcache || Math.random()) * 0x100000000);
  6761. rcache = _r() * 0x3ade67b7;
  6762. words.push((_r() * 0x100000000) | 0);
  6763. }
  6764. return new WordArray.init(words, nBytes);
  6765. }
  6766. });
  6767. /**
  6768. * Encoder namespace.
  6769. */
  6770. var C_enc = C.enc = {};
  6771. /**
  6772. * Hex encoding strategy.
  6773. */
  6774. var Hex = C_enc.Hex = {
  6775. /**
  6776. * Converts a word array to a hex string.
  6777. *
  6778. * @param {WordArray} wordArray The word array.
  6779. *
  6780. * @return {string} The hex string.
  6781. *
  6782. * @static
  6783. *
  6784. * @example
  6785. *
  6786. * var hexString = CryptoJS.enc.Hex.stringify(wordArray);
  6787. */
  6788. stringify: function (wordArray) {
  6789. // Shortcuts
  6790. var words = wordArray.words;
  6791. var sigBytes = wordArray.sigBytes;
  6792. // Convert
  6793. var hexChars = [];
  6794. for (var i = 0; i < sigBytes; i++) {
  6795. var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
  6796. hexChars.push((bite >>> 4).toString(16));
  6797. hexChars.push((bite & 0x0f).toString(16));
  6798. }
  6799. return hexChars.join('');
  6800. },
  6801. /**
  6802. * Converts a hex string to a word array.
  6803. *
  6804. * @param {string} hexStr The hex string.
  6805. *
  6806. * @return {WordArray} The word array.
  6807. *
  6808. * @static
  6809. *
  6810. * @example
  6811. *
  6812. * var wordArray = CryptoJS.enc.Hex.parse(hexString);
  6813. */
  6814. parse: function (hexStr) {
  6815. // Shortcut
  6816. var hexStrLength = hexStr.length;
  6817. // Convert
  6818. var words = [];
  6819. for (var i = 0; i < hexStrLength; i += 2) {
  6820. words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
  6821. }
  6822. return new WordArray.init(words, hexStrLength / 2);
  6823. }
  6824. };
  6825. /**
  6826. * Latin1 encoding strategy.
  6827. */
  6828. var Latin1 = C_enc.Latin1 = {
  6829. /**
  6830. * Converts a word array to a Latin1 string.
  6831. *
  6832. * @param {WordArray} wordArray The word array.
  6833. *
  6834. * @return {string} The Latin1 string.
  6835. *
  6836. * @static
  6837. *
  6838. * @example
  6839. *
  6840. * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
  6841. */
  6842. stringify: function (wordArray) {
  6843. // Shortcuts
  6844. var words = wordArray.words;
  6845. var sigBytes = wordArray.sigBytes;
  6846. // Convert
  6847. var latin1Chars = [];
  6848. for (var i = 0; i < sigBytes; i++) {
  6849. var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
  6850. latin1Chars.push(String.fromCharCode(bite));
  6851. }
  6852. return latin1Chars.join('');
  6853. },
  6854. /**
  6855. * Converts a Latin1 string to a word array.
  6856. *
  6857. * @param {string} latin1Str The Latin1 string.
  6858. *
  6859. * @return {WordArray} The word array.
  6860. *
  6861. * @static
  6862. *
  6863. * @example
  6864. *
  6865. * var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
  6866. */
  6867. parse: function (latin1Str) {
  6868. // Shortcut
  6869. var latin1StrLength = latin1Str.length;
  6870. // Convert
  6871. var words = [];
  6872. for (var i = 0; i < latin1StrLength; i++) {
  6873. words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
  6874. }
  6875. return new WordArray.init(words, latin1StrLength);
  6876. }
  6877. };
  6878. /**
  6879. * UTF-8 encoding strategy.
  6880. */
  6881. var Utf8 = C_enc.Utf8 = {
  6882. /**
  6883. * Converts a word array to a UTF-8 string.
  6884. *
  6885. * @param {WordArray} wordArray The word array.
  6886. *
  6887. * @return {string} The UTF-8 string.
  6888. *
  6889. * @static
  6890. *
  6891. * @example
  6892. *
  6893. * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
  6894. */
  6895. stringify: function (wordArray) {
  6896. try {
  6897. return decodeURIComponent(escape(Latin1.stringify(wordArray)));
  6898. } catch (e) {
  6899. throw new Error('Malformed UTF-8 data');
  6900. }
  6901. },
  6902. /**
  6903. * Converts a UTF-8 string to a word array.
  6904. *
  6905. * @param {string} utf8Str The UTF-8 string.
  6906. *
  6907. * @return {WordArray} The word array.
  6908. *
  6909. * @static
  6910. *
  6911. * @example
  6912. *
  6913. * var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
  6914. */
  6915. parse: function (utf8Str) {
  6916. return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
  6917. }
  6918. };
  6919. /**
  6920. * Abstract buffered block algorithm template.
  6921. *
  6922. * The property blockSize must be implemented in a concrete subtype.
  6923. *
  6924. * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
  6925. */
  6926. var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
  6927. /**
  6928. * Resets this block algorithm's data buffer to its initial state.
  6929. *
  6930. * @example
  6931. *
  6932. * bufferedBlockAlgorithm.reset();
  6933. */
  6934. reset: function () {
  6935. // Initial values
  6936. this._data = new WordArray.init();
  6937. this._nDataBytes = 0;
  6938. },
  6939. /**
  6940. * Adds new data to this block algorithm's buffer.
  6941. *
  6942. * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
  6943. *
  6944. * @example
  6945. *
  6946. * bufferedBlockAlgorithm._append('data');
  6947. * bufferedBlockAlgorithm._append(wordArray);
  6948. */
  6949. _append: function (data) {
  6950. // Convert string to WordArray, else assume WordArray already
  6951. if (typeof data == 'string') {
  6952. data = Utf8.parse(data);
  6953. }
  6954. // Append
  6955. this._data.concat(data);
  6956. this._nDataBytes += data.sigBytes;
  6957. },
  6958. /**
  6959. * Processes available data blocks.
  6960. *
  6961. * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
  6962. *
  6963. * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
  6964. *
  6965. * @return {WordArray} The processed data.
  6966. *
  6967. * @example
  6968. *
  6969. * var processedData = bufferedBlockAlgorithm._process();
  6970. * var processedData = bufferedBlockAlgorithm._process(!!'flush');
  6971. */
  6972. _process: function (doFlush) {
  6973. // Shortcuts
  6974. var data = this._data;
  6975. var dataWords = data.words;
  6976. var dataSigBytes = data.sigBytes;
  6977. var blockSize = this.blockSize;
  6978. var blockSizeBytes = blockSize * 4;
  6979. // Count blocks ready
  6980. var nBlocksReady = dataSigBytes / blockSizeBytes;
  6981. if (doFlush) {
  6982. // Round up to include partial blocks
  6983. nBlocksReady = Math.ceil(nBlocksReady);
  6984. } else {
  6985. // Round down to include only full blocks,
  6986. // less the number of blocks that must remain in the buffer
  6987. nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
  6988. }
  6989. // Count words ready
  6990. var nWordsReady = nBlocksReady * blockSize;
  6991. // Count bytes ready
  6992. var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
  6993. // Process blocks
  6994. if (nWordsReady) {
  6995. for (var offset = 0; offset < nWordsReady; offset += blockSize) {
  6996. // Perform concrete-algorithm logic
  6997. this._doProcessBlock(dataWords, offset);
  6998. }
  6999. // Remove processed words
  7000. var processedWords = dataWords.splice(0, nWordsReady);
  7001. data.sigBytes -= nBytesReady;
  7002. }
  7003. // Return processed words
  7004. return new WordArray.init(processedWords, nBytesReady);
  7005. },
  7006. /**
  7007. * Creates a copy of this object.
  7008. *
  7009. * @return {Object} The clone.
  7010. *
  7011. * @example
  7012. *
  7013. * var clone = bufferedBlockAlgorithm.clone();
  7014. */
  7015. clone: function () {
  7016. var clone = Base.clone.call(this);
  7017. clone._data = this._data.clone();
  7018. return clone;
  7019. },
  7020. _minBufferSize: 0
  7021. });
  7022. /**
  7023. * Abstract hasher template.
  7024. *
  7025. * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
  7026. */
  7027. var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
  7028. /**
  7029. * Configuration options.
  7030. */
  7031. cfg: Base.extend(),
  7032. /**
  7033. * Initializes a newly created hasher.
  7034. *
  7035. * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
  7036. *
  7037. * @example
  7038. *
  7039. * var hasher = CryptoJS.algo.SHA256.create();
  7040. */
  7041. init: function (cfg) {
  7042. // Apply config defaults
  7043. this.cfg = this.cfg.extend(cfg);
  7044. // Set initial values
  7045. this.reset();
  7046. },
  7047. /**
  7048. * Resets this hasher to its initial state.
  7049. *
  7050. * @example
  7051. *
  7052. * hasher.reset();
  7053. */
  7054. reset: function () {
  7055. // Reset data buffer
  7056. BufferedBlockAlgorithm.reset.call(this);
  7057. // Perform concrete-hasher logic
  7058. this._doReset();
  7059. },
  7060. /**
  7061. * Updates this hasher with a message.
  7062. *
  7063. * @param {WordArray|string} messageUpdate The message to append.
  7064. *
  7065. * @return {Hasher} This hasher.
  7066. *
  7067. * @example
  7068. *
  7069. * hasher.update('message');
  7070. * hasher.update(wordArray);
  7071. */
  7072. update: function (messageUpdate) {
  7073. // Append
  7074. this._append(messageUpdate);
  7075. // Update the hash
  7076. this._process();
  7077. // Chainable
  7078. return this;
  7079. },
  7080. /**
  7081. * Finalizes the hash computation.
  7082. * Note that the finalize operation is effectively a destructive, read-once operation.
  7083. *
  7084. * @param {WordArray|string} messageUpdate (Optional) A final message update.
  7085. *
  7086. * @return {WordArray} The hash.
  7087. *
  7088. * @example
  7089. *
  7090. * var hash = hasher.finalize();
  7091. * var hash = hasher.finalize('message');
  7092. * var hash = hasher.finalize(wordArray);
  7093. */
  7094. finalize: function (messageUpdate) {
  7095. // Final message update
  7096. if (messageUpdate) {
  7097. this._append(messageUpdate);
  7098. }
  7099. // Perform concrete-hasher logic
  7100. var hash = this._doFinalize();
  7101. return hash;
  7102. },
  7103. blockSize: 512/32,
  7104. /**
  7105. * Creates a shortcut function to a hasher's object interface.
  7106. *
  7107. * @param {Hasher} hasher The hasher to create a helper for.
  7108. *
  7109. * @return {Function} The shortcut function.
  7110. *
  7111. * @static
  7112. *
  7113. * @example
  7114. *
  7115. * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
  7116. */
  7117. _createHelper: function (hasher) {
  7118. return function (message, cfg) {
  7119. return new hasher.init(cfg).finalize(message);
  7120. };
  7121. },
  7122. /**
  7123. * Creates a shortcut function to the HMAC's object interface.
  7124. *
  7125. * @param {Hasher} hasher The hasher to use in this HMAC helper.
  7126. *
  7127. * @return {Function} The shortcut function.
  7128. *
  7129. * @static
  7130. *
  7131. * @example
  7132. *
  7133. * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
  7134. */
  7135. _createHmacHelper: function (hasher) {
  7136. return function (message, key) {
  7137. return new C_algo.HMAC.init(hasher, key).finalize(message);
  7138. };
  7139. }
  7140. });
  7141. /**
  7142. * Algorithm namespace.
  7143. */
  7144. var C_algo = C.algo = {};
  7145. return C;
  7146. }(Math));
  7147. return CryptoJS;
  7148. }));
  7149. },{}],53:[function(require,module,exports){
  7150. ;(function (root, factory) {
  7151. if (typeof exports === "object") {
  7152. // CommonJS
  7153. module.exports = exports = factory(require("./core"));
  7154. }
  7155. else if (typeof define === "function" && define.amd) {
  7156. // AMD
  7157. define(["./core"], factory);
  7158. }
  7159. else {
  7160. // Global (browser)
  7161. factory(root.CryptoJS);
  7162. }
  7163. }(this, function (CryptoJS) {
  7164. (function () {
  7165. // Shortcuts
  7166. var C = CryptoJS;
  7167. var C_lib = C.lib;
  7168. var WordArray = C_lib.WordArray;
  7169. var C_enc = C.enc;
  7170. /**
  7171. * Base64 encoding strategy.
  7172. */
  7173. var Base64 = C_enc.Base64 = {
  7174. /**
  7175. * Converts a word array to a Base64 string.
  7176. *
  7177. * @param {WordArray} wordArray The word array.
  7178. *
  7179. * @return {string} The Base64 string.
  7180. *
  7181. * @static
  7182. *
  7183. * @example
  7184. *
  7185. * var base64String = CryptoJS.enc.Base64.stringify(wordArray);
  7186. */
  7187. stringify: function (wordArray) {
  7188. // Shortcuts
  7189. var words = wordArray.words;
  7190. var sigBytes = wordArray.sigBytes;
  7191. var map = this._map;
  7192. // Clamp excess bits
  7193. wordArray.clamp();
  7194. // Convert
  7195. var base64Chars = [];
  7196. for (var i = 0; i < sigBytes; i += 3) {
  7197. var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
  7198. var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
  7199. var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
  7200. var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
  7201. for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
  7202. base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
  7203. }
  7204. }
  7205. // Add padding
  7206. var paddingChar = map.charAt(64);
  7207. if (paddingChar) {
  7208. while (base64Chars.length % 4) {
  7209. base64Chars.push(paddingChar);
  7210. }
  7211. }
  7212. return base64Chars.join('');
  7213. },
  7214. /**
  7215. * Converts a Base64 string to a word array.
  7216. *
  7217. * @param {string} base64Str The Base64 string.
  7218. *
  7219. * @return {WordArray} The word array.
  7220. *
  7221. * @static
  7222. *
  7223. * @example
  7224. *
  7225. * var wordArray = CryptoJS.enc.Base64.parse(base64String);
  7226. */
  7227. parse: function (base64Str) {
  7228. // Shortcuts
  7229. var base64StrLength = base64Str.length;
  7230. var map = this._map;
  7231. // Ignore padding
  7232. var paddingChar = map.charAt(64);
  7233. if (paddingChar) {
  7234. var paddingIndex = base64Str.indexOf(paddingChar);
  7235. if (paddingIndex != -1) {
  7236. base64StrLength = paddingIndex;
  7237. }
  7238. }
  7239. // Convert
  7240. var words = [];
  7241. var nBytes = 0;
  7242. for (var i = 0; i < base64StrLength; i++) {
  7243. if (i % 4) {
  7244. var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2);
  7245. var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2);
  7246. words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8);
  7247. nBytes++;
  7248. }
  7249. }
  7250. return WordArray.create(words, nBytes);
  7251. },
  7252. _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
  7253. };
  7254. }());
  7255. return CryptoJS.enc.Base64;
  7256. }));
  7257. },{"./core":52}],54:[function(require,module,exports){
  7258. ;(function (root, factory) {
  7259. if (typeof exports === "object") {
  7260. // CommonJS
  7261. module.exports = exports = factory(require("./core"));
  7262. }
  7263. else if (typeof define === "function" && define.amd) {
  7264. // AMD
  7265. define(["./core"], factory);
  7266. }
  7267. else {
  7268. // Global (browser)
  7269. factory(root.CryptoJS);
  7270. }
  7271. }(this, function (CryptoJS) {
  7272. (function () {
  7273. // Shortcuts
  7274. var C = CryptoJS;
  7275. var C_lib = C.lib;
  7276. var WordArray = C_lib.WordArray;
  7277. var C_enc = C.enc;
  7278. /**
  7279. * UTF-16 BE encoding strategy.
  7280. */
  7281. var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = {
  7282. /**
  7283. * Converts a word array to a UTF-16 BE string.
  7284. *
  7285. * @param {WordArray} wordArray The word array.
  7286. *
  7287. * @return {string} The UTF-16 BE string.
  7288. *
  7289. * @static
  7290. *
  7291. * @example
  7292. *
  7293. * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
  7294. */
  7295. stringify: function (wordArray) {
  7296. // Shortcuts
  7297. var words = wordArray.words;
  7298. var sigBytes = wordArray.sigBytes;
  7299. // Convert
  7300. var utf16Chars = [];
  7301. for (var i = 0; i < sigBytes; i += 2) {
  7302. var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff;
  7303. utf16Chars.push(String.fromCharCode(codePoint));
  7304. }
  7305. return utf16Chars.join('');
  7306. },
  7307. /**
  7308. * Converts a UTF-16 BE string to a word array.
  7309. *
  7310. * @param {string} utf16Str The UTF-16 BE string.
  7311. *
  7312. * @return {WordArray} The word array.
  7313. *
  7314. * @static
  7315. *
  7316. * @example
  7317. *
  7318. * var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
  7319. */
  7320. parse: function (utf16Str) {
  7321. // Shortcut
  7322. var utf16StrLength = utf16Str.length;
  7323. // Convert
  7324. var words = [];
  7325. for (var i = 0; i < utf16StrLength; i++) {
  7326. words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16);
  7327. }
  7328. return WordArray.create(words, utf16StrLength * 2);
  7329. }
  7330. };
  7331. /**
  7332. * UTF-16 LE encoding strategy.
  7333. */
  7334. C_enc.Utf16LE = {
  7335. /**
  7336. * Converts a word array to a UTF-16 LE string.
  7337. *
  7338. * @param {WordArray} wordArray The word array.
  7339. *
  7340. * @return {string} The UTF-16 LE string.
  7341. *
  7342. * @static
  7343. *
  7344. * @example
  7345. *
  7346. * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
  7347. */
  7348. stringify: function (wordArray) {
  7349. // Shortcuts
  7350. var words = wordArray.words;
  7351. var sigBytes = wordArray.sigBytes;
  7352. // Convert
  7353. var utf16Chars = [];
  7354. for (var i = 0; i < sigBytes; i += 2) {
  7355. var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff);
  7356. utf16Chars.push(String.fromCharCode(codePoint));
  7357. }
  7358. return utf16Chars.join('');
  7359. },
  7360. /**
  7361. * Converts a UTF-16 LE string to a word array.
  7362. *
  7363. * @param {string} utf16Str The UTF-16 LE string.
  7364. *
  7365. * @return {WordArray} The word array.
  7366. *
  7367. * @static
  7368. *
  7369. * @example
  7370. *
  7371. * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
  7372. */
  7373. parse: function (utf16Str) {
  7374. // Shortcut
  7375. var utf16StrLength = utf16Str.length;
  7376. // Convert
  7377. var words = [];
  7378. for (var i = 0; i < utf16StrLength; i++) {
  7379. words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16));
  7380. }
  7381. return WordArray.create(words, utf16StrLength * 2);
  7382. }
  7383. };
  7384. function swapEndian(word) {
  7385. return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff);
  7386. }
  7387. }());
  7388. return CryptoJS.enc.Utf16;
  7389. }));
  7390. },{"./core":52}],55:[function(require,module,exports){
  7391. ;(function (root, factory, undef) {
  7392. if (typeof exports === "object") {
  7393. // CommonJS
  7394. module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac"));
  7395. }
  7396. else if (typeof define === "function" && define.amd) {
  7397. // AMD
  7398. define(["./core", "./sha1", "./hmac"], factory);
  7399. }
  7400. else {
  7401. // Global (browser)
  7402. factory(root.CryptoJS);
  7403. }
  7404. }(this, function (CryptoJS) {
  7405. (function () {
  7406. // Shortcuts
  7407. var C = CryptoJS;
  7408. var C_lib = C.lib;
  7409. var Base = C_lib.Base;
  7410. var WordArray = C_lib.WordArray;
  7411. var C_algo = C.algo;
  7412. var MD5 = C_algo.MD5;
  7413. /**
  7414. * This key derivation function is meant to conform with EVP_BytesToKey.
  7415. * www.openssl.org/docs/crypto/EVP_BytesToKey.html
  7416. */
  7417. var EvpKDF = C_algo.EvpKDF = Base.extend({
  7418. /**
  7419. * Configuration options.
  7420. *
  7421. * @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
  7422. * @property {Hasher} hasher The hash algorithm to use. Default: MD5
  7423. * @property {number} iterations The number of iterations to perform. Default: 1
  7424. */
  7425. cfg: Base.extend({
  7426. keySize: 128/32,
  7427. hasher: MD5,
  7428. iterations: 1
  7429. }),
  7430. /**
  7431. * Initializes a newly created key derivation function.
  7432. *
  7433. * @param {Object} cfg (Optional) The configuration options to use for the derivation.
  7434. *
  7435. * @example
  7436. *
  7437. * var kdf = CryptoJS.algo.EvpKDF.create();
  7438. * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
  7439. * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
  7440. */
  7441. init: function (cfg) {
  7442. this.cfg = this.cfg.extend(cfg);
  7443. },
  7444. /**
  7445. * Derives a key from a password.
  7446. *
  7447. * @param {WordArray|string} password The password.
  7448. * @param {WordArray|string} salt A salt.
  7449. *
  7450. * @return {WordArray} The derived key.
  7451. *
  7452. * @example
  7453. *
  7454. * var key = kdf.compute(password, salt);
  7455. */
  7456. compute: function (password, salt) {
  7457. // Shortcut
  7458. var cfg = this.cfg;
  7459. // Init hasher
  7460. var hasher = cfg.hasher.create();
  7461. // Initial values
  7462. var derivedKey = WordArray.create();
  7463. // Shortcuts
  7464. var derivedKeyWords = derivedKey.words;
  7465. var keySize = cfg.keySize;
  7466. var iterations = cfg.iterations;
  7467. // Generate key
  7468. while (derivedKeyWords.length < keySize) {
  7469. if (block) {
  7470. hasher.update(block);
  7471. }
  7472. var block = hasher.update(password).finalize(salt);
  7473. hasher.reset();
  7474. // Iterations
  7475. for (var i = 1; i < iterations; i++) {
  7476. block = hasher.finalize(block);
  7477. hasher.reset();
  7478. }
  7479. derivedKey.concat(block);
  7480. }
  7481. derivedKey.sigBytes = keySize * 4;
  7482. return derivedKey;
  7483. }
  7484. });
  7485. /**
  7486. * Derives a key from a password.
  7487. *
  7488. * @param {WordArray|string} password The password.
  7489. * @param {WordArray|string} salt A salt.
  7490. * @param {Object} cfg (Optional) The configuration options to use for this computation.
  7491. *
  7492. * @return {WordArray} The derived key.
  7493. *
  7494. * @static
  7495. *
  7496. * @example
  7497. *
  7498. * var key = CryptoJS.EvpKDF(password, salt);
  7499. * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 });
  7500. * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });
  7501. */
  7502. C.EvpKDF = function (password, salt, cfg) {
  7503. return EvpKDF.create(cfg).compute(password, salt);
  7504. };
  7505. }());
  7506. return CryptoJS.EvpKDF;
  7507. }));
  7508. },{"./core":52,"./hmac":57,"./sha1":76}],56:[function(require,module,exports){
  7509. ;(function (root, factory, undef) {
  7510. if (typeof exports === "object") {
  7511. // CommonJS
  7512. module.exports = exports = factory(require("./core"), require("./cipher-core"));
  7513. }
  7514. else if (typeof define === "function" && define.amd) {
  7515. // AMD
  7516. define(["./core", "./cipher-core"], factory);
  7517. }
  7518. else {
  7519. // Global (browser)
  7520. factory(root.CryptoJS);
  7521. }
  7522. }(this, function (CryptoJS) {
  7523. (function (undefined) {
  7524. // Shortcuts
  7525. var C = CryptoJS;
  7526. var C_lib = C.lib;
  7527. var CipherParams = C_lib.CipherParams;
  7528. var C_enc = C.enc;
  7529. var Hex = C_enc.Hex;
  7530. var C_format = C.format;
  7531. var HexFormatter = C_format.Hex = {
  7532. /**
  7533. * Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
  7534. *
  7535. * @param {CipherParams} cipherParams The cipher params object.
  7536. *
  7537. * @return {string} The hexadecimally encoded string.
  7538. *
  7539. * @static
  7540. *
  7541. * @example
  7542. *
  7543. * var hexString = CryptoJS.format.Hex.stringify(cipherParams);
  7544. */
  7545. stringify: function (cipherParams) {
  7546. return cipherParams.ciphertext.toString(Hex);
  7547. },
  7548. /**
  7549. * Converts a hexadecimally encoded ciphertext string to a cipher params object.
  7550. *
  7551. * @param {string} input The hexadecimally encoded string.
  7552. *
  7553. * @return {CipherParams} The cipher params object.
  7554. *
  7555. * @static
  7556. *
  7557. * @example
  7558. *
  7559. * var cipherParams = CryptoJS.format.Hex.parse(hexString);
  7560. */
  7561. parse: function (input) {
  7562. var ciphertext = Hex.parse(input);
  7563. return CipherParams.create({ ciphertext: ciphertext });
  7564. }
  7565. };
  7566. }());
  7567. return CryptoJS.format.Hex;
  7568. }));
  7569. },{"./cipher-core":51,"./core":52}],57:[function(require,module,exports){
  7570. ;(function (root, factory) {
  7571. if (typeof exports === "object") {
  7572. // CommonJS
  7573. module.exports = exports = factory(require("./core"));
  7574. }
  7575. else if (typeof define === "function" && define.amd) {
  7576. // AMD
  7577. define(["./core"], factory);
  7578. }
  7579. else {
  7580. // Global (browser)
  7581. factory(root.CryptoJS);
  7582. }
  7583. }(this, function (CryptoJS) {
  7584. (function () {
  7585. // Shortcuts
  7586. var C = CryptoJS;
  7587. var C_lib = C.lib;
  7588. var Base = C_lib.Base;
  7589. var C_enc = C.enc;
  7590. var Utf8 = C_enc.Utf8;
  7591. var C_algo = C.algo;
  7592. /**
  7593. * HMAC algorithm.
  7594. */
  7595. var HMAC = C_algo.HMAC = Base.extend({
  7596. /**
  7597. * Initializes a newly created HMAC.
  7598. *
  7599. * @param {Hasher} hasher The hash algorithm to use.
  7600. * @param {WordArray|string} key The secret key.
  7601. *
  7602. * @example
  7603. *
  7604. * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
  7605. */
  7606. init: function (hasher, key) {
  7607. // Init hasher
  7608. hasher = this._hasher = new hasher.init();
  7609. // Convert string to WordArray, else assume WordArray already
  7610. if (typeof key == 'string') {
  7611. key = Utf8.parse(key);
  7612. }
  7613. // Shortcuts
  7614. var hasherBlockSize = hasher.blockSize;
  7615. var hasherBlockSizeBytes = hasherBlockSize * 4;
  7616. // Allow arbitrary length keys
  7617. if (key.sigBytes > hasherBlockSizeBytes) {
  7618. key = hasher.finalize(key);
  7619. }
  7620. // Clamp excess bits
  7621. key.clamp();
  7622. // Clone key for inner and outer pads
  7623. var oKey = this._oKey = key.clone();
  7624. var iKey = this._iKey = key.clone();
  7625. // Shortcuts
  7626. var oKeyWords = oKey.words;
  7627. var iKeyWords = iKey.words;
  7628. // XOR keys with pad constants
  7629. for (var i = 0; i < hasherBlockSize; i++) {
  7630. oKeyWords[i] ^= 0x5c5c5c5c;
  7631. iKeyWords[i] ^= 0x36363636;
  7632. }
  7633. oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
  7634. // Set initial values
  7635. this.reset();
  7636. },
  7637. /**
  7638. * Resets this HMAC to its initial state.
  7639. *
  7640. * @example
  7641. *
  7642. * hmacHasher.reset();
  7643. */
  7644. reset: function () {
  7645. // Shortcut
  7646. var hasher = this._hasher;
  7647. // Reset
  7648. hasher.reset();
  7649. hasher.update(this._iKey);
  7650. },
  7651. /**
  7652. * Updates this HMAC with a message.
  7653. *
  7654. * @param {WordArray|string} messageUpdate The message to append.
  7655. *
  7656. * @return {HMAC} This HMAC instance.
  7657. *
  7658. * @example
  7659. *
  7660. * hmacHasher.update('message');
  7661. * hmacHasher.update(wordArray);
  7662. */
  7663. update: function (messageUpdate) {
  7664. this._hasher.update(messageUpdate);
  7665. // Chainable
  7666. return this;
  7667. },
  7668. /**
  7669. * Finalizes the HMAC computation.
  7670. * Note that the finalize operation is effectively a destructive, read-once operation.
  7671. *
  7672. * @param {WordArray|string} messageUpdate (Optional) A final message update.
  7673. *
  7674. * @return {WordArray} The HMAC.
  7675. *
  7676. * @example
  7677. *
  7678. * var hmac = hmacHasher.finalize();
  7679. * var hmac = hmacHasher.finalize('message');
  7680. * var hmac = hmacHasher.finalize(wordArray);
  7681. */
  7682. finalize: function (messageUpdate) {
  7683. // Shortcut
  7684. var hasher = this._hasher;
  7685. // Compute HMAC
  7686. var innerHash = hasher.finalize(messageUpdate);
  7687. hasher.reset();
  7688. var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
  7689. return hmac;
  7690. }
  7691. });
  7692. }());
  7693. }));
  7694. },{"./core":52}],58:[function(require,module,exports){
  7695. ;(function (root, factory, undef) {
  7696. if (typeof exports === "object") {
  7697. // CommonJS
  7698. module.exports = exports = factory(require("./core"), require("./x64-core"), require("./lib-typedarrays"), require("./enc-utf16"), require("./enc-base64"), require("./md5"), require("./sha1"), require("./sha256"), require("./sha224"), require("./sha512"), require("./sha384"), require("./sha3"), require("./ripemd160"), require("./hmac"), require("./pbkdf2"), require("./evpkdf"), require("./cipher-core"), require("./mode-cfb"), require("./mode-ctr"), require("./mode-ctr-gladman"), require("./mode-ofb"), require("./mode-ecb"), require("./pad-ansix923"), require("./pad-iso10126"), require("./pad-iso97971"), require("./pad-zeropadding"), require("./pad-nopadding"), require("./format-hex"), require("./aes"), require("./tripledes"), require("./rc4"), require("./rabbit"), require("./rabbit-legacy"));
  7699. }
  7700. else if (typeof define === "function" && define.amd) {
  7701. // AMD
  7702. define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory);
  7703. }
  7704. else {
  7705. // Global (browser)
  7706. root.CryptoJS = factory(root.CryptoJS);
  7707. }
  7708. }(this, function (CryptoJS) {
  7709. return CryptoJS;
  7710. }));
  7711. },{"./aes":50,"./cipher-core":51,"./core":52,"./enc-base64":53,"./enc-utf16":54,"./evpkdf":55,"./format-hex":56,"./hmac":57,"./lib-typedarrays":59,"./md5":60,"./mode-cfb":61,"./mode-ctr":63,"./mode-ctr-gladman":62,"./mode-ecb":64,"./mode-ofb":65,"./pad-ansix923":66,"./pad-iso10126":67,"./pad-iso97971":68,"./pad-nopadding":69,"./pad-zeropadding":70,"./pbkdf2":71,"./rabbit":73,"./rabbit-legacy":72,"./rc4":74,"./ripemd160":75,"./sha1":76,"./sha224":77,"./sha256":78,"./sha3":79,"./sha384":80,"./sha512":81,"./tripledes":82,"./x64-core":83}],59:[function(require,module,exports){
  7712. ;(function (root, factory) {
  7713. if (typeof exports === "object") {
  7714. // CommonJS
  7715. module.exports = exports = factory(require("./core"));
  7716. }
  7717. else if (typeof define === "function" && define.amd) {
  7718. // AMD
  7719. define(["./core"], factory);
  7720. }
  7721. else {
  7722. // Global (browser)
  7723. factory(root.CryptoJS);
  7724. }
  7725. }(this, function (CryptoJS) {
  7726. (function () {
  7727. // Check if typed arrays are supported
  7728. if (typeof ArrayBuffer != 'function') {
  7729. return;
  7730. }
  7731. // Shortcuts
  7732. var C = CryptoJS;
  7733. var C_lib = C.lib;
  7734. var WordArray = C_lib.WordArray;
  7735. // Reference original init
  7736. var superInit = WordArray.init;
  7737. // Augment WordArray.init to handle typed arrays
  7738. var subInit = WordArray.init = function (typedArray) {
  7739. // Convert buffers to uint8
  7740. if (typedArray instanceof ArrayBuffer) {
  7741. typedArray = new Uint8Array(typedArray);
  7742. }
  7743. // Convert other array views to uint8
  7744. if (
  7745. typedArray instanceof Int8Array ||
  7746. (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) ||
  7747. typedArray instanceof Int16Array ||
  7748. typedArray instanceof Uint16Array ||
  7749. typedArray instanceof Int32Array ||
  7750. typedArray instanceof Uint32Array ||
  7751. typedArray instanceof Float32Array ||
  7752. typedArray instanceof Float64Array
  7753. ) {
  7754. typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
  7755. }
  7756. // Handle Uint8Array
  7757. if (typedArray instanceof Uint8Array) {
  7758. // Shortcut
  7759. var typedArrayByteLength = typedArray.byteLength;
  7760. // Extract bytes
  7761. var words = [];
  7762. for (var i = 0; i < typedArrayByteLength; i++) {
  7763. words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8);
  7764. }
  7765. // Initialize this word array
  7766. superInit.call(this, words, typedArrayByteLength);
  7767. } else {
  7768. // Else call normal init
  7769. superInit.apply(this, arguments);
  7770. }
  7771. };
  7772. subInit.prototype = WordArray;
  7773. }());
  7774. return CryptoJS.lib.WordArray;
  7775. }));
  7776. },{"./core":52}],60:[function(require,module,exports){
  7777. ;(function (root, factory) {
  7778. if (typeof exports === "object") {
  7779. // CommonJS
  7780. module.exports = exports = factory(require("./core"));
  7781. }
  7782. else if (typeof define === "function" && define.amd) {
  7783. // AMD
  7784. define(["./core"], factory);
  7785. }
  7786. else {
  7787. // Global (browser)
  7788. factory(root.CryptoJS);
  7789. }
  7790. }(this, function (CryptoJS) {
  7791. (function (Math) {
  7792. // Shortcuts
  7793. var C = CryptoJS;
  7794. var C_lib = C.lib;
  7795. var WordArray = C_lib.WordArray;
  7796. var Hasher = C_lib.Hasher;
  7797. var C_algo = C.algo;
  7798. // Constants table
  7799. var T = [];
  7800. // Compute constants
  7801. (function () {
  7802. for (var i = 0; i < 64; i++) {
  7803. T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;
  7804. }
  7805. }());
  7806. /**
  7807. * MD5 hash algorithm.
  7808. */
  7809. var MD5 = C_algo.MD5 = Hasher.extend({
  7810. _doReset: function () {
  7811. this._hash = new WordArray.init([
  7812. 0x67452301, 0xefcdab89,
  7813. 0x98badcfe, 0x10325476
  7814. ]);
  7815. },
  7816. _doProcessBlock: function (M, offset) {
  7817. // Swap endian
  7818. for (var i = 0; i < 16; i++) {
  7819. // Shortcuts
  7820. var offset_i = offset + i;
  7821. var M_offset_i = M[offset_i];
  7822. M[offset_i] = (
  7823. (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
  7824. (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
  7825. );
  7826. }
  7827. // Shortcuts
  7828. var H = this._hash.words;
  7829. var M_offset_0 = M[offset + 0];
  7830. var M_offset_1 = M[offset + 1];
  7831. var M_offset_2 = M[offset + 2];
  7832. var M_offset_3 = M[offset + 3];
  7833. var M_offset_4 = M[offset + 4];
  7834. var M_offset_5 = M[offset + 5];
  7835. var M_offset_6 = M[offset + 6];
  7836. var M_offset_7 = M[offset + 7];
  7837. var M_offset_8 = M[offset + 8];
  7838. var M_offset_9 = M[offset + 9];
  7839. var M_offset_10 = M[offset + 10];
  7840. var M_offset_11 = M[offset + 11];
  7841. var M_offset_12 = M[offset + 12];
  7842. var M_offset_13 = M[offset + 13];
  7843. var M_offset_14 = M[offset + 14];
  7844. var M_offset_15 = M[offset + 15];
  7845. // Working varialbes
  7846. var a = H[0];
  7847. var b = H[1];
  7848. var c = H[2];
  7849. var d = H[3];
  7850. // Computation
  7851. a = FF(a, b, c, d, M_offset_0, 7, T[0]);
  7852. d = FF(d, a, b, c, M_offset_1, 12, T[1]);
  7853. c = FF(c, d, a, b, M_offset_2, 17, T[2]);
  7854. b = FF(b, c, d, a, M_offset_3, 22, T[3]);
  7855. a = FF(a, b, c, d, M_offset_4, 7, T[4]);
  7856. d = FF(d, a, b, c, M_offset_5, 12, T[5]);
  7857. c = FF(c, d, a, b, M_offset_6, 17, T[6]);
  7858. b = FF(b, c, d, a, M_offset_7, 22, T[7]);
  7859. a = FF(a, b, c, d, M_offset_8, 7, T[8]);
  7860. d = FF(d, a, b, c, M_offset_9, 12, T[9]);
  7861. c = FF(c, d, a, b, M_offset_10, 17, T[10]);
  7862. b = FF(b, c, d, a, M_offset_11, 22, T[11]);
  7863. a = FF(a, b, c, d, M_offset_12, 7, T[12]);
  7864. d = FF(d, a, b, c, M_offset_13, 12, T[13]);
  7865. c = FF(c, d, a, b, M_offset_14, 17, T[14]);
  7866. b = FF(b, c, d, a, M_offset_15, 22, T[15]);
  7867. a = GG(a, b, c, d, M_offset_1, 5, T[16]);
  7868. d = GG(d, a, b, c, M_offset_6, 9, T[17]);
  7869. c = GG(c, d, a, b, M_offset_11, 14, T[18]);
  7870. b = GG(b, c, d, a, M_offset_0, 20, T[19]);
  7871. a = GG(a, b, c, d, M_offset_5, 5, T[20]);
  7872. d = GG(d, a, b, c, M_offset_10, 9, T[21]);
  7873. c = GG(c, d, a, b, M_offset_15, 14, T[22]);
  7874. b = GG(b, c, d, a, M_offset_4, 20, T[23]);
  7875. a = GG(a, b, c, d, M_offset_9, 5, T[24]);
  7876. d = GG(d, a, b, c, M_offset_14, 9, T[25]);
  7877. c = GG(c, d, a, b, M_offset_3, 14, T[26]);
  7878. b = GG(b, c, d, a, M_offset_8, 20, T[27]);
  7879. a = GG(a, b, c, d, M_offset_13, 5, T[28]);
  7880. d = GG(d, a, b, c, M_offset_2, 9, T[29]);
  7881. c = GG(c, d, a, b, M_offset_7, 14, T[30]);
  7882. b = GG(b, c, d, a, M_offset_12, 20, T[31]);
  7883. a = HH(a, b, c, d, M_offset_5, 4, T[32]);
  7884. d = HH(d, a, b, c, M_offset_8, 11, T[33]);
  7885. c = HH(c, d, a, b, M_offset_11, 16, T[34]);
  7886. b = HH(b, c, d, a, M_offset_14, 23, T[35]);
  7887. a = HH(a, b, c, d, M_offset_1, 4, T[36]);
  7888. d = HH(d, a, b, c, M_offset_4, 11, T[37]);
  7889. c = HH(c, d, a, b, M_offset_7, 16, T[38]);
  7890. b = HH(b, c, d, a, M_offset_10, 23, T[39]);
  7891. a = HH(a, b, c, d, M_offset_13, 4, T[40]);
  7892. d = HH(d, a, b, c, M_offset_0, 11, T[41]);
  7893. c = HH(c, d, a, b, M_offset_3, 16, T[42]);
  7894. b = HH(b, c, d, a, M_offset_6, 23, T[43]);
  7895. a = HH(a, b, c, d, M_offset_9, 4, T[44]);
  7896. d = HH(d, a, b, c, M_offset_12, 11, T[45]);
  7897. c = HH(c, d, a, b, M_offset_15, 16, T[46]);
  7898. b = HH(b, c, d, a, M_offset_2, 23, T[47]);
  7899. a = II(a, b, c, d, M_offset_0, 6, T[48]);
  7900. d = II(d, a, b, c, M_offset_7, 10, T[49]);
  7901. c = II(c, d, a, b, M_offset_14, 15, T[50]);
  7902. b = II(b, c, d, a, M_offset_5, 21, T[51]);
  7903. a = II(a, b, c, d, M_offset_12, 6, T[52]);
  7904. d = II(d, a, b, c, M_offset_3, 10, T[53]);
  7905. c = II(c, d, a, b, M_offset_10, 15, T[54]);
  7906. b = II(b, c, d, a, M_offset_1, 21, T[55]);
  7907. a = II(a, b, c, d, M_offset_8, 6, T[56]);
  7908. d = II(d, a, b, c, M_offset_15, 10, T[57]);
  7909. c = II(c, d, a, b, M_offset_6, 15, T[58]);
  7910. b = II(b, c, d, a, M_offset_13, 21, T[59]);
  7911. a = II(a, b, c, d, M_offset_4, 6, T[60]);
  7912. d = II(d, a, b, c, M_offset_11, 10, T[61]);
  7913. c = II(c, d, a, b, M_offset_2, 15, T[62]);
  7914. b = II(b, c, d, a, M_offset_9, 21, T[63]);
  7915. // Intermediate hash value
  7916. H[0] = (H[0] + a) | 0;
  7917. H[1] = (H[1] + b) | 0;
  7918. H[2] = (H[2] + c) | 0;
  7919. H[3] = (H[3] + d) | 0;
  7920. },
  7921. _doFinalize: function () {
  7922. // Shortcuts
  7923. var data = this._data;
  7924. var dataWords = data.words;
  7925. var nBitsTotal = this._nDataBytes * 8;
  7926. var nBitsLeft = data.sigBytes * 8;
  7927. // Add padding
  7928. dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
  7929. var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);
  7930. var nBitsTotalL = nBitsTotal;
  7931. dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = (
  7932. (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) |
  7933. (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00)
  7934. );
  7935. dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
  7936. (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) |
  7937. (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00)
  7938. );
  7939. data.sigBytes = (dataWords.length + 1) * 4;
  7940. // Hash final blocks
  7941. this._process();
  7942. // Shortcuts
  7943. var hash = this._hash;
  7944. var H = hash.words;
  7945. // Swap endian
  7946. for (var i = 0; i < 4; i++) {
  7947. // Shortcut
  7948. var H_i = H[i];
  7949. H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
  7950. (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
  7951. }
  7952. // Return final computed hash
  7953. return hash;
  7954. },
  7955. clone: function () {
  7956. var clone = Hasher.clone.call(this);
  7957. clone._hash = this._hash.clone();
  7958. return clone;
  7959. }
  7960. });
  7961. function FF(a, b, c, d, x, s, t) {
  7962. var n = a + ((b & c) | (~b & d)) + x + t;
  7963. return ((n << s) | (n >>> (32 - s))) + b;
  7964. }
  7965. function GG(a, b, c, d, x, s, t) {
  7966. var n = a + ((b & d) | (c & ~d)) + x + t;
  7967. return ((n << s) | (n >>> (32 - s))) + b;
  7968. }
  7969. function HH(a, b, c, d, x, s, t) {
  7970. var n = a + (b ^ c ^ d) + x + t;
  7971. return ((n << s) | (n >>> (32 - s))) + b;
  7972. }
  7973. function II(a, b, c, d, x, s, t) {
  7974. var n = a + (c ^ (b | ~d)) + x + t;
  7975. return ((n << s) | (n >>> (32 - s))) + b;
  7976. }
  7977. /**
  7978. * Shortcut function to the hasher's object interface.
  7979. *
  7980. * @param {WordArray|string} message The message to hash.
  7981. *
  7982. * @return {WordArray} The hash.
  7983. *
  7984. * @static
  7985. *
  7986. * @example
  7987. *
  7988. * var hash = CryptoJS.MD5('message');
  7989. * var hash = CryptoJS.MD5(wordArray);
  7990. */
  7991. C.MD5 = Hasher._createHelper(MD5);
  7992. /**
  7993. * Shortcut function to the HMAC's object interface.
  7994. *
  7995. * @param {WordArray|string} message The message to hash.
  7996. * @param {WordArray|string} key The secret key.
  7997. *
  7998. * @return {WordArray} The HMAC.
  7999. *
  8000. * @static
  8001. *
  8002. * @example
  8003. *
  8004. * var hmac = CryptoJS.HmacMD5(message, key);
  8005. */
  8006. C.HmacMD5 = Hasher._createHmacHelper(MD5);
  8007. }(Math));
  8008. return CryptoJS.MD5;
  8009. }));
  8010. },{"./core":52}],61:[function(require,module,exports){
  8011. ;(function (root, factory, undef) {
  8012. if (typeof exports === "object") {
  8013. // CommonJS
  8014. module.exports = exports = factory(require("./core"), require("./cipher-core"));
  8015. }
  8016. else if (typeof define === "function" && define.amd) {
  8017. // AMD
  8018. define(["./core", "./cipher-core"], factory);
  8019. }
  8020. else {
  8021. // Global (browser)
  8022. factory(root.CryptoJS);
  8023. }
  8024. }(this, function (CryptoJS) {
  8025. /**
  8026. * Cipher Feedback block mode.
  8027. */
  8028. CryptoJS.mode.CFB = (function () {
  8029. var CFB = CryptoJS.lib.BlockCipherMode.extend();
  8030. CFB.Encryptor = CFB.extend({
  8031. processBlock: function (words, offset) {
  8032. // Shortcuts
  8033. var cipher = this._cipher;
  8034. var blockSize = cipher.blockSize;
  8035. generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
  8036. // Remember this block to use with next block
  8037. this._prevBlock = words.slice(offset, offset + blockSize);
  8038. }
  8039. });
  8040. CFB.Decryptor = CFB.extend({
  8041. processBlock: function (words, offset) {
  8042. // Shortcuts
  8043. var cipher = this._cipher;
  8044. var blockSize = cipher.blockSize;
  8045. // Remember this block to use with next block
  8046. var thisBlock = words.slice(offset, offset + blockSize);
  8047. generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
  8048. // This block becomes the previous block
  8049. this._prevBlock = thisBlock;
  8050. }
  8051. });
  8052. function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) {
  8053. // Shortcut
  8054. var iv = this._iv;
  8055. // Generate keystream
  8056. if (iv) {
  8057. var keystream = iv.slice(0);
  8058. // Remove IV for subsequent blocks
  8059. this._iv = undefined;
  8060. } else {
  8061. var keystream = this._prevBlock;
  8062. }
  8063. cipher.encryptBlock(keystream, 0);
  8064. // Encrypt
  8065. for (var i = 0; i < blockSize; i++) {
  8066. words[offset + i] ^= keystream[i];
  8067. }
  8068. }
  8069. return CFB;
  8070. }());
  8071. return CryptoJS.mode.CFB;
  8072. }));
  8073. },{"./cipher-core":51,"./core":52}],62:[function(require,module,exports){
  8074. ;(function (root, factory, undef) {
  8075. if (typeof exports === "object") {
  8076. // CommonJS
  8077. module.exports = exports = factory(require("./core"), require("./cipher-core"));
  8078. }
  8079. else if (typeof define === "function" && define.amd) {
  8080. // AMD
  8081. define(["./core", "./cipher-core"], factory);
  8082. }
  8083. else {
  8084. // Global (browser)
  8085. factory(root.CryptoJS);
  8086. }
  8087. }(this, function (CryptoJS) {
  8088. /** @preserve
  8089. * Counter block mode compatible with Dr Brian Gladman fileenc.c
  8090. * derived from CryptoJS.mode.CTR
  8091. * Jan Hruby jhruby.web@gmail.com
  8092. */
  8093. CryptoJS.mode.CTRGladman = (function () {
  8094. var CTRGladman = CryptoJS.lib.BlockCipherMode.extend();
  8095. function incWord(word)
  8096. {
  8097. if (((word >> 24) & 0xff) === 0xff) { //overflow
  8098. var b1 = (word >> 16)&0xff;
  8099. var b2 = (word >> 8)&0xff;
  8100. var b3 = word & 0xff;
  8101. if (b1 === 0xff) // overflow b1
  8102. {
  8103. b1 = 0;
  8104. if (b2 === 0xff)
  8105. {
  8106. b2 = 0;
  8107. if (b3 === 0xff)
  8108. {
  8109. b3 = 0;
  8110. }
  8111. else
  8112. {
  8113. ++b3;
  8114. }
  8115. }
  8116. else
  8117. {
  8118. ++b2;
  8119. }
  8120. }
  8121. else
  8122. {
  8123. ++b1;
  8124. }
  8125. word = 0;
  8126. word += (b1 << 16);
  8127. word += (b2 << 8);
  8128. word += b3;
  8129. }
  8130. else
  8131. {
  8132. word += (0x01 << 24);
  8133. }
  8134. return word;
  8135. }
  8136. function incCounter(counter)
  8137. {
  8138. if ((counter[0] = incWord(counter[0])) === 0)
  8139. {
  8140. // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8
  8141. counter[1] = incWord(counter[1]);
  8142. }
  8143. return counter;
  8144. }
  8145. var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
  8146. processBlock: function (words, offset) {
  8147. // Shortcuts
  8148. var cipher = this._cipher
  8149. var blockSize = cipher.blockSize;
  8150. var iv = this._iv;
  8151. var counter = this._counter;
  8152. // Generate keystream
  8153. if (iv) {
  8154. counter = this._counter = iv.slice(0);
  8155. // Remove IV for subsequent blocks
  8156. this._iv = undefined;
  8157. }
  8158. incCounter(counter);
  8159. var keystream = counter.slice(0);
  8160. cipher.encryptBlock(keystream, 0);
  8161. // Encrypt
  8162. for (var i = 0; i < blockSize; i++) {
  8163. words[offset + i] ^= keystream[i];
  8164. }
  8165. }
  8166. });
  8167. CTRGladman.Decryptor = Encryptor;
  8168. return CTRGladman;
  8169. }());
  8170. return CryptoJS.mode.CTRGladman;
  8171. }));
  8172. },{"./cipher-core":51,"./core":52}],63:[function(require,module,exports){
  8173. ;(function (root, factory, undef) {
  8174. if (typeof exports === "object") {
  8175. // CommonJS
  8176. module.exports = exports = factory(require("./core"), require("./cipher-core"));
  8177. }
  8178. else if (typeof define === "function" && define.amd) {
  8179. // AMD
  8180. define(["./core", "./cipher-core"], factory);
  8181. }
  8182. else {
  8183. // Global (browser)
  8184. factory(root.CryptoJS);
  8185. }
  8186. }(this, function (CryptoJS) {
  8187. /**
  8188. * Counter block mode.
  8189. */
  8190. CryptoJS.mode.CTR = (function () {
  8191. var CTR = CryptoJS.lib.BlockCipherMode.extend();
  8192. var Encryptor = CTR.Encryptor = CTR.extend({
  8193. processBlock: function (words, offset) {
  8194. // Shortcuts
  8195. var cipher = this._cipher
  8196. var blockSize = cipher.blockSize;
  8197. var iv = this._iv;
  8198. var counter = this._counter;
  8199. // Generate keystream
  8200. if (iv) {
  8201. counter = this._counter = iv.slice(0);
  8202. // Remove IV for subsequent blocks
  8203. this._iv = undefined;
  8204. }
  8205. var keystream = counter.slice(0);
  8206. cipher.encryptBlock(keystream, 0);
  8207. // Increment counter
  8208. counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0
  8209. // Encrypt
  8210. for (var i = 0; i < blockSize; i++) {
  8211. words[offset + i] ^= keystream[i];
  8212. }
  8213. }
  8214. });
  8215. CTR.Decryptor = Encryptor;
  8216. return CTR;
  8217. }());
  8218. return CryptoJS.mode.CTR;
  8219. }));
  8220. },{"./cipher-core":51,"./core":52}],64:[function(require,module,exports){
  8221. ;(function (root, factory, undef) {
  8222. if (typeof exports === "object") {
  8223. // CommonJS
  8224. module.exports = exports = factory(require("./core"), require("./cipher-core"));
  8225. }
  8226. else if (typeof define === "function" && define.amd) {
  8227. // AMD
  8228. define(["./core", "./cipher-core"], factory);
  8229. }
  8230. else {
  8231. // Global (browser)
  8232. factory(root.CryptoJS);
  8233. }
  8234. }(this, function (CryptoJS) {
  8235. /**
  8236. * Electronic Codebook block mode.
  8237. */
  8238. CryptoJS.mode.ECB = (function () {
  8239. var ECB = CryptoJS.lib.BlockCipherMode.extend();
  8240. ECB.Encryptor = ECB.extend({
  8241. processBlock: function (words, offset) {
  8242. this._cipher.encryptBlock(words, offset);
  8243. }
  8244. });
  8245. ECB.Decryptor = ECB.extend({
  8246. processBlock: function (words, offset) {
  8247. this._cipher.decryptBlock(words, offset);
  8248. }
  8249. });
  8250. return ECB;
  8251. }());
  8252. return CryptoJS.mode.ECB;
  8253. }));
  8254. },{"./cipher-core":51,"./core":52}],65:[function(require,module,exports){
  8255. ;(function (root, factory, undef) {
  8256. if (typeof exports === "object") {
  8257. // CommonJS
  8258. module.exports = exports = factory(require("./core"), require("./cipher-core"));
  8259. }
  8260. else if (typeof define === "function" && define.amd) {
  8261. // AMD
  8262. define(["./core", "./cipher-core"], factory);
  8263. }
  8264. else {
  8265. // Global (browser)
  8266. factory(root.CryptoJS);
  8267. }
  8268. }(this, function (CryptoJS) {
  8269. /**
  8270. * Output Feedback block mode.
  8271. */
  8272. CryptoJS.mode.OFB = (function () {
  8273. var OFB = CryptoJS.lib.BlockCipherMode.extend();
  8274. var Encryptor = OFB.Encryptor = OFB.extend({
  8275. processBlock: function (words, offset) {
  8276. // Shortcuts
  8277. var cipher = this._cipher
  8278. var blockSize = cipher.blockSize;
  8279. var iv = this._iv;
  8280. var keystream = this._keystream;
  8281. // Generate keystream
  8282. if (iv) {
  8283. keystream = this._keystream = iv.slice(0);
  8284. // Remove IV for subsequent blocks
  8285. this._iv = undefined;
  8286. }
  8287. cipher.encryptBlock(keystream, 0);
  8288. // Encrypt
  8289. for (var i = 0; i < blockSize; i++) {
  8290. words[offset + i] ^= keystream[i];
  8291. }
  8292. }
  8293. });
  8294. OFB.Decryptor = Encryptor;
  8295. return OFB;
  8296. }());
  8297. return CryptoJS.mode.OFB;
  8298. }));
  8299. },{"./cipher-core":51,"./core":52}],66:[function(require,module,exports){
  8300. ;(function (root, factory, undef) {
  8301. if (typeof exports === "object") {
  8302. // CommonJS
  8303. module.exports = exports = factory(require("./core"), require("./cipher-core"));
  8304. }
  8305. else if (typeof define === "function" && define.amd) {
  8306. // AMD
  8307. define(["./core", "./cipher-core"], factory);
  8308. }
  8309. else {
  8310. // Global (browser)
  8311. factory(root.CryptoJS);
  8312. }
  8313. }(this, function (CryptoJS) {
  8314. /**
  8315. * ANSI X.923 padding strategy.
  8316. */
  8317. CryptoJS.pad.AnsiX923 = {
  8318. pad: function (data, blockSize) {
  8319. // Shortcuts
  8320. var dataSigBytes = data.sigBytes;
  8321. var blockSizeBytes = blockSize * 4;
  8322. // Count padding bytes
  8323. var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes;
  8324. // Compute last byte position
  8325. var lastBytePos = dataSigBytes + nPaddingBytes - 1;
  8326. // Pad
  8327. data.clamp();
  8328. data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8);
  8329. data.sigBytes += nPaddingBytes;
  8330. },
  8331. unpad: function (data) {
  8332. // Get number of padding bytes from last byte
  8333. var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
  8334. // Remove padding
  8335. data.sigBytes -= nPaddingBytes;
  8336. }
  8337. };
  8338. return CryptoJS.pad.Ansix923;
  8339. }));
  8340. },{"./cipher-core":51,"./core":52}],67:[function(require,module,exports){
  8341. ;(function (root, factory, undef) {
  8342. if (typeof exports === "object") {
  8343. // CommonJS
  8344. module.exports = exports = factory(require("./core"), require("./cipher-core"));
  8345. }
  8346. else if (typeof define === "function" && define.amd) {
  8347. // AMD
  8348. define(["./core", "./cipher-core"], factory);
  8349. }
  8350. else {
  8351. // Global (browser)
  8352. factory(root.CryptoJS);
  8353. }
  8354. }(this, function (CryptoJS) {
  8355. /**
  8356. * ISO 10126 padding strategy.
  8357. */
  8358. CryptoJS.pad.Iso10126 = {
  8359. pad: function (data, blockSize) {
  8360. // Shortcut
  8361. var blockSizeBytes = blockSize * 4;
  8362. // Count padding bytes
  8363. var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
  8364. // Pad
  8365. data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)).
  8366. concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1));
  8367. },
  8368. unpad: function (data) {
  8369. // Get number of padding bytes from last byte
  8370. var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
  8371. // Remove padding
  8372. data.sigBytes -= nPaddingBytes;
  8373. }
  8374. };
  8375. return CryptoJS.pad.Iso10126;
  8376. }));
  8377. },{"./cipher-core":51,"./core":52}],68:[function(require,module,exports){
  8378. ;(function (root, factory, undef) {
  8379. if (typeof exports === "object") {
  8380. // CommonJS
  8381. module.exports = exports = factory(require("./core"), require("./cipher-core"));
  8382. }
  8383. else if (typeof define === "function" && define.amd) {
  8384. // AMD
  8385. define(["./core", "./cipher-core"], factory);
  8386. }
  8387. else {
  8388. // Global (browser)
  8389. factory(root.CryptoJS);
  8390. }
  8391. }(this, function (CryptoJS) {
  8392. /**
  8393. * ISO/IEC 9797-1 Padding Method 2.
  8394. */
  8395. CryptoJS.pad.Iso97971 = {
  8396. pad: function (data, blockSize) {
  8397. // Add 0x80 byte
  8398. data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1));
  8399. // Zero pad the rest
  8400. CryptoJS.pad.ZeroPadding.pad(data, blockSize);
  8401. },
  8402. unpad: function (data) {
  8403. // Remove zero padding
  8404. CryptoJS.pad.ZeroPadding.unpad(data);
  8405. // Remove one more byte -- the 0x80 byte
  8406. data.sigBytes--;
  8407. }
  8408. };
  8409. return CryptoJS.pad.Iso97971;
  8410. }));
  8411. },{"./cipher-core":51,"./core":52}],69:[function(require,module,exports){
  8412. ;(function (root, factory, undef) {
  8413. if (typeof exports === "object") {
  8414. // CommonJS
  8415. module.exports = exports = factory(require("./core"), require("./cipher-core"));
  8416. }
  8417. else if (typeof define === "function" && define.amd) {
  8418. // AMD
  8419. define(["./core", "./cipher-core"], factory);
  8420. }
  8421. else {
  8422. // Global (browser)
  8423. factory(root.CryptoJS);
  8424. }
  8425. }(this, function (CryptoJS) {
  8426. /**
  8427. * A noop padding strategy.
  8428. */
  8429. CryptoJS.pad.NoPadding = {
  8430. pad: function () {
  8431. },
  8432. unpad: function () {
  8433. }
  8434. };
  8435. return CryptoJS.pad.NoPadding;
  8436. }));
  8437. },{"./cipher-core":51,"./core":52}],70:[function(require,module,exports){
  8438. ;(function (root, factory, undef) {
  8439. if (typeof exports === "object") {
  8440. // CommonJS
  8441. module.exports = exports = factory(require("./core"), require("./cipher-core"));
  8442. }
  8443. else if (typeof define === "function" && define.amd) {
  8444. // AMD
  8445. define(["./core", "./cipher-core"], factory);
  8446. }
  8447. else {
  8448. // Global (browser)
  8449. factory(root.CryptoJS);
  8450. }
  8451. }(this, function (CryptoJS) {
  8452. /**
  8453. * Zero padding strategy.
  8454. */
  8455. CryptoJS.pad.ZeroPadding = {
  8456. pad: function (data, blockSize) {
  8457. // Shortcut
  8458. var blockSizeBytes = blockSize * 4;
  8459. // Pad
  8460. data.clamp();
  8461. data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes);
  8462. },
  8463. unpad: function (data) {
  8464. // Shortcut
  8465. var dataWords = data.words;
  8466. // Unpad
  8467. var i = data.sigBytes - 1;
  8468. while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) {
  8469. i--;
  8470. }
  8471. data.sigBytes = i + 1;
  8472. }
  8473. };
  8474. return CryptoJS.pad.ZeroPadding;
  8475. }));
  8476. },{"./cipher-core":51,"./core":52}],71:[function(require,module,exports){
  8477. ;(function (root, factory, undef) {
  8478. if (typeof exports === "object") {
  8479. // CommonJS
  8480. module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac"));
  8481. }
  8482. else if (typeof define === "function" && define.amd) {
  8483. // AMD
  8484. define(["./core", "./sha1", "./hmac"], factory);
  8485. }
  8486. else {
  8487. // Global (browser)
  8488. factory(root.CryptoJS);
  8489. }
  8490. }(this, function (CryptoJS) {
  8491. (function () {
  8492. // Shortcuts
  8493. var C = CryptoJS;
  8494. var C_lib = C.lib;
  8495. var Base = C_lib.Base;
  8496. var WordArray = C_lib.WordArray;
  8497. var C_algo = C.algo;
  8498. var SHA1 = C_algo.SHA1;
  8499. var HMAC = C_algo.HMAC;
  8500. /**
  8501. * Password-Based Key Derivation Function 2 algorithm.
  8502. */
  8503. var PBKDF2 = C_algo.PBKDF2 = Base.extend({
  8504. /**
  8505. * Configuration options.
  8506. *
  8507. * @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
  8508. * @property {Hasher} hasher The hasher to use. Default: SHA1
  8509. * @property {number} iterations The number of iterations to perform. Default: 1
  8510. */
  8511. cfg: Base.extend({
  8512. keySize: 128/32,
  8513. hasher: SHA1,
  8514. iterations: 1
  8515. }),
  8516. /**
  8517. * Initializes a newly created key derivation function.
  8518. *
  8519. * @param {Object} cfg (Optional) The configuration options to use for the derivation.
  8520. *
  8521. * @example
  8522. *
  8523. * var kdf = CryptoJS.algo.PBKDF2.create();
  8524. * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
  8525. * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
  8526. */
  8527. init: function (cfg) {
  8528. this.cfg = this.cfg.extend(cfg);
  8529. },
  8530. /**
  8531. * Computes the Password-Based Key Derivation Function 2.
  8532. *
  8533. * @param {WordArray|string} password The password.
  8534. * @param {WordArray|string} salt A salt.
  8535. *
  8536. * @return {WordArray} The derived key.
  8537. *
  8538. * @example
  8539. *
  8540. * var key = kdf.compute(password, salt);
  8541. */
  8542. compute: function (password, salt) {
  8543. // Shortcut
  8544. var cfg = this.cfg;
  8545. // Init HMAC
  8546. var hmac = HMAC.create(cfg.hasher, password);
  8547. // Initial values
  8548. var derivedKey = WordArray.create();
  8549. var blockIndex = WordArray.create([0x00000001]);
  8550. // Shortcuts
  8551. var derivedKeyWords = derivedKey.words;
  8552. var blockIndexWords = blockIndex.words;
  8553. var keySize = cfg.keySize;
  8554. var iterations = cfg.iterations;
  8555. // Generate key
  8556. while (derivedKeyWords.length < keySize) {
  8557. var block = hmac.update(salt).finalize(blockIndex);
  8558. hmac.reset();
  8559. // Shortcuts
  8560. var blockWords = block.words;
  8561. var blockWordsLength = blockWords.length;
  8562. // Iterations
  8563. var intermediate = block;
  8564. for (var i = 1; i < iterations; i++) {
  8565. intermediate = hmac.finalize(intermediate);
  8566. hmac.reset();
  8567. // Shortcut
  8568. var intermediateWords = intermediate.words;
  8569. // XOR intermediate with block
  8570. for (var j = 0; j < blockWordsLength; j++) {
  8571. blockWords[j] ^= intermediateWords[j];
  8572. }
  8573. }
  8574. derivedKey.concat(block);
  8575. blockIndexWords[0]++;
  8576. }
  8577. derivedKey.sigBytes = keySize * 4;
  8578. return derivedKey;
  8579. }
  8580. });
  8581. /**
  8582. * Computes the Password-Based Key Derivation Function 2.
  8583. *
  8584. * @param {WordArray|string} password The password.
  8585. * @param {WordArray|string} salt A salt.
  8586. * @param {Object} cfg (Optional) The configuration options to use for this computation.
  8587. *
  8588. * @return {WordArray} The derived key.
  8589. *
  8590. * @static
  8591. *
  8592. * @example
  8593. *
  8594. * var key = CryptoJS.PBKDF2(password, salt);
  8595. * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 });
  8596. * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 });
  8597. */
  8598. C.PBKDF2 = function (password, salt, cfg) {
  8599. return PBKDF2.create(cfg).compute(password, salt);
  8600. };
  8601. }());
  8602. return CryptoJS.PBKDF2;
  8603. }));
  8604. },{"./core":52,"./hmac":57,"./sha1":76}],72:[function(require,module,exports){
  8605. ;(function (root, factory, undef) {
  8606. if (typeof exports === "object") {
  8607. // CommonJS
  8608. module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core"));
  8609. }
  8610. else if (typeof define === "function" && define.amd) {
  8611. // AMD
  8612. define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
  8613. }
  8614. else {
  8615. // Global (browser)
  8616. factory(root.CryptoJS);
  8617. }
  8618. }(this, function (CryptoJS) {
  8619. (function () {
  8620. // Shortcuts
  8621. var C = CryptoJS;
  8622. var C_lib = C.lib;
  8623. var StreamCipher = C_lib.StreamCipher;
  8624. var C_algo = C.algo;
  8625. // Reusable objects
  8626. var S = [];
  8627. var C_ = [];
  8628. var G = [];
  8629. /**
  8630. * Rabbit stream cipher algorithm.
  8631. *
  8632. * This is a legacy version that neglected to convert the key to little-endian.
  8633. * This error doesn't affect the cipher's security,
  8634. * but it does affect its compatibility with other implementations.
  8635. */
  8636. var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
  8637. _doReset: function () {
  8638. // Shortcuts
  8639. var K = this._key.words;
  8640. var iv = this.cfg.iv;
  8641. // Generate initial state values
  8642. var X = this._X = [
  8643. K[0], (K[3] << 16) | (K[2] >>> 16),
  8644. K[1], (K[0] << 16) | (K[3] >>> 16),
  8645. K[2], (K[1] << 16) | (K[0] >>> 16),
  8646. K[3], (K[2] << 16) | (K[1] >>> 16)
  8647. ];
  8648. // Generate initial counter values
  8649. var C = this._C = [
  8650. (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
  8651. (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
  8652. (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
  8653. (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
  8654. ];
  8655. // Carry bit
  8656. this._b = 0;
  8657. // Iterate the system four times
  8658. for (var i = 0; i < 4; i++) {
  8659. nextState.call(this);
  8660. }
  8661. // Modify the counters
  8662. for (var i = 0; i < 8; i++) {
  8663. C[i] ^= X[(i + 4) & 7];
  8664. }
  8665. // IV setup
  8666. if (iv) {
  8667. // Shortcuts
  8668. var IV = iv.words;
  8669. var IV_0 = IV[0];
  8670. var IV_1 = IV[1];
  8671. // Generate four subvectors
  8672. var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
  8673. var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
  8674. var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
  8675. var i3 = (i2 << 16) | (i0 & 0x0000ffff);
  8676. // Modify counter values
  8677. C[0] ^= i0;
  8678. C[1] ^= i1;
  8679. C[2] ^= i2;
  8680. C[3] ^= i3;
  8681. C[4] ^= i0;
  8682. C[5] ^= i1;
  8683. C[6] ^= i2;
  8684. C[7] ^= i3;
  8685. // Iterate the system four times
  8686. for (var i = 0; i < 4; i++) {
  8687. nextState.call(this);
  8688. }
  8689. }
  8690. },
  8691. _doProcessBlock: function (M, offset) {
  8692. // Shortcut
  8693. var X = this._X;
  8694. // Iterate the system
  8695. nextState.call(this);
  8696. // Generate four keystream words
  8697. S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
  8698. S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
  8699. S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
  8700. S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
  8701. for (var i = 0; i < 4; i++) {
  8702. // Swap endian
  8703. S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
  8704. (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
  8705. // Encrypt
  8706. M[offset + i] ^= S[i];
  8707. }
  8708. },
  8709. blockSize: 128/32,
  8710. ivSize: 64/32
  8711. });
  8712. function nextState() {
  8713. // Shortcuts
  8714. var X = this._X;
  8715. var C = this._C;
  8716. // Save old counter values
  8717. for (var i = 0; i < 8; i++) {
  8718. C_[i] = C[i];
  8719. }
  8720. // Calculate new counter values
  8721. C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
  8722. C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
  8723. C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
  8724. C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
  8725. C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
  8726. C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
  8727. C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
  8728. C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
  8729. this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
  8730. // Calculate the g-values
  8731. for (var i = 0; i < 8; i++) {
  8732. var gx = X[i] + C[i];
  8733. // Construct high and low argument for squaring
  8734. var ga = gx & 0xffff;
  8735. var gb = gx >>> 16;
  8736. // Calculate high and low result of squaring
  8737. var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
  8738. var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
  8739. // High XOR low
  8740. G[i] = gh ^ gl;
  8741. }
  8742. // Calculate new state values
  8743. X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
  8744. X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
  8745. X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
  8746. X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
  8747. X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
  8748. X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
  8749. X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
  8750. X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
  8751. }
  8752. /**
  8753. * Shortcut functions to the cipher's object interface.
  8754. *
  8755. * @example
  8756. *
  8757. * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg);
  8758. * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg);
  8759. */
  8760. C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
  8761. }());
  8762. return CryptoJS.RabbitLegacy;
  8763. }));
  8764. },{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],73:[function(require,module,exports){
  8765. ;(function (root, factory, undef) {
  8766. if (typeof exports === "object") {
  8767. // CommonJS
  8768. module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core"));
  8769. }
  8770. else if (typeof define === "function" && define.amd) {
  8771. // AMD
  8772. define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
  8773. }
  8774. else {
  8775. // Global (browser)
  8776. factory(root.CryptoJS);
  8777. }
  8778. }(this, function (CryptoJS) {
  8779. (function () {
  8780. // Shortcuts
  8781. var C = CryptoJS;
  8782. var C_lib = C.lib;
  8783. var StreamCipher = C_lib.StreamCipher;
  8784. var C_algo = C.algo;
  8785. // Reusable objects
  8786. var S = [];
  8787. var C_ = [];
  8788. var G = [];
  8789. /**
  8790. * Rabbit stream cipher algorithm
  8791. */
  8792. var Rabbit = C_algo.Rabbit = StreamCipher.extend({
  8793. _doReset: function () {
  8794. // Shortcuts
  8795. var K = this._key.words;
  8796. var iv = this.cfg.iv;
  8797. // Swap endian
  8798. for (var i = 0; i < 4; i++) {
  8799. K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) |
  8800. (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00);
  8801. }
  8802. // Generate initial state values
  8803. var X = this._X = [
  8804. K[0], (K[3] << 16) | (K[2] >>> 16),
  8805. K[1], (K[0] << 16) | (K[3] >>> 16),
  8806. K[2], (K[1] << 16) | (K[0] >>> 16),
  8807. K[3], (K[2] << 16) | (K[1] >>> 16)
  8808. ];
  8809. // Generate initial counter values
  8810. var C = this._C = [
  8811. (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
  8812. (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
  8813. (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
  8814. (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
  8815. ];
  8816. // Carry bit
  8817. this._b = 0;
  8818. // Iterate the system four times
  8819. for (var i = 0; i < 4; i++) {
  8820. nextState.call(this);
  8821. }
  8822. // Modify the counters
  8823. for (var i = 0; i < 8; i++) {
  8824. C[i] ^= X[(i + 4) & 7];
  8825. }
  8826. // IV setup
  8827. if (iv) {
  8828. // Shortcuts
  8829. var IV = iv.words;
  8830. var IV_0 = IV[0];
  8831. var IV_1 = IV[1];
  8832. // Generate four subvectors
  8833. var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
  8834. var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
  8835. var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
  8836. var i3 = (i2 << 16) | (i0 & 0x0000ffff);
  8837. // Modify counter values
  8838. C[0] ^= i0;
  8839. C[1] ^= i1;
  8840. C[2] ^= i2;
  8841. C[3] ^= i3;
  8842. C[4] ^= i0;
  8843. C[5] ^= i1;
  8844. C[6] ^= i2;
  8845. C[7] ^= i3;
  8846. // Iterate the system four times
  8847. for (var i = 0; i < 4; i++) {
  8848. nextState.call(this);
  8849. }
  8850. }
  8851. },
  8852. _doProcessBlock: function (M, offset) {
  8853. // Shortcut
  8854. var X = this._X;
  8855. // Iterate the system
  8856. nextState.call(this);
  8857. // Generate four keystream words
  8858. S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
  8859. S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
  8860. S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
  8861. S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
  8862. for (var i = 0; i < 4; i++) {
  8863. // Swap endian
  8864. S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
  8865. (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
  8866. // Encrypt
  8867. M[offset + i] ^= S[i];
  8868. }
  8869. },
  8870. blockSize: 128/32,
  8871. ivSize: 64/32
  8872. });
  8873. function nextState() {
  8874. // Shortcuts
  8875. var X = this._X;
  8876. var C = this._C;
  8877. // Save old counter values
  8878. for (var i = 0; i < 8; i++) {
  8879. C_[i] = C[i];
  8880. }
  8881. // Calculate new counter values
  8882. C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
  8883. C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
  8884. C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
  8885. C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
  8886. C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
  8887. C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
  8888. C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
  8889. C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
  8890. this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
  8891. // Calculate the g-values
  8892. for (var i = 0; i < 8; i++) {
  8893. var gx = X[i] + C[i];
  8894. // Construct high and low argument for squaring
  8895. var ga = gx & 0xffff;
  8896. var gb = gx >>> 16;
  8897. // Calculate high and low result of squaring
  8898. var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
  8899. var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
  8900. // High XOR low
  8901. G[i] = gh ^ gl;
  8902. }
  8903. // Calculate new state values
  8904. X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
  8905. X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
  8906. X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
  8907. X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
  8908. X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
  8909. X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
  8910. X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
  8911. X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
  8912. }
  8913. /**
  8914. * Shortcut functions to the cipher's object interface.
  8915. *
  8916. * @example
  8917. *
  8918. * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg);
  8919. * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg);
  8920. */
  8921. C.Rabbit = StreamCipher._createHelper(Rabbit);
  8922. }());
  8923. return CryptoJS.Rabbit;
  8924. }));
  8925. },{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],74:[function(require,module,exports){
  8926. ;(function (root, factory, undef) {
  8927. if (typeof exports === "object") {
  8928. // CommonJS
  8929. module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core"));
  8930. }
  8931. else if (typeof define === "function" && define.amd) {
  8932. // AMD
  8933. define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
  8934. }
  8935. else {
  8936. // Global (browser)
  8937. factory(root.CryptoJS);
  8938. }
  8939. }(this, function (CryptoJS) {
  8940. (function () {
  8941. // Shortcuts
  8942. var C = CryptoJS;
  8943. var C_lib = C.lib;
  8944. var StreamCipher = C_lib.StreamCipher;
  8945. var C_algo = C.algo;
  8946. /**
  8947. * RC4 stream cipher algorithm.
  8948. */
  8949. var RC4 = C_algo.RC4 = StreamCipher.extend({
  8950. _doReset: function () {
  8951. // Shortcuts
  8952. var key = this._key;
  8953. var keyWords = key.words;
  8954. var keySigBytes = key.sigBytes;
  8955. // Init sbox
  8956. var S = this._S = [];
  8957. for (var i = 0; i < 256; i++) {
  8958. S[i] = i;
  8959. }
  8960. // Key setup
  8961. for (var i = 0, j = 0; i < 256; i++) {
  8962. var keyByteIndex = i % keySigBytes;
  8963. var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff;
  8964. j = (j + S[i] + keyByte) % 256;
  8965. // Swap
  8966. var t = S[i];
  8967. S[i] = S[j];
  8968. S[j] = t;
  8969. }
  8970. // Counters
  8971. this._i = this._j = 0;
  8972. },
  8973. _doProcessBlock: function (M, offset) {
  8974. M[offset] ^= generateKeystreamWord.call(this);
  8975. },
  8976. keySize: 256/32,
  8977. ivSize: 0
  8978. });
  8979. function generateKeystreamWord() {
  8980. // Shortcuts
  8981. var S = this._S;
  8982. var i = this._i;
  8983. var j = this._j;
  8984. // Generate keystream word
  8985. var keystreamWord = 0;
  8986. for (var n = 0; n < 4; n++) {
  8987. i = (i + 1) % 256;
  8988. j = (j + S[i]) % 256;
  8989. // Swap
  8990. var t = S[i];
  8991. S[i] = S[j];
  8992. S[j] = t;
  8993. keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8);
  8994. }
  8995. // Update counters
  8996. this._i = i;
  8997. this._j = j;
  8998. return keystreamWord;
  8999. }
  9000. /**
  9001. * Shortcut functions to the cipher's object interface.
  9002. *
  9003. * @example
  9004. *
  9005. * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg);
  9006. * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg);
  9007. */
  9008. C.RC4 = StreamCipher._createHelper(RC4);
  9009. /**
  9010. * Modified RC4 stream cipher algorithm.
  9011. */
  9012. var RC4Drop = C_algo.RC4Drop = RC4.extend({
  9013. /**
  9014. * Configuration options.
  9015. *
  9016. * @property {number} drop The number of keystream words to drop. Default 192
  9017. */
  9018. cfg: RC4.cfg.extend({
  9019. drop: 192
  9020. }),
  9021. _doReset: function () {
  9022. RC4._doReset.call(this);
  9023. // Drop
  9024. for (var i = this.cfg.drop; i > 0; i--) {
  9025. generateKeystreamWord.call(this);
  9026. }
  9027. }
  9028. });
  9029. /**
  9030. * Shortcut functions to the cipher's object interface.
  9031. *
  9032. * @example
  9033. *
  9034. * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg);
  9035. * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg);
  9036. */
  9037. C.RC4Drop = StreamCipher._createHelper(RC4Drop);
  9038. }());
  9039. return CryptoJS.RC4;
  9040. }));
  9041. },{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],75:[function(require,module,exports){
  9042. ;(function (root, factory) {
  9043. if (typeof exports === "object") {
  9044. // CommonJS
  9045. module.exports = exports = factory(require("./core"));
  9046. }
  9047. else if (typeof define === "function" && define.amd) {
  9048. // AMD
  9049. define(["./core"], factory);
  9050. }
  9051. else {
  9052. // Global (browser)
  9053. factory(root.CryptoJS);
  9054. }
  9055. }(this, function (CryptoJS) {
  9056. /** @preserve
  9057. (c) 2012 by Cédric Mesnil. All rights reserved.
  9058. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
  9059. - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  9060. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  9061. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  9062. */
  9063. (function (Math) {
  9064. // Shortcuts
  9065. var C = CryptoJS;
  9066. var C_lib = C.lib;
  9067. var WordArray = C_lib.WordArray;
  9068. var Hasher = C_lib.Hasher;
  9069. var C_algo = C.algo;
  9070. // Constants table
  9071. var _zl = WordArray.create([
  9072. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
  9073. 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
  9074. 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
  9075. 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
  9076. 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]);
  9077. var _zr = WordArray.create([
  9078. 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
  9079. 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
  9080. 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
  9081. 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
  9082. 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]);
  9083. var _sl = WordArray.create([
  9084. 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
  9085. 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
  9086. 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
  9087. 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
  9088. 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]);
  9089. var _sr = WordArray.create([
  9090. 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
  9091. 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
  9092. 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
  9093. 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
  9094. 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]);
  9095. var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]);
  9096. var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]);
  9097. /**
  9098. * RIPEMD160 hash algorithm.
  9099. */
  9100. var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({
  9101. _doReset: function () {
  9102. this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]);
  9103. },
  9104. _doProcessBlock: function (M, offset) {
  9105. // Swap endian
  9106. for (var i = 0; i < 16; i++) {
  9107. // Shortcuts
  9108. var offset_i = offset + i;
  9109. var M_offset_i = M[offset_i];
  9110. // Swap
  9111. M[offset_i] = (
  9112. (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
  9113. (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
  9114. );
  9115. }
  9116. // Shortcut
  9117. var H = this._hash.words;
  9118. var hl = _hl.words;
  9119. var hr = _hr.words;
  9120. var zl = _zl.words;
  9121. var zr = _zr.words;
  9122. var sl = _sl.words;
  9123. var sr = _sr.words;
  9124. // Working variables
  9125. var al, bl, cl, dl, el;
  9126. var ar, br, cr, dr, er;
  9127. ar = al = H[0];
  9128. br = bl = H[1];
  9129. cr = cl = H[2];
  9130. dr = dl = H[3];
  9131. er = el = H[4];
  9132. // Computation
  9133. var t;
  9134. for (var i = 0; i < 80; i += 1) {
  9135. t = (al + M[offset+zl[i]])|0;
  9136. if (i<16){
  9137. t += f1(bl,cl,dl) + hl[0];
  9138. } else if (i<32) {
  9139. t += f2(bl,cl,dl) + hl[1];
  9140. } else if (i<48) {
  9141. t += f3(bl,cl,dl) + hl[2];
  9142. } else if (i<64) {
  9143. t += f4(bl,cl,dl) + hl[3];
  9144. } else {// if (i<80) {
  9145. t += f5(bl,cl,dl) + hl[4];
  9146. }
  9147. t = t|0;
  9148. t = rotl(t,sl[i]);
  9149. t = (t+el)|0;
  9150. al = el;
  9151. el = dl;
  9152. dl = rotl(cl, 10);
  9153. cl = bl;
  9154. bl = t;
  9155. t = (ar + M[offset+zr[i]])|0;
  9156. if (i<16){
  9157. t += f5(br,cr,dr) + hr[0];
  9158. } else if (i<32) {
  9159. t += f4(br,cr,dr) + hr[1];
  9160. } else if (i<48) {
  9161. t += f3(br,cr,dr) + hr[2];
  9162. } else if (i<64) {
  9163. t += f2(br,cr,dr) + hr[3];
  9164. } else {// if (i<80) {
  9165. t += f1(br,cr,dr) + hr[4];
  9166. }
  9167. t = t|0;
  9168. t = rotl(t,sr[i]) ;
  9169. t = (t+er)|0;
  9170. ar = er;
  9171. er = dr;
  9172. dr = rotl(cr, 10);
  9173. cr = br;
  9174. br = t;
  9175. }
  9176. // Intermediate hash value
  9177. t = (H[1] + cl + dr)|0;
  9178. H[1] = (H[2] + dl + er)|0;
  9179. H[2] = (H[3] + el + ar)|0;
  9180. H[3] = (H[4] + al + br)|0;
  9181. H[4] = (H[0] + bl + cr)|0;
  9182. H[0] = t;
  9183. },
  9184. _doFinalize: function () {
  9185. // Shortcuts
  9186. var data = this._data;
  9187. var dataWords = data.words;
  9188. var nBitsTotal = this._nDataBytes * 8;
  9189. var nBitsLeft = data.sigBytes * 8;
  9190. // Add padding
  9191. dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
  9192. dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
  9193. (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
  9194. (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
  9195. );
  9196. data.sigBytes = (dataWords.length + 1) * 4;
  9197. // Hash final blocks
  9198. this._process();
  9199. // Shortcuts
  9200. var hash = this._hash;
  9201. var H = hash.words;
  9202. // Swap endian
  9203. for (var i = 0; i < 5; i++) {
  9204. // Shortcut
  9205. var H_i = H[i];
  9206. // Swap
  9207. H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
  9208. (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
  9209. }
  9210. // Return final computed hash
  9211. return hash;
  9212. },
  9213. clone: function () {
  9214. var clone = Hasher.clone.call(this);
  9215. clone._hash = this._hash.clone();
  9216. return clone;
  9217. }
  9218. });
  9219. function f1(x, y, z) {
  9220. return ((x) ^ (y) ^ (z));
  9221. }
  9222. function f2(x, y, z) {
  9223. return (((x)&(y)) | ((~x)&(z)));
  9224. }
  9225. function f3(x, y, z) {
  9226. return (((x) | (~(y))) ^ (z));
  9227. }
  9228. function f4(x, y, z) {
  9229. return (((x) & (z)) | ((y)&(~(z))));
  9230. }
  9231. function f5(x, y, z) {
  9232. return ((x) ^ ((y) |(~(z))));
  9233. }
  9234. function rotl(x,n) {
  9235. return (x<<n) | (x>>>(32-n));
  9236. }
  9237. /**
  9238. * Shortcut function to the hasher's object interface.
  9239. *
  9240. * @param {WordArray|string} message The message to hash.
  9241. *
  9242. * @return {WordArray} The hash.
  9243. *
  9244. * @static
  9245. *
  9246. * @example
  9247. *
  9248. * var hash = CryptoJS.RIPEMD160('message');
  9249. * var hash = CryptoJS.RIPEMD160(wordArray);
  9250. */
  9251. C.RIPEMD160 = Hasher._createHelper(RIPEMD160);
  9252. /**
  9253. * Shortcut function to the HMAC's object interface.
  9254. *
  9255. * @param {WordArray|string} message The message to hash.
  9256. * @param {WordArray|string} key The secret key.
  9257. *
  9258. * @return {WordArray} The HMAC.
  9259. *
  9260. * @static
  9261. *
  9262. * @example
  9263. *
  9264. * var hmac = CryptoJS.HmacRIPEMD160(message, key);
  9265. */
  9266. C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160);
  9267. }(Math));
  9268. return CryptoJS.RIPEMD160;
  9269. }));
  9270. },{"./core":52}],76:[function(require,module,exports){
  9271. ;(function (root, factory) {
  9272. if (typeof exports === "object") {
  9273. // CommonJS
  9274. module.exports = exports = factory(require("./core"));
  9275. }
  9276. else if (typeof define === "function" && define.amd) {
  9277. // AMD
  9278. define(["./core"], factory);
  9279. }
  9280. else {
  9281. // Global (browser)
  9282. factory(root.CryptoJS);
  9283. }
  9284. }(this, function (CryptoJS) {
  9285. (function () {
  9286. // Shortcuts
  9287. var C = CryptoJS;
  9288. var C_lib = C.lib;
  9289. var WordArray = C_lib.WordArray;
  9290. var Hasher = C_lib.Hasher;
  9291. var C_algo = C.algo;
  9292. // Reusable object
  9293. var W = [];
  9294. /**
  9295. * SHA-1 hash algorithm.
  9296. */
  9297. var SHA1 = C_algo.SHA1 = Hasher.extend({
  9298. _doReset: function () {
  9299. this._hash = new WordArray.init([
  9300. 0x67452301, 0xefcdab89,
  9301. 0x98badcfe, 0x10325476,
  9302. 0xc3d2e1f0
  9303. ]);
  9304. },
  9305. _doProcessBlock: function (M, offset) {
  9306. // Shortcut
  9307. var H = this._hash.words;
  9308. // Working variables
  9309. var a = H[0];
  9310. var b = H[1];
  9311. var c = H[2];
  9312. var d = H[3];
  9313. var e = H[4];
  9314. // Computation
  9315. for (var i = 0; i < 80; i++) {
  9316. if (i < 16) {
  9317. W[i] = M[offset + i] | 0;
  9318. } else {
  9319. var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
  9320. W[i] = (n << 1) | (n >>> 31);
  9321. }
  9322. var t = ((a << 5) | (a >>> 27)) + e + W[i];
  9323. if (i < 20) {
  9324. t += ((b & c) | (~b & d)) + 0x5a827999;
  9325. } else if (i < 40) {
  9326. t += (b ^ c ^ d) + 0x6ed9eba1;
  9327. } else if (i < 60) {
  9328. t += ((b & c) | (b & d) | (c & d)) - 0x70e44324;
  9329. } else /* if (i < 80) */ {
  9330. t += (b ^ c ^ d) - 0x359d3e2a;
  9331. }
  9332. e = d;
  9333. d = c;
  9334. c = (b << 30) | (b >>> 2);
  9335. b = a;
  9336. a = t;
  9337. }
  9338. // Intermediate hash value
  9339. H[0] = (H[0] + a) | 0;
  9340. H[1] = (H[1] + b) | 0;
  9341. H[2] = (H[2] + c) | 0;
  9342. H[3] = (H[3] + d) | 0;
  9343. H[4] = (H[4] + e) | 0;
  9344. },
  9345. _doFinalize: function () {
  9346. // Shortcuts
  9347. var data = this._data;
  9348. var dataWords = data.words;
  9349. var nBitsTotal = this._nDataBytes * 8;
  9350. var nBitsLeft = data.sigBytes * 8;
  9351. // Add padding
  9352. dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
  9353. dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
  9354. dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
  9355. data.sigBytes = dataWords.length * 4;
  9356. // Hash final blocks
  9357. this._process();
  9358. // Return final computed hash
  9359. return this._hash;
  9360. },
  9361. clone: function () {
  9362. var clone = Hasher.clone.call(this);
  9363. clone._hash = this._hash.clone();
  9364. return clone;
  9365. }
  9366. });
  9367. /**
  9368. * Shortcut function to the hasher's object interface.
  9369. *
  9370. * @param {WordArray|string} message The message to hash.
  9371. *
  9372. * @return {WordArray} The hash.
  9373. *
  9374. * @static
  9375. *
  9376. * @example
  9377. *
  9378. * var hash = CryptoJS.SHA1('message');
  9379. * var hash = CryptoJS.SHA1(wordArray);
  9380. */
  9381. C.SHA1 = Hasher._createHelper(SHA1);
  9382. /**
  9383. * Shortcut function to the HMAC's object interface.
  9384. *
  9385. * @param {WordArray|string} message The message to hash.
  9386. * @param {WordArray|string} key The secret key.
  9387. *
  9388. * @return {WordArray} The HMAC.
  9389. *
  9390. * @static
  9391. *
  9392. * @example
  9393. *
  9394. * var hmac = CryptoJS.HmacSHA1(message, key);
  9395. */
  9396. C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
  9397. }());
  9398. return CryptoJS.SHA1;
  9399. }));
  9400. },{"./core":52}],77:[function(require,module,exports){
  9401. ;(function (root, factory, undef) {
  9402. if (typeof exports === "object") {
  9403. // CommonJS
  9404. module.exports = exports = factory(require("./core"), require("./sha256"));
  9405. }
  9406. else if (typeof define === "function" && define.amd) {
  9407. // AMD
  9408. define(["./core", "./sha256"], factory);
  9409. }
  9410. else {
  9411. // Global (browser)
  9412. factory(root.CryptoJS);
  9413. }
  9414. }(this, function (CryptoJS) {
  9415. (function () {
  9416. // Shortcuts
  9417. var C = CryptoJS;
  9418. var C_lib = C.lib;
  9419. var WordArray = C_lib.WordArray;
  9420. var C_algo = C.algo;
  9421. var SHA256 = C_algo.SHA256;
  9422. /**
  9423. * SHA-224 hash algorithm.
  9424. */
  9425. var SHA224 = C_algo.SHA224 = SHA256.extend({
  9426. _doReset: function () {
  9427. this._hash = new WordArray.init([
  9428. 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
  9429. 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4
  9430. ]);
  9431. },
  9432. _doFinalize: function () {
  9433. var hash = SHA256._doFinalize.call(this);
  9434. hash.sigBytes -= 4;
  9435. return hash;
  9436. }
  9437. });
  9438. /**
  9439. * Shortcut function to the hasher's object interface.
  9440. *
  9441. * @param {WordArray|string} message The message to hash.
  9442. *
  9443. * @return {WordArray} The hash.
  9444. *
  9445. * @static
  9446. *
  9447. * @example
  9448. *
  9449. * var hash = CryptoJS.SHA224('message');
  9450. * var hash = CryptoJS.SHA224(wordArray);
  9451. */
  9452. C.SHA224 = SHA256._createHelper(SHA224);
  9453. /**
  9454. * Shortcut function to the HMAC's object interface.
  9455. *
  9456. * @param {WordArray|string} message The message to hash.
  9457. * @param {WordArray|string} key The secret key.
  9458. *
  9459. * @return {WordArray} The HMAC.
  9460. *
  9461. * @static
  9462. *
  9463. * @example
  9464. *
  9465. * var hmac = CryptoJS.HmacSHA224(message, key);
  9466. */
  9467. C.HmacSHA224 = SHA256._createHmacHelper(SHA224);
  9468. }());
  9469. return CryptoJS.SHA224;
  9470. }));
  9471. },{"./core":52,"./sha256":78}],78:[function(require,module,exports){
  9472. ;(function (root, factory) {
  9473. if (typeof exports === "object") {
  9474. // CommonJS
  9475. module.exports = exports = factory(require("./core"));
  9476. }
  9477. else if (typeof define === "function" && define.amd) {
  9478. // AMD
  9479. define(["./core"], factory);
  9480. }
  9481. else {
  9482. // Global (browser)
  9483. factory(root.CryptoJS);
  9484. }
  9485. }(this, function (CryptoJS) {
  9486. (function (Math) {
  9487. // Shortcuts
  9488. var C = CryptoJS;
  9489. var C_lib = C.lib;
  9490. var WordArray = C_lib.WordArray;
  9491. var Hasher = C_lib.Hasher;
  9492. var C_algo = C.algo;
  9493. // Initialization and round constants tables
  9494. var H = [];
  9495. var K = [];
  9496. // Compute constants
  9497. (function () {
  9498. function isPrime(n) {
  9499. var sqrtN = Math.sqrt(n);
  9500. for (var factor = 2; factor <= sqrtN; factor++) {
  9501. if (!(n % factor)) {
  9502. return false;
  9503. }
  9504. }
  9505. return true;
  9506. }
  9507. function getFractionalBits(n) {
  9508. return ((n - (n | 0)) * 0x100000000) | 0;
  9509. }
  9510. var n = 2;
  9511. var nPrime = 0;
  9512. while (nPrime < 64) {
  9513. if (isPrime(n)) {
  9514. if (nPrime < 8) {
  9515. H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
  9516. }
  9517. K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
  9518. nPrime++;
  9519. }
  9520. n++;
  9521. }
  9522. }());
  9523. // Reusable object
  9524. var W = [];
  9525. /**
  9526. * SHA-256 hash algorithm.
  9527. */
  9528. var SHA256 = C_algo.SHA256 = Hasher.extend({
  9529. _doReset: function () {
  9530. this._hash = new WordArray.init(H.slice(0));
  9531. },
  9532. _doProcessBlock: function (M, offset) {
  9533. // Shortcut
  9534. var H = this._hash.words;
  9535. // Working variables
  9536. var a = H[0];
  9537. var b = H[1];
  9538. var c = H[2];
  9539. var d = H[3];
  9540. var e = H[4];
  9541. var f = H[5];
  9542. var g = H[6];
  9543. var h = H[7];
  9544. // Computation
  9545. for (var i = 0; i < 64; i++) {
  9546. if (i < 16) {
  9547. W[i] = M[offset + i] | 0;
  9548. } else {
  9549. var gamma0x = W[i - 15];
  9550. var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
  9551. ((gamma0x << 14) | (gamma0x >>> 18)) ^
  9552. (gamma0x >>> 3);
  9553. var gamma1x = W[i - 2];
  9554. var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
  9555. ((gamma1x << 13) | (gamma1x >>> 19)) ^
  9556. (gamma1x >>> 10);
  9557. W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
  9558. }
  9559. var ch = (e & f) ^ (~e & g);
  9560. var maj = (a & b) ^ (a & c) ^ (b & c);
  9561. var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
  9562. var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
  9563. var t1 = h + sigma1 + ch + K[i] + W[i];
  9564. var t2 = sigma0 + maj;
  9565. h = g;
  9566. g = f;
  9567. f = e;
  9568. e = (d + t1) | 0;
  9569. d = c;
  9570. c = b;
  9571. b = a;
  9572. a = (t1 + t2) | 0;
  9573. }
  9574. // Intermediate hash value
  9575. H[0] = (H[0] + a) | 0;
  9576. H[1] = (H[1] + b) | 0;
  9577. H[2] = (H[2] + c) | 0;
  9578. H[3] = (H[3] + d) | 0;
  9579. H[4] = (H[4] + e) | 0;
  9580. H[5] = (H[5] + f) | 0;
  9581. H[6] = (H[6] + g) | 0;
  9582. H[7] = (H[7] + h) | 0;
  9583. },
  9584. _doFinalize: function () {
  9585. // Shortcuts
  9586. var data = this._data;
  9587. var dataWords = data.words;
  9588. var nBitsTotal = this._nDataBytes * 8;
  9589. var nBitsLeft = data.sigBytes * 8;
  9590. // Add padding
  9591. dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
  9592. dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
  9593. dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
  9594. data.sigBytes = dataWords.length * 4;
  9595. // Hash final blocks
  9596. this._process();
  9597. // Return final computed hash
  9598. return this._hash;
  9599. },
  9600. clone: function () {
  9601. var clone = Hasher.clone.call(this);
  9602. clone._hash = this._hash.clone();
  9603. return clone;
  9604. }
  9605. });
  9606. /**
  9607. * Shortcut function to the hasher's object interface.
  9608. *
  9609. * @param {WordArray|string} message The message to hash.
  9610. *
  9611. * @return {WordArray} The hash.
  9612. *
  9613. * @static
  9614. *
  9615. * @example
  9616. *
  9617. * var hash = CryptoJS.SHA256('message');
  9618. * var hash = CryptoJS.SHA256(wordArray);
  9619. */
  9620. C.SHA256 = Hasher._createHelper(SHA256);
  9621. /**
  9622. * Shortcut function to the HMAC's object interface.
  9623. *
  9624. * @param {WordArray|string} message The message to hash.
  9625. * @param {WordArray|string} key The secret key.
  9626. *
  9627. * @return {WordArray} The HMAC.
  9628. *
  9629. * @static
  9630. *
  9631. * @example
  9632. *
  9633. * var hmac = CryptoJS.HmacSHA256(message, key);
  9634. */
  9635. C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
  9636. }(Math));
  9637. return CryptoJS.SHA256;
  9638. }));
  9639. },{"./core":52}],79:[function(require,module,exports){
  9640. ;(function (root, factory, undef) {
  9641. if (typeof exports === "object") {
  9642. // CommonJS
  9643. module.exports = exports = factory(require("./core"), require("./x64-core"));
  9644. }
  9645. else if (typeof define === "function" && define.amd) {
  9646. // AMD
  9647. define(["./core", "./x64-core"], factory);
  9648. }
  9649. else {
  9650. // Global (browser)
  9651. factory(root.CryptoJS);
  9652. }
  9653. }(this, function (CryptoJS) {
  9654. (function (Math) {
  9655. // Shortcuts
  9656. var C = CryptoJS;
  9657. var C_lib = C.lib;
  9658. var WordArray = C_lib.WordArray;
  9659. var Hasher = C_lib.Hasher;
  9660. var C_x64 = C.x64;
  9661. var X64Word = C_x64.Word;
  9662. var C_algo = C.algo;
  9663. // Constants tables
  9664. var RHO_OFFSETS = [];
  9665. var PI_INDEXES = [];
  9666. var ROUND_CONSTANTS = [];
  9667. // Compute Constants
  9668. (function () {
  9669. // Compute rho offset constants
  9670. var x = 1, y = 0;
  9671. for (var t = 0; t < 24; t++) {
  9672. RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64;
  9673. var newX = y % 5;
  9674. var newY = (2 * x + 3 * y) % 5;
  9675. x = newX;
  9676. y = newY;
  9677. }
  9678. // Compute pi index constants
  9679. for (var x = 0; x < 5; x++) {
  9680. for (var y = 0; y < 5; y++) {
  9681. PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5;
  9682. }
  9683. }
  9684. // Compute round constants
  9685. var LFSR = 0x01;
  9686. for (var i = 0; i < 24; i++) {
  9687. var roundConstantMsw = 0;
  9688. var roundConstantLsw = 0;
  9689. for (var j = 0; j < 7; j++) {
  9690. if (LFSR & 0x01) {
  9691. var bitPosition = (1 << j) - 1;
  9692. if (bitPosition < 32) {
  9693. roundConstantLsw ^= 1 << bitPosition;
  9694. } else /* if (bitPosition >= 32) */ {
  9695. roundConstantMsw ^= 1 << (bitPosition - 32);
  9696. }
  9697. }
  9698. // Compute next LFSR
  9699. if (LFSR & 0x80) {
  9700. // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1
  9701. LFSR = (LFSR << 1) ^ 0x71;
  9702. } else {
  9703. LFSR <<= 1;
  9704. }
  9705. }
  9706. ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw);
  9707. }
  9708. }());
  9709. // Reusable objects for temporary values
  9710. var T = [];
  9711. (function () {
  9712. for (var i = 0; i < 25; i++) {
  9713. T[i] = X64Word.create();
  9714. }
  9715. }());
  9716. /**
  9717. * SHA-3 hash algorithm.
  9718. */
  9719. var SHA3 = C_algo.SHA3 = Hasher.extend({
  9720. /**
  9721. * Configuration options.
  9722. *
  9723. * @property {number} outputLength
  9724. * The desired number of bits in the output hash.
  9725. * Only values permitted are: 224, 256, 384, 512.
  9726. * Default: 512
  9727. */
  9728. cfg: Hasher.cfg.extend({
  9729. outputLength: 512
  9730. }),
  9731. _doReset: function () {
  9732. var state = this._state = []
  9733. for (var i = 0; i < 25; i++) {
  9734. state[i] = new X64Word.init();
  9735. }
  9736. this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
  9737. },
  9738. _doProcessBlock: function (M, offset) {
  9739. // Shortcuts
  9740. var state = this._state;
  9741. var nBlockSizeLanes = this.blockSize / 2;
  9742. // Absorb
  9743. for (var i = 0; i < nBlockSizeLanes; i++) {
  9744. // Shortcuts
  9745. var M2i = M[offset + 2 * i];
  9746. var M2i1 = M[offset + 2 * i + 1];
  9747. // Swap endian
  9748. M2i = (
  9749. (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) |
  9750. (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00)
  9751. );
  9752. M2i1 = (
  9753. (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) |
  9754. (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00)
  9755. );
  9756. // Absorb message into state
  9757. var lane = state[i];
  9758. lane.high ^= M2i1;
  9759. lane.low ^= M2i;
  9760. }
  9761. // Rounds
  9762. for (var round = 0; round < 24; round++) {
  9763. // Theta
  9764. for (var x = 0; x < 5; x++) {
  9765. // Mix column lanes
  9766. var tMsw = 0, tLsw = 0;
  9767. for (var y = 0; y < 5; y++) {
  9768. var lane = state[x + 5 * y];
  9769. tMsw ^= lane.high;
  9770. tLsw ^= lane.low;
  9771. }
  9772. // Temporary values
  9773. var Tx = T[x];
  9774. Tx.high = tMsw;
  9775. Tx.low = tLsw;
  9776. }
  9777. for (var x = 0; x < 5; x++) {
  9778. // Shortcuts
  9779. var Tx4 = T[(x + 4) % 5];
  9780. var Tx1 = T[(x + 1) % 5];
  9781. var Tx1Msw = Tx1.high;
  9782. var Tx1Lsw = Tx1.low;
  9783. // Mix surrounding columns
  9784. var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31));
  9785. var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31));
  9786. for (var y = 0; y < 5; y++) {
  9787. var lane = state[x + 5 * y];
  9788. lane.high ^= tMsw;
  9789. lane.low ^= tLsw;
  9790. }
  9791. }
  9792. // Rho Pi
  9793. for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
  9794. // Shortcuts
  9795. var lane = state[laneIndex];
  9796. var laneMsw = lane.high;
  9797. var laneLsw = lane.low;
  9798. var rhoOffset = RHO_OFFSETS[laneIndex];
  9799. // Rotate lanes
  9800. if (rhoOffset < 32) {
  9801. var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset));
  9802. var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset));
  9803. } else /* if (rhoOffset >= 32) */ {
  9804. var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset));
  9805. var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset));
  9806. }
  9807. // Transpose lanes
  9808. var TPiLane = T[PI_INDEXES[laneIndex]];
  9809. TPiLane.high = tMsw;
  9810. TPiLane.low = tLsw;
  9811. }
  9812. // Rho pi at x = y = 0
  9813. var T0 = T[0];
  9814. var state0 = state[0];
  9815. T0.high = state0.high;
  9816. T0.low = state0.low;
  9817. // Chi
  9818. for (var x = 0; x < 5; x++) {
  9819. for (var y = 0; y < 5; y++) {
  9820. // Shortcuts
  9821. var laneIndex = x + 5 * y;
  9822. var lane = state[laneIndex];
  9823. var TLane = T[laneIndex];
  9824. var Tx1Lane = T[((x + 1) % 5) + 5 * y];
  9825. var Tx2Lane = T[((x + 2) % 5) + 5 * y];
  9826. // Mix rows
  9827. lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high);
  9828. lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low);
  9829. }
  9830. }
  9831. // Iota
  9832. var lane = state[0];
  9833. var roundConstant = ROUND_CONSTANTS[round];
  9834. lane.high ^= roundConstant.high;
  9835. lane.low ^= roundConstant.low;;
  9836. }
  9837. },
  9838. _doFinalize: function () {
  9839. // Shortcuts
  9840. var data = this._data;
  9841. var dataWords = data.words;
  9842. var nBitsTotal = this._nDataBytes * 8;
  9843. var nBitsLeft = data.sigBytes * 8;
  9844. var blockSizeBits = this.blockSize * 32;
  9845. // Add padding
  9846. dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32);
  9847. dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80;
  9848. data.sigBytes = dataWords.length * 4;
  9849. // Hash final blocks
  9850. this._process();
  9851. // Shortcuts
  9852. var state = this._state;
  9853. var outputLengthBytes = this.cfg.outputLength / 8;
  9854. var outputLengthLanes = outputLengthBytes / 8;
  9855. // Squeeze
  9856. var hashWords = [];
  9857. for (var i = 0; i < outputLengthLanes; i++) {
  9858. // Shortcuts
  9859. var lane = state[i];
  9860. var laneMsw = lane.high;
  9861. var laneLsw = lane.low;
  9862. // Swap endian
  9863. laneMsw = (
  9864. (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) |
  9865. (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00)
  9866. );
  9867. laneLsw = (
  9868. (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) |
  9869. (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00)
  9870. );
  9871. // Squeeze state to retrieve hash
  9872. hashWords.push(laneLsw);
  9873. hashWords.push(laneMsw);
  9874. }
  9875. // Return final computed hash
  9876. return new WordArray.init(hashWords, outputLengthBytes);
  9877. },
  9878. clone: function () {
  9879. var clone = Hasher.clone.call(this);
  9880. var state = clone._state = this._state.slice(0);
  9881. for (var i = 0; i < 25; i++) {
  9882. state[i] = state[i].clone();
  9883. }
  9884. return clone;
  9885. }
  9886. });
  9887. /**
  9888. * Shortcut function to the hasher's object interface.
  9889. *
  9890. * @param {WordArray|string} message The message to hash.
  9891. *
  9892. * @return {WordArray} The hash.
  9893. *
  9894. * @static
  9895. *
  9896. * @example
  9897. *
  9898. * var hash = CryptoJS.SHA3('message');
  9899. * var hash = CryptoJS.SHA3(wordArray);
  9900. */
  9901. C.SHA3 = Hasher._createHelper(SHA3);
  9902. /**
  9903. * Shortcut function to the HMAC's object interface.
  9904. *
  9905. * @param {WordArray|string} message The message to hash.
  9906. * @param {WordArray|string} key The secret key.
  9907. *
  9908. * @return {WordArray} The HMAC.
  9909. *
  9910. * @static
  9911. *
  9912. * @example
  9913. *
  9914. * var hmac = CryptoJS.HmacSHA3(message, key);
  9915. */
  9916. C.HmacSHA3 = Hasher._createHmacHelper(SHA3);
  9917. }(Math));
  9918. return CryptoJS.SHA3;
  9919. }));
  9920. },{"./core":52,"./x64-core":83}],80:[function(require,module,exports){
  9921. ;(function (root, factory, undef) {
  9922. if (typeof exports === "object") {
  9923. // CommonJS
  9924. module.exports = exports = factory(require("./core"), require("./x64-core"), require("./sha512"));
  9925. }
  9926. else if (typeof define === "function" && define.amd) {
  9927. // AMD
  9928. define(["./core", "./x64-core", "./sha512"], factory);
  9929. }
  9930. else {
  9931. // Global (browser)
  9932. factory(root.CryptoJS);
  9933. }
  9934. }(this, function (CryptoJS) {
  9935. (function () {
  9936. // Shortcuts
  9937. var C = CryptoJS;
  9938. var C_x64 = C.x64;
  9939. var X64Word = C_x64.Word;
  9940. var X64WordArray = C_x64.WordArray;
  9941. var C_algo = C.algo;
  9942. var SHA512 = C_algo.SHA512;
  9943. /**
  9944. * SHA-384 hash algorithm.
  9945. */
  9946. var SHA384 = C_algo.SHA384 = SHA512.extend({
  9947. _doReset: function () {
  9948. this._hash = new X64WordArray.init([
  9949. new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507),
  9950. new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939),
  9951. new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511),
  9952. new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4)
  9953. ]);
  9954. },
  9955. _doFinalize: function () {
  9956. var hash = SHA512._doFinalize.call(this);
  9957. hash.sigBytes -= 16;
  9958. return hash;
  9959. }
  9960. });
  9961. /**
  9962. * Shortcut function to the hasher's object interface.
  9963. *
  9964. * @param {WordArray|string} message The message to hash.
  9965. *
  9966. * @return {WordArray} The hash.
  9967. *
  9968. * @static
  9969. *
  9970. * @example
  9971. *
  9972. * var hash = CryptoJS.SHA384('message');
  9973. * var hash = CryptoJS.SHA384(wordArray);
  9974. */
  9975. C.SHA384 = SHA512._createHelper(SHA384);
  9976. /**
  9977. * Shortcut function to the HMAC's object interface.
  9978. *
  9979. * @param {WordArray|string} message The message to hash.
  9980. * @param {WordArray|string} key The secret key.
  9981. *
  9982. * @return {WordArray} The HMAC.
  9983. *
  9984. * @static
  9985. *
  9986. * @example
  9987. *
  9988. * var hmac = CryptoJS.HmacSHA384(message, key);
  9989. */
  9990. C.HmacSHA384 = SHA512._createHmacHelper(SHA384);
  9991. }());
  9992. return CryptoJS.SHA384;
  9993. }));
  9994. },{"./core":52,"./sha512":81,"./x64-core":83}],81:[function(require,module,exports){
  9995. ;(function (root, factory, undef) {
  9996. if (typeof exports === "object") {
  9997. // CommonJS
  9998. module.exports = exports = factory(require("./core"), require("./x64-core"));
  9999. }
  10000. else if (typeof define === "function" && define.amd) {
  10001. // AMD
  10002. define(["./core", "./x64-core"], factory);
  10003. }
  10004. else {
  10005. // Global (browser)
  10006. factory(root.CryptoJS);
  10007. }
  10008. }(this, function (CryptoJS) {
  10009. (function () {
  10010. // Shortcuts
  10011. var C = CryptoJS;
  10012. var C_lib = C.lib;
  10013. var Hasher = C_lib.Hasher;
  10014. var C_x64 = C.x64;
  10015. var X64Word = C_x64.Word;
  10016. var X64WordArray = C_x64.WordArray;
  10017. var C_algo = C.algo;
  10018. function X64Word_create() {
  10019. return X64Word.create.apply(X64Word, arguments);
  10020. }
  10021. // Constants
  10022. var K = [
  10023. X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd),
  10024. X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc),
  10025. X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019),
  10026. X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118),
  10027. X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe),
  10028. X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2),
  10029. X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1),
  10030. X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694),
  10031. X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3),
  10032. X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65),
  10033. X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483),
  10034. X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5),
  10035. X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210),
  10036. X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4),
  10037. X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725),
  10038. X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70),
  10039. X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926),
  10040. X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df),
  10041. X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8),
  10042. X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b),
  10043. X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001),
  10044. X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30),
  10045. X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910),
  10046. X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8),
  10047. X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53),
  10048. X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8),
  10049. X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb),
  10050. X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3),
  10051. X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60),
  10052. X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec),
  10053. X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9),
  10054. X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b),
  10055. X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207),
  10056. X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178),
  10057. X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6),
  10058. X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b),
  10059. X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493),
  10060. X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c),
  10061. X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a),
  10062. X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817)
  10063. ];
  10064. // Reusable objects
  10065. var W = [];
  10066. (function () {
  10067. for (var i = 0; i < 80; i++) {
  10068. W[i] = X64Word_create();
  10069. }
  10070. }());
  10071. /**
  10072. * SHA-512 hash algorithm.
  10073. */
  10074. var SHA512 = C_algo.SHA512 = Hasher.extend({
  10075. _doReset: function () {
  10076. this._hash = new X64WordArray.init([
  10077. new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b),
  10078. new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1),
  10079. new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f),
  10080. new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179)
  10081. ]);
  10082. },
  10083. _doProcessBlock: function (M, offset) {
  10084. // Shortcuts
  10085. var H = this._hash.words;
  10086. var H0 = H[0];
  10087. var H1 = H[1];
  10088. var H2 = H[2];
  10089. var H3 = H[3];
  10090. var H4 = H[4];
  10091. var H5 = H[5];
  10092. var H6 = H[6];
  10093. var H7 = H[7];
  10094. var H0h = H0.high;
  10095. var H0l = H0.low;
  10096. var H1h = H1.high;
  10097. var H1l = H1.low;
  10098. var H2h = H2.high;
  10099. var H2l = H2.low;
  10100. var H3h = H3.high;
  10101. var H3l = H3.low;
  10102. var H4h = H4.high;
  10103. var H4l = H4.low;
  10104. var H5h = H5.high;
  10105. var H5l = H5.low;
  10106. var H6h = H6.high;
  10107. var H6l = H6.low;
  10108. var H7h = H7.high;
  10109. var H7l = H7.low;
  10110. // Working variables
  10111. var ah = H0h;
  10112. var al = H0l;
  10113. var bh = H1h;
  10114. var bl = H1l;
  10115. var ch = H2h;
  10116. var cl = H2l;
  10117. var dh = H3h;
  10118. var dl = H3l;
  10119. var eh = H4h;
  10120. var el = H4l;
  10121. var fh = H5h;
  10122. var fl = H5l;
  10123. var gh = H6h;
  10124. var gl = H6l;
  10125. var hh = H7h;
  10126. var hl = H7l;
  10127. // Rounds
  10128. for (var i = 0; i < 80; i++) {
  10129. // Shortcut
  10130. var Wi = W[i];
  10131. // Extend message
  10132. if (i < 16) {
  10133. var Wih = Wi.high = M[offset + i * 2] | 0;
  10134. var Wil = Wi.low = M[offset + i * 2 + 1] | 0;
  10135. } else {
  10136. // Gamma0
  10137. var gamma0x = W[i - 15];
  10138. var gamma0xh = gamma0x.high;
  10139. var gamma0xl = gamma0x.low;
  10140. var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7);
  10141. var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25));
  10142. // Gamma1
  10143. var gamma1x = W[i - 2];
  10144. var gamma1xh = gamma1x.high;
  10145. var gamma1xl = gamma1x.low;
  10146. var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6);
  10147. var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26));
  10148. // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
  10149. var Wi7 = W[i - 7];
  10150. var Wi7h = Wi7.high;
  10151. var Wi7l = Wi7.low;
  10152. var Wi16 = W[i - 16];
  10153. var Wi16h = Wi16.high;
  10154. var Wi16l = Wi16.low;
  10155. var Wil = gamma0l + Wi7l;
  10156. var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0);
  10157. var Wil = Wil + gamma1l;
  10158. var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0);
  10159. var Wil = Wil + Wi16l;
  10160. var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0);
  10161. Wi.high = Wih;
  10162. Wi.low = Wil;
  10163. }
  10164. var chh = (eh & fh) ^ (~eh & gh);
  10165. var chl = (el & fl) ^ (~el & gl);
  10166. var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch);
  10167. var majl = (al & bl) ^ (al & cl) ^ (bl & cl);
  10168. var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7));
  10169. var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7));
  10170. var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9));
  10171. var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9));
  10172. // t1 = h + sigma1 + ch + K[i] + W[i]
  10173. var Ki = K[i];
  10174. var Kih = Ki.high;
  10175. var Kil = Ki.low;
  10176. var t1l = hl + sigma1l;
  10177. var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0);
  10178. var t1l = t1l + chl;
  10179. var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0);
  10180. var t1l = t1l + Kil;
  10181. var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0);
  10182. var t1l = t1l + Wil;
  10183. var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0);
  10184. // t2 = sigma0 + maj
  10185. var t2l = sigma0l + majl;
  10186. var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0);
  10187. // Update working variables
  10188. hh = gh;
  10189. hl = gl;
  10190. gh = fh;
  10191. gl = fl;
  10192. fh = eh;
  10193. fl = el;
  10194. el = (dl + t1l) | 0;
  10195. eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0;
  10196. dh = ch;
  10197. dl = cl;
  10198. ch = bh;
  10199. cl = bl;
  10200. bh = ah;
  10201. bl = al;
  10202. al = (t1l + t2l) | 0;
  10203. ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0;
  10204. }
  10205. // Intermediate hash value
  10206. H0l = H0.low = (H0l + al);
  10207. H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0));
  10208. H1l = H1.low = (H1l + bl);
  10209. H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0));
  10210. H2l = H2.low = (H2l + cl);
  10211. H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0));
  10212. H3l = H3.low = (H3l + dl);
  10213. H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0));
  10214. H4l = H4.low = (H4l + el);
  10215. H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0));
  10216. H5l = H5.low = (H5l + fl);
  10217. H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0));
  10218. H6l = H6.low = (H6l + gl);
  10219. H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0));
  10220. H7l = H7.low = (H7l + hl);
  10221. H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0));
  10222. },
  10223. _doFinalize: function () {
  10224. // Shortcuts
  10225. var data = this._data;
  10226. var dataWords = data.words;
  10227. var nBitsTotal = this._nDataBytes * 8;
  10228. var nBitsLeft = data.sigBytes * 8;
  10229. // Add padding
  10230. dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
  10231. dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000);
  10232. dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal;
  10233. data.sigBytes = dataWords.length * 4;
  10234. // Hash final blocks
  10235. this._process();
  10236. // Convert hash to 32-bit word array before returning
  10237. var hash = this._hash.toX32();
  10238. // Return final computed hash
  10239. return hash;
  10240. },
  10241. clone: function () {
  10242. var clone = Hasher.clone.call(this);
  10243. clone._hash = this._hash.clone();
  10244. return clone;
  10245. },
  10246. blockSize: 1024/32
  10247. });
  10248. /**
  10249. * Shortcut function to the hasher's object interface.
  10250. *
  10251. * @param {WordArray|string} message The message to hash.
  10252. *
  10253. * @return {WordArray} The hash.
  10254. *
  10255. * @static
  10256. *
  10257. * @example
  10258. *
  10259. * var hash = CryptoJS.SHA512('message');
  10260. * var hash = CryptoJS.SHA512(wordArray);
  10261. */
  10262. C.SHA512 = Hasher._createHelper(SHA512);
  10263. /**
  10264. * Shortcut function to the HMAC's object interface.
  10265. *
  10266. * @param {WordArray|string} message The message to hash.
  10267. * @param {WordArray|string} key The secret key.
  10268. *
  10269. * @return {WordArray} The HMAC.
  10270. *
  10271. * @static
  10272. *
  10273. * @example
  10274. *
  10275. * var hmac = CryptoJS.HmacSHA512(message, key);
  10276. */
  10277. C.HmacSHA512 = Hasher._createHmacHelper(SHA512);
  10278. }());
  10279. return CryptoJS.SHA512;
  10280. }));
  10281. },{"./core":52,"./x64-core":83}],82:[function(require,module,exports){
  10282. ;(function (root, factory, undef) {
  10283. if (typeof exports === "object") {
  10284. // CommonJS
  10285. module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core"));
  10286. }
  10287. else if (typeof define === "function" && define.amd) {
  10288. // AMD
  10289. define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
  10290. }
  10291. else {
  10292. // Global (browser)
  10293. factory(root.CryptoJS);
  10294. }
  10295. }(this, function (CryptoJS) {
  10296. (function () {
  10297. // Shortcuts
  10298. var C = CryptoJS;
  10299. var C_lib = C.lib;
  10300. var WordArray = C_lib.WordArray;
  10301. var BlockCipher = C_lib.BlockCipher;
  10302. var C_algo = C.algo;
  10303. // Permuted Choice 1 constants
  10304. var PC1 = [
  10305. 57, 49, 41, 33, 25, 17, 9, 1,
  10306. 58, 50, 42, 34, 26, 18, 10, 2,
  10307. 59, 51, 43, 35, 27, 19, 11, 3,
  10308. 60, 52, 44, 36, 63, 55, 47, 39,
  10309. 31, 23, 15, 7, 62, 54, 46, 38,
  10310. 30, 22, 14, 6, 61, 53, 45, 37,
  10311. 29, 21, 13, 5, 28, 20, 12, 4
  10312. ];
  10313. // Permuted Choice 2 constants
  10314. var PC2 = [
  10315. 14, 17, 11, 24, 1, 5,
  10316. 3, 28, 15, 6, 21, 10,
  10317. 23, 19, 12, 4, 26, 8,
  10318. 16, 7, 27, 20, 13, 2,
  10319. 41, 52, 31, 37, 47, 55,
  10320. 30, 40, 51, 45, 33, 48,
  10321. 44, 49, 39, 56, 34, 53,
  10322. 46, 42, 50, 36, 29, 32
  10323. ];
  10324. // Cumulative bit shift constants
  10325. var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28];
  10326. // SBOXes and round permutation constants
  10327. var SBOX_P = [
  10328. {
  10329. 0x0: 0x808200,
  10330. 0x10000000: 0x8000,
  10331. 0x20000000: 0x808002,
  10332. 0x30000000: 0x2,
  10333. 0x40000000: 0x200,
  10334. 0x50000000: 0x808202,
  10335. 0x60000000: 0x800202,
  10336. 0x70000000: 0x800000,
  10337. 0x80000000: 0x202,
  10338. 0x90000000: 0x800200,
  10339. 0xa0000000: 0x8200,
  10340. 0xb0000000: 0x808000,
  10341. 0xc0000000: 0x8002,
  10342. 0xd0000000: 0x800002,
  10343. 0xe0000000: 0x0,
  10344. 0xf0000000: 0x8202,
  10345. 0x8000000: 0x0,
  10346. 0x18000000: 0x808202,
  10347. 0x28000000: 0x8202,
  10348. 0x38000000: 0x8000,
  10349. 0x48000000: 0x808200,
  10350. 0x58000000: 0x200,
  10351. 0x68000000: 0x808002,
  10352. 0x78000000: 0x2,
  10353. 0x88000000: 0x800200,
  10354. 0x98000000: 0x8200,
  10355. 0xa8000000: 0x808000,
  10356. 0xb8000000: 0x800202,
  10357. 0xc8000000: 0x800002,
  10358. 0xd8000000: 0x8002,
  10359. 0xe8000000: 0x202,
  10360. 0xf8000000: 0x800000,
  10361. 0x1: 0x8000,
  10362. 0x10000001: 0x2,
  10363. 0x20000001: 0x808200,
  10364. 0x30000001: 0x800000,
  10365. 0x40000001: 0x808002,
  10366. 0x50000001: 0x8200,
  10367. 0x60000001: 0x200,
  10368. 0x70000001: 0x800202,
  10369. 0x80000001: 0x808202,
  10370. 0x90000001: 0x808000,
  10371. 0xa0000001: 0x800002,
  10372. 0xb0000001: 0x8202,
  10373. 0xc0000001: 0x202,
  10374. 0xd0000001: 0x800200,
  10375. 0xe0000001: 0x8002,
  10376. 0xf0000001: 0x0,
  10377. 0x8000001: 0x808202,
  10378. 0x18000001: 0x808000,
  10379. 0x28000001: 0x800000,
  10380. 0x38000001: 0x200,
  10381. 0x48000001: 0x8000,
  10382. 0x58000001: 0x800002,
  10383. 0x68000001: 0x2,
  10384. 0x78000001: 0x8202,
  10385. 0x88000001: 0x8002,
  10386. 0x98000001: 0x800202,
  10387. 0xa8000001: 0x202,
  10388. 0xb8000001: 0x808200,
  10389. 0xc8000001: 0x800200,
  10390. 0xd8000001: 0x0,
  10391. 0xe8000001: 0x8200,
  10392. 0xf8000001: 0x808002
  10393. },
  10394. {
  10395. 0x0: 0x40084010,
  10396. 0x1000000: 0x4000,
  10397. 0x2000000: 0x80000,
  10398. 0x3000000: 0x40080010,
  10399. 0x4000000: 0x40000010,
  10400. 0x5000000: 0x40084000,
  10401. 0x6000000: 0x40004000,
  10402. 0x7000000: 0x10,
  10403. 0x8000000: 0x84000,
  10404. 0x9000000: 0x40004010,
  10405. 0xa000000: 0x40000000,
  10406. 0xb000000: 0x84010,
  10407. 0xc000000: 0x80010,
  10408. 0xd000000: 0x0,
  10409. 0xe000000: 0x4010,
  10410. 0xf000000: 0x40080000,
  10411. 0x800000: 0x40004000,
  10412. 0x1800000: 0x84010,
  10413. 0x2800000: 0x10,
  10414. 0x3800000: 0x40004010,
  10415. 0x4800000: 0x40084010,
  10416. 0x5800000: 0x40000000,
  10417. 0x6800000: 0x80000,
  10418. 0x7800000: 0x40080010,
  10419. 0x8800000: 0x80010,
  10420. 0x9800000: 0x0,
  10421. 0xa800000: 0x4000,
  10422. 0xb800000: 0x40080000,
  10423. 0xc800000: 0x40000010,
  10424. 0xd800000: 0x84000,
  10425. 0xe800000: 0x40084000,
  10426. 0xf800000: 0x4010,
  10427. 0x10000000: 0x0,
  10428. 0x11000000: 0x40080010,
  10429. 0x12000000: 0x40004010,
  10430. 0x13000000: 0x40084000,
  10431. 0x14000000: 0x40080000,
  10432. 0x15000000: 0x10,
  10433. 0x16000000: 0x84010,
  10434. 0x17000000: 0x4000,
  10435. 0x18000000: 0x4010,
  10436. 0x19000000: 0x80000,
  10437. 0x1a000000: 0x80010,
  10438. 0x1b000000: 0x40000010,
  10439. 0x1c000000: 0x84000,
  10440. 0x1d000000: 0x40004000,
  10441. 0x1e000000: 0x40000000,
  10442. 0x1f000000: 0x40084010,
  10443. 0x10800000: 0x84010,
  10444. 0x11800000: 0x80000,
  10445. 0x12800000: 0x40080000,
  10446. 0x13800000: 0x4000,
  10447. 0x14800000: 0x40004000,
  10448. 0x15800000: 0x40084010,
  10449. 0x16800000: 0x10,
  10450. 0x17800000: 0x40000000,
  10451. 0x18800000: 0x40084000,
  10452. 0x19800000: 0x40000010,
  10453. 0x1a800000: 0x40004010,
  10454. 0x1b800000: 0x80010,
  10455. 0x1c800000: 0x0,
  10456. 0x1d800000: 0x4010,
  10457. 0x1e800000: 0x40080010,
  10458. 0x1f800000: 0x84000
  10459. },
  10460. {
  10461. 0x0: 0x104,
  10462. 0x100000: 0x0,
  10463. 0x200000: 0x4000100,
  10464. 0x300000: 0x10104,
  10465. 0x400000: 0x10004,
  10466. 0x500000: 0x4000004,
  10467. 0x600000: 0x4010104,
  10468. 0x700000: 0x4010000,
  10469. 0x800000: 0x4000000,
  10470. 0x900000: 0x4010100,
  10471. 0xa00000: 0x10100,
  10472. 0xb00000: 0x4010004,
  10473. 0xc00000: 0x4000104,
  10474. 0xd00000: 0x10000,
  10475. 0xe00000: 0x4,
  10476. 0xf00000: 0x100,
  10477. 0x80000: 0x4010100,
  10478. 0x180000: 0x4010004,
  10479. 0x280000: 0x0,
  10480. 0x380000: 0x4000100,
  10481. 0x480000: 0x4000004,
  10482. 0x580000: 0x10000,
  10483. 0x680000: 0x10004,
  10484. 0x780000: 0x104,
  10485. 0x880000: 0x4,
  10486. 0x980000: 0x100,
  10487. 0xa80000: 0x4010000,
  10488. 0xb80000: 0x10104,
  10489. 0xc80000: 0x10100,
  10490. 0xd80000: 0x4000104,
  10491. 0xe80000: 0x4010104,
  10492. 0xf80000: 0x4000000,
  10493. 0x1000000: 0x4010100,
  10494. 0x1100000: 0x10004,
  10495. 0x1200000: 0x10000,
  10496. 0x1300000: 0x4000100,
  10497. 0x1400000: 0x100,
  10498. 0x1500000: 0x4010104,
  10499. 0x1600000: 0x4000004,
  10500. 0x1700000: 0x0,
  10501. 0x1800000: 0x4000104,
  10502. 0x1900000: 0x4000000,
  10503. 0x1a00000: 0x4,
  10504. 0x1b00000: 0x10100,
  10505. 0x1c00000: 0x4010000,
  10506. 0x1d00000: 0x104,
  10507. 0x1e00000: 0x10104,
  10508. 0x1f00000: 0x4010004,
  10509. 0x1080000: 0x4000000,
  10510. 0x1180000: 0x104,
  10511. 0x1280000: 0x4010100,
  10512. 0x1380000: 0x0,
  10513. 0x1480000: 0x10004,
  10514. 0x1580000: 0x4000100,
  10515. 0x1680000: 0x100,
  10516. 0x1780000: 0x4010004,
  10517. 0x1880000: 0x10000,
  10518. 0x1980000: 0x4010104,
  10519. 0x1a80000: 0x10104,
  10520. 0x1b80000: 0x4000004,
  10521. 0x1c80000: 0x4000104,
  10522. 0x1d80000: 0x4010000,
  10523. 0x1e80000: 0x4,
  10524. 0x1f80000: 0x10100
  10525. },
  10526. {
  10527. 0x0: 0x80401000,
  10528. 0x10000: 0x80001040,
  10529. 0x20000: 0x401040,
  10530. 0x30000: 0x80400000,
  10531. 0x40000: 0x0,
  10532. 0x50000: 0x401000,
  10533. 0x60000: 0x80000040,
  10534. 0x70000: 0x400040,
  10535. 0x80000: 0x80000000,
  10536. 0x90000: 0x400000,
  10537. 0xa0000: 0x40,
  10538. 0xb0000: 0x80001000,
  10539. 0xc0000: 0x80400040,
  10540. 0xd0000: 0x1040,
  10541. 0xe0000: 0x1000,
  10542. 0xf0000: 0x80401040,
  10543. 0x8000: 0x80001040,
  10544. 0x18000: 0x40,
  10545. 0x28000: 0x80400040,
  10546. 0x38000: 0x80001000,
  10547. 0x48000: 0x401000,
  10548. 0x58000: 0x80401040,
  10549. 0x68000: 0x0,
  10550. 0x78000: 0x80400000,
  10551. 0x88000: 0x1000,
  10552. 0x98000: 0x80401000,
  10553. 0xa8000: 0x400000,
  10554. 0xb8000: 0x1040,
  10555. 0xc8000: 0x80000000,
  10556. 0xd8000: 0x400040,
  10557. 0xe8000: 0x401040,
  10558. 0xf8000: 0x80000040,
  10559. 0x100000: 0x400040,
  10560. 0x110000: 0x401000,
  10561. 0x120000: 0x80000040,
  10562. 0x130000: 0x0,
  10563. 0x140000: 0x1040,
  10564. 0x150000: 0x80400040,
  10565. 0x160000: 0x80401000,
  10566. 0x170000: 0x80001040,
  10567. 0x180000: 0x80401040,
  10568. 0x190000: 0x80000000,
  10569. 0x1a0000: 0x80400000,
  10570. 0x1b0000: 0x401040,
  10571. 0x1c0000: 0x80001000,
  10572. 0x1d0000: 0x400000,
  10573. 0x1e0000: 0x40,
  10574. 0x1f0000: 0x1000,
  10575. 0x108000: 0x80400000,
  10576. 0x118000: 0x80401040,
  10577. 0x128000: 0x0,
  10578. 0x138000: 0x401000,
  10579. 0x148000: 0x400040,
  10580. 0x158000: 0x80000000,
  10581. 0x168000: 0x80001040,
  10582. 0x178000: 0x40,
  10583. 0x188000: 0x80000040,
  10584. 0x198000: 0x1000,
  10585. 0x1a8000: 0x80001000,
  10586. 0x1b8000: 0x80400040,
  10587. 0x1c8000: 0x1040,
  10588. 0x1d8000: 0x80401000,
  10589. 0x1e8000: 0x400000,
  10590. 0x1f8000: 0x401040
  10591. },
  10592. {
  10593. 0x0: 0x80,
  10594. 0x1000: 0x1040000,
  10595. 0x2000: 0x40000,
  10596. 0x3000: 0x20000000,
  10597. 0x4000: 0x20040080,
  10598. 0x5000: 0x1000080,
  10599. 0x6000: 0x21000080,
  10600. 0x7000: 0x40080,
  10601. 0x8000: 0x1000000,
  10602. 0x9000: 0x20040000,
  10603. 0xa000: 0x20000080,
  10604. 0xb000: 0x21040080,
  10605. 0xc000: 0x21040000,
  10606. 0xd000: 0x0,
  10607. 0xe000: 0x1040080,
  10608. 0xf000: 0x21000000,
  10609. 0x800: 0x1040080,
  10610. 0x1800: 0x21000080,
  10611. 0x2800: 0x80,
  10612. 0x3800: 0x1040000,
  10613. 0x4800: 0x40000,
  10614. 0x5800: 0x20040080,
  10615. 0x6800: 0x21040000,
  10616. 0x7800: 0x20000000,
  10617. 0x8800: 0x20040000,
  10618. 0x9800: 0x0,
  10619. 0xa800: 0x21040080,
  10620. 0xb800: 0x1000080,
  10621. 0xc800: 0x20000080,
  10622. 0xd800: 0x21000000,
  10623. 0xe800: 0x1000000,
  10624. 0xf800: 0x40080,
  10625. 0x10000: 0x40000,
  10626. 0x11000: 0x80,
  10627. 0x12000: 0x20000000,
  10628. 0x13000: 0x21000080,
  10629. 0x14000: 0x1000080,
  10630. 0x15000: 0x21040000,
  10631. 0x16000: 0x20040080,
  10632. 0x17000: 0x1000000,
  10633. 0x18000: 0x21040080,
  10634. 0x19000: 0x21000000,
  10635. 0x1a000: 0x1040000,
  10636. 0x1b000: 0x20040000,
  10637. 0x1c000: 0x40080,
  10638. 0x1d000: 0x20000080,
  10639. 0x1e000: 0x0,
  10640. 0x1f000: 0x1040080,
  10641. 0x10800: 0x21000080,
  10642. 0x11800: 0x1000000,
  10643. 0x12800: 0x1040000,
  10644. 0x13800: 0x20040080,
  10645. 0x14800: 0x20000000,
  10646. 0x15800: 0x1040080,
  10647. 0x16800: 0x80,
  10648. 0x17800: 0x21040000,
  10649. 0x18800: 0x40080,
  10650. 0x19800: 0x21040080,
  10651. 0x1a800: 0x0,
  10652. 0x1b800: 0x21000000,
  10653. 0x1c800: 0x1000080,
  10654. 0x1d800: 0x40000,
  10655. 0x1e800: 0x20040000,
  10656. 0x1f800: 0x20000080
  10657. },
  10658. {
  10659. 0x0: 0x10000008,
  10660. 0x100: 0x2000,
  10661. 0x200: 0x10200000,
  10662. 0x300: 0x10202008,
  10663. 0x400: 0x10002000,
  10664. 0x500: 0x200000,
  10665. 0x600: 0x200008,
  10666. 0x700: 0x10000000,
  10667. 0x800: 0x0,
  10668. 0x900: 0x10002008,
  10669. 0xa00: 0x202000,
  10670. 0xb00: 0x8,
  10671. 0xc00: 0x10200008,
  10672. 0xd00: 0x202008,
  10673. 0xe00: 0x2008,
  10674. 0xf00: 0x10202000,
  10675. 0x80: 0x10200000,
  10676. 0x180: 0x10202008,
  10677. 0x280: 0x8,
  10678. 0x380: 0x200000,
  10679. 0x480: 0x202008,
  10680. 0x580: 0x10000008,
  10681. 0x680: 0x10002000,
  10682. 0x780: 0x2008,
  10683. 0x880: 0x200008,
  10684. 0x980: 0x2000,
  10685. 0xa80: 0x10002008,
  10686. 0xb80: 0x10200008,
  10687. 0xc80: 0x0,
  10688. 0xd80: 0x10202000,
  10689. 0xe80: 0x202000,
  10690. 0xf80: 0x10000000,
  10691. 0x1000: 0x10002000,
  10692. 0x1100: 0x10200008,
  10693. 0x1200: 0x10202008,
  10694. 0x1300: 0x2008,
  10695. 0x1400: 0x200000,
  10696. 0x1500: 0x10000000,
  10697. 0x1600: 0x10000008,
  10698. 0x1700: 0x202000,
  10699. 0x1800: 0x202008,
  10700. 0x1900: 0x0,
  10701. 0x1a00: 0x8,
  10702. 0x1b00: 0x10200000,
  10703. 0x1c00: 0x2000,
  10704. 0x1d00: 0x10002008,
  10705. 0x1e00: 0x10202000,
  10706. 0x1f00: 0x200008,
  10707. 0x1080: 0x8,
  10708. 0x1180: 0x202000,
  10709. 0x1280: 0x200000,
  10710. 0x1380: 0x10000008,
  10711. 0x1480: 0x10002000,
  10712. 0x1580: 0x2008,
  10713. 0x1680: 0x10202008,
  10714. 0x1780: 0x10200000,
  10715. 0x1880: 0x10202000,
  10716. 0x1980: 0x10200008,
  10717. 0x1a80: 0x2000,
  10718. 0x1b80: 0x202008,
  10719. 0x1c80: 0x200008,
  10720. 0x1d80: 0x0,
  10721. 0x1e80: 0x10000000,
  10722. 0x1f80: 0x10002008
  10723. },
  10724. {
  10725. 0x0: 0x100000,
  10726. 0x10: 0x2000401,
  10727. 0x20: 0x400,
  10728. 0x30: 0x100401,
  10729. 0x40: 0x2100401,
  10730. 0x50: 0x0,
  10731. 0x60: 0x1,
  10732. 0x70: 0x2100001,
  10733. 0x80: 0x2000400,
  10734. 0x90: 0x100001,
  10735. 0xa0: 0x2000001,
  10736. 0xb0: 0x2100400,
  10737. 0xc0: 0x2100000,
  10738. 0xd0: 0x401,
  10739. 0xe0: 0x100400,
  10740. 0xf0: 0x2000000,
  10741. 0x8: 0x2100001,
  10742. 0x18: 0x0,
  10743. 0x28: 0x2000401,
  10744. 0x38: 0x2100400,
  10745. 0x48: 0x100000,
  10746. 0x58: 0x2000001,
  10747. 0x68: 0x2000000,
  10748. 0x78: 0x401,
  10749. 0x88: 0x100401,
  10750. 0x98: 0x2000400,
  10751. 0xa8: 0x2100000,
  10752. 0xb8: 0x100001,
  10753. 0xc8: 0x400,
  10754. 0xd8: 0x2100401,
  10755. 0xe8: 0x1,
  10756. 0xf8: 0x100400,
  10757. 0x100: 0x2000000,
  10758. 0x110: 0x100000,
  10759. 0x120: 0x2000401,
  10760. 0x130: 0x2100001,
  10761. 0x140: 0x100001,
  10762. 0x150: 0x2000400,
  10763. 0x160: 0x2100400,
  10764. 0x170: 0x100401,
  10765. 0x180: 0x401,
  10766. 0x190: 0x2100401,
  10767. 0x1a0: 0x100400,
  10768. 0x1b0: 0x1,
  10769. 0x1c0: 0x0,
  10770. 0x1d0: 0x2100000,
  10771. 0x1e0: 0x2000001,
  10772. 0x1f0: 0x400,
  10773. 0x108: 0x100400,
  10774. 0x118: 0x2000401,
  10775. 0x128: 0x2100001,
  10776. 0x138: 0x1,
  10777. 0x148: 0x2000000,
  10778. 0x158: 0x100000,
  10779. 0x168: 0x401,
  10780. 0x178: 0x2100400,
  10781. 0x188: 0x2000001,
  10782. 0x198: 0x2100000,
  10783. 0x1a8: 0x0,
  10784. 0x1b8: 0x2100401,
  10785. 0x1c8: 0x100401,
  10786. 0x1d8: 0x400,
  10787. 0x1e8: 0x2000400,
  10788. 0x1f8: 0x100001
  10789. },
  10790. {
  10791. 0x0: 0x8000820,
  10792. 0x1: 0x20000,
  10793. 0x2: 0x8000000,
  10794. 0x3: 0x20,
  10795. 0x4: 0x20020,
  10796. 0x5: 0x8020820,
  10797. 0x6: 0x8020800,
  10798. 0x7: 0x800,
  10799. 0x8: 0x8020000,
  10800. 0x9: 0x8000800,
  10801. 0xa: 0x20800,
  10802. 0xb: 0x8020020,
  10803. 0xc: 0x820,
  10804. 0xd: 0x0,
  10805. 0xe: 0x8000020,
  10806. 0xf: 0x20820,
  10807. 0x80000000: 0x800,
  10808. 0x80000001: 0x8020820,
  10809. 0x80000002: 0x8000820,
  10810. 0x80000003: 0x8000000,
  10811. 0x80000004: 0x8020000,
  10812. 0x80000005: 0x20800,
  10813. 0x80000006: 0x20820,
  10814. 0x80000007: 0x20,
  10815. 0x80000008: 0x8000020,
  10816. 0x80000009: 0x820,
  10817. 0x8000000a: 0x20020,
  10818. 0x8000000b: 0x8020800,
  10819. 0x8000000c: 0x0,
  10820. 0x8000000d: 0x8020020,
  10821. 0x8000000e: 0x8000800,
  10822. 0x8000000f: 0x20000,
  10823. 0x10: 0x20820,
  10824. 0x11: 0x8020800,
  10825. 0x12: 0x20,
  10826. 0x13: 0x800,
  10827. 0x14: 0x8000800,
  10828. 0x15: 0x8000020,
  10829. 0x16: 0x8020020,
  10830. 0x17: 0x20000,
  10831. 0x18: 0x0,
  10832. 0x19: 0x20020,
  10833. 0x1a: 0x8020000,
  10834. 0x1b: 0x8000820,
  10835. 0x1c: 0x8020820,
  10836. 0x1d: 0x20800,
  10837. 0x1e: 0x820,
  10838. 0x1f: 0x8000000,
  10839. 0x80000010: 0x20000,
  10840. 0x80000011: 0x800,
  10841. 0x80000012: 0x8020020,
  10842. 0x80000013: 0x20820,
  10843. 0x80000014: 0x20,
  10844. 0x80000015: 0x8020000,
  10845. 0x80000016: 0x8000000,
  10846. 0x80000017: 0x8000820,
  10847. 0x80000018: 0x8020820,
  10848. 0x80000019: 0x8000020,
  10849. 0x8000001a: 0x8000800,
  10850. 0x8000001b: 0x0,
  10851. 0x8000001c: 0x20800,
  10852. 0x8000001d: 0x820,
  10853. 0x8000001e: 0x20020,
  10854. 0x8000001f: 0x8020800
  10855. }
  10856. ];
  10857. // Masks that select the SBOX input
  10858. var SBOX_MASK = [
  10859. 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000,
  10860. 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f
  10861. ];
  10862. /**
  10863. * DES block cipher algorithm.
  10864. */
  10865. var DES = C_algo.DES = BlockCipher.extend({
  10866. _doReset: function () {
  10867. // Shortcuts
  10868. var key = this._key;
  10869. var keyWords = key.words;
  10870. // Select 56 bits according to PC1
  10871. var keyBits = [];
  10872. for (var i = 0; i < 56; i++) {
  10873. var keyBitPos = PC1[i] - 1;
  10874. keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1;
  10875. }
  10876. // Assemble 16 subkeys
  10877. var subKeys = this._subKeys = [];
  10878. for (var nSubKey = 0; nSubKey < 16; nSubKey++) {
  10879. // Create subkey
  10880. var subKey = subKeys[nSubKey] = [];
  10881. // Shortcut
  10882. var bitShift = BIT_SHIFTS[nSubKey];
  10883. // Select 48 bits according to PC2
  10884. for (var i = 0; i < 24; i++) {
  10885. // Select from the left 28 key bits
  10886. subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6);
  10887. // Select from the right 28 key bits
  10888. subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6);
  10889. }
  10890. // Since each subkey is applied to an expanded 32-bit input,
  10891. // the subkey can be broken into 8 values scaled to 32-bits,
  10892. // which allows the key to be used without expansion
  10893. subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31);
  10894. for (var i = 1; i < 7; i++) {
  10895. subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3);
  10896. }
  10897. subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27);
  10898. }
  10899. // Compute inverse subkeys
  10900. var invSubKeys = this._invSubKeys = [];
  10901. for (var i = 0; i < 16; i++) {
  10902. invSubKeys[i] = subKeys[15 - i];
  10903. }
  10904. },
  10905. encryptBlock: function (M, offset) {
  10906. this._doCryptBlock(M, offset, this._subKeys);
  10907. },
  10908. decryptBlock: function (M, offset) {
  10909. this._doCryptBlock(M, offset, this._invSubKeys);
  10910. },
  10911. _doCryptBlock: function (M, offset, subKeys) {
  10912. // Get input
  10913. this._lBlock = M[offset];
  10914. this._rBlock = M[offset + 1];
  10915. // Initial permutation
  10916. exchangeLR.call(this, 4, 0x0f0f0f0f);
  10917. exchangeLR.call(this, 16, 0x0000ffff);
  10918. exchangeRL.call(this, 2, 0x33333333);
  10919. exchangeRL.call(this, 8, 0x00ff00ff);
  10920. exchangeLR.call(this, 1, 0x55555555);
  10921. // Rounds
  10922. for (var round = 0; round < 16; round++) {
  10923. // Shortcuts
  10924. var subKey = subKeys[round];
  10925. var lBlock = this._lBlock;
  10926. var rBlock = this._rBlock;
  10927. // Feistel function
  10928. var f = 0;
  10929. for (var i = 0; i < 8; i++) {
  10930. f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0];
  10931. }
  10932. this._lBlock = rBlock;
  10933. this._rBlock = lBlock ^ f;
  10934. }
  10935. // Undo swap from last round
  10936. var t = this._lBlock;
  10937. this._lBlock = this._rBlock;
  10938. this._rBlock = t;
  10939. // Final permutation
  10940. exchangeLR.call(this, 1, 0x55555555);
  10941. exchangeRL.call(this, 8, 0x00ff00ff);
  10942. exchangeRL.call(this, 2, 0x33333333);
  10943. exchangeLR.call(this, 16, 0x0000ffff);
  10944. exchangeLR.call(this, 4, 0x0f0f0f0f);
  10945. // Set output
  10946. M[offset] = this._lBlock;
  10947. M[offset + 1] = this._rBlock;
  10948. },
  10949. keySize: 64/32,
  10950. ivSize: 64/32,
  10951. blockSize: 64/32
  10952. });
  10953. // Swap bits across the left and right words
  10954. function exchangeLR(offset, mask) {
  10955. var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask;
  10956. this._rBlock ^= t;
  10957. this._lBlock ^= t << offset;
  10958. }
  10959. function exchangeRL(offset, mask) {
  10960. var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask;
  10961. this._lBlock ^= t;
  10962. this._rBlock ^= t << offset;
  10963. }
  10964. /**
  10965. * Shortcut functions to the cipher's object interface.
  10966. *
  10967. * @example
  10968. *
  10969. * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg);
  10970. * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg);
  10971. */
  10972. C.DES = BlockCipher._createHelper(DES);
  10973. /**
  10974. * Triple-DES block cipher algorithm.
  10975. */
  10976. var TripleDES = C_algo.TripleDES = BlockCipher.extend({
  10977. _doReset: function () {
  10978. // Shortcuts
  10979. var key = this._key;
  10980. var keyWords = key.words;
  10981. // Create DES instances
  10982. this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2)));
  10983. this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4)));
  10984. this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6)));
  10985. },
  10986. encryptBlock: function (M, offset) {
  10987. this._des1.encryptBlock(M, offset);
  10988. this._des2.decryptBlock(M, offset);
  10989. this._des3.encryptBlock(M, offset);
  10990. },
  10991. decryptBlock: function (M, offset) {
  10992. this._des3.decryptBlock(M, offset);
  10993. this._des2.encryptBlock(M, offset);
  10994. this._des1.decryptBlock(M, offset);
  10995. },
  10996. keySize: 192/32,
  10997. ivSize: 64/32,
  10998. blockSize: 64/32
  10999. });
  11000. /**
  11001. * Shortcut functions to the cipher's object interface.
  11002. *
  11003. * @example
  11004. *
  11005. * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg);
  11006. * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg);
  11007. */
  11008. C.TripleDES = BlockCipher._createHelper(TripleDES);
  11009. }());
  11010. return CryptoJS.TripleDES;
  11011. }));
  11012. },{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],83:[function(require,module,exports){
  11013. ;(function (root, factory) {
  11014. if (typeof exports === "object") {
  11015. // CommonJS
  11016. module.exports = exports = factory(require("./core"));
  11017. }
  11018. else if (typeof define === "function" && define.amd) {
  11019. // AMD
  11020. define(["./core"], factory);
  11021. }
  11022. else {
  11023. // Global (browser)
  11024. factory(root.CryptoJS);
  11025. }
  11026. }(this, function (CryptoJS) {
  11027. (function (undefined) {
  11028. // Shortcuts
  11029. var C = CryptoJS;
  11030. var C_lib = C.lib;
  11031. var Base = C_lib.Base;
  11032. var X32WordArray = C_lib.WordArray;
  11033. /**
  11034. * x64 namespace.
  11035. */
  11036. var C_x64 = C.x64 = {};
  11037. /**
  11038. * A 64-bit word.
  11039. */
  11040. var X64Word = C_x64.Word = Base.extend({
  11041. /**
  11042. * Initializes a newly created 64-bit word.
  11043. *
  11044. * @param {number} high The high 32 bits.
  11045. * @param {number} low The low 32 bits.
  11046. *
  11047. * @example
  11048. *
  11049. * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
  11050. */
  11051. init: function (high, low) {
  11052. this.high = high;
  11053. this.low = low;
  11054. }
  11055. /**
  11056. * Bitwise NOTs this word.
  11057. *
  11058. * @return {X64Word} A new x64-Word object after negating.
  11059. *
  11060. * @example
  11061. *
  11062. * var negated = x64Word.not();
  11063. */
  11064. // not: function () {
  11065. // var high = ~this.high;
  11066. // var low = ~this.low;
  11067. // return X64Word.create(high, low);
  11068. // },
  11069. /**
  11070. * Bitwise ANDs this word with the passed word.
  11071. *
  11072. * @param {X64Word} word The x64-Word to AND with this word.
  11073. *
  11074. * @return {X64Word} A new x64-Word object after ANDing.
  11075. *
  11076. * @example
  11077. *
  11078. * var anded = x64Word.and(anotherX64Word);
  11079. */
  11080. // and: function (word) {
  11081. // var high = this.high & word.high;
  11082. // var low = this.low & word.low;
  11083. // return X64Word.create(high, low);
  11084. // },
  11085. /**
  11086. * Bitwise ORs this word with the passed word.
  11087. *
  11088. * @param {X64Word} word The x64-Word to OR with this word.
  11089. *
  11090. * @return {X64Word} A new x64-Word object after ORing.
  11091. *
  11092. * @example
  11093. *
  11094. * var ored = x64Word.or(anotherX64Word);
  11095. */
  11096. // or: function (word) {
  11097. // var high = this.high | word.high;
  11098. // var low = this.low | word.low;
  11099. // return X64Word.create(high, low);
  11100. // },
  11101. /**
  11102. * Bitwise XORs this word with the passed word.
  11103. *
  11104. * @param {X64Word} word The x64-Word to XOR with this word.
  11105. *
  11106. * @return {X64Word} A new x64-Word object after XORing.
  11107. *
  11108. * @example
  11109. *
  11110. * var xored = x64Word.xor(anotherX64Word);
  11111. */
  11112. // xor: function (word) {
  11113. // var high = this.high ^ word.high;
  11114. // var low = this.low ^ word.low;
  11115. // return X64Word.create(high, low);
  11116. // },
  11117. /**
  11118. * Shifts this word n bits to the left.
  11119. *
  11120. * @param {number} n The number of bits to shift.
  11121. *
  11122. * @return {X64Word} A new x64-Word object after shifting.
  11123. *
  11124. * @example
  11125. *
  11126. * var shifted = x64Word.shiftL(25);
  11127. */
  11128. // shiftL: function (n) {
  11129. // if (n < 32) {
  11130. // var high = (this.high << n) | (this.low >>> (32 - n));
  11131. // var low = this.low << n;
  11132. // } else {
  11133. // var high = this.low << (n - 32);
  11134. // var low = 0;
  11135. // }
  11136. // return X64Word.create(high, low);
  11137. // },
  11138. /**
  11139. * Shifts this word n bits to the right.
  11140. *
  11141. * @param {number} n The number of bits to shift.
  11142. *
  11143. * @return {X64Word} A new x64-Word object after shifting.
  11144. *
  11145. * @example
  11146. *
  11147. * var shifted = x64Word.shiftR(7);
  11148. */
  11149. // shiftR: function (n) {
  11150. // if (n < 32) {
  11151. // var low = (this.low >>> n) | (this.high << (32 - n));
  11152. // var high = this.high >>> n;
  11153. // } else {
  11154. // var low = this.high >>> (n - 32);
  11155. // var high = 0;
  11156. // }
  11157. // return X64Word.create(high, low);
  11158. // },
  11159. /**
  11160. * Rotates this word n bits to the left.
  11161. *
  11162. * @param {number} n The number of bits to rotate.
  11163. *
  11164. * @return {X64Word} A new x64-Word object after rotating.
  11165. *
  11166. * @example
  11167. *
  11168. * var rotated = x64Word.rotL(25);
  11169. */
  11170. // rotL: function (n) {
  11171. // return this.shiftL(n).or(this.shiftR(64 - n));
  11172. // },
  11173. /**
  11174. * Rotates this word n bits to the right.
  11175. *
  11176. * @param {number} n The number of bits to rotate.
  11177. *
  11178. * @return {X64Word} A new x64-Word object after rotating.
  11179. *
  11180. * @example
  11181. *
  11182. * var rotated = x64Word.rotR(7);
  11183. */
  11184. // rotR: function (n) {
  11185. // return this.shiftR(n).or(this.shiftL(64 - n));
  11186. // },
  11187. /**
  11188. * Adds this word with the passed word.
  11189. *
  11190. * @param {X64Word} word The x64-Word to add with this word.
  11191. *
  11192. * @return {X64Word} A new x64-Word object after adding.
  11193. *
  11194. * @example
  11195. *
  11196. * var added = x64Word.add(anotherX64Word);
  11197. */
  11198. // add: function (word) {
  11199. // var low = (this.low + word.low) | 0;
  11200. // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
  11201. // var high = (this.high + word.high + carry) | 0;
  11202. // return X64Word.create(high, low);
  11203. // }
  11204. });
  11205. /**
  11206. * An array of 64-bit words.
  11207. *
  11208. * @property {Array} words The array of CryptoJS.x64.Word objects.
  11209. * @property {number} sigBytes The number of significant bytes in this word array.
  11210. */
  11211. var X64WordArray = C_x64.WordArray = Base.extend({
  11212. /**
  11213. * Initializes a newly created word array.
  11214. *
  11215. * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
  11216. * @param {number} sigBytes (Optional) The number of significant bytes in the words.
  11217. *
  11218. * @example
  11219. *
  11220. * var wordArray = CryptoJS.x64.WordArray.create();
  11221. *
  11222. * var wordArray = CryptoJS.x64.WordArray.create([
  11223. * CryptoJS.x64.Word.create(0x00010203, 0x04050607),
  11224. * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
  11225. * ]);
  11226. *
  11227. * var wordArray = CryptoJS.x64.WordArray.create([
  11228. * CryptoJS.x64.Word.create(0x00010203, 0x04050607),
  11229. * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
  11230. * ], 10);
  11231. */
  11232. init: function (words, sigBytes) {
  11233. words = this.words = words || [];
  11234. if (sigBytes != undefined) {
  11235. this.sigBytes = sigBytes;
  11236. } else {
  11237. this.sigBytes = words.length * 8;
  11238. }
  11239. },
  11240. /**
  11241. * Converts this 64-bit word array to a 32-bit word array.
  11242. *
  11243. * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
  11244. *
  11245. * @example
  11246. *
  11247. * var x32WordArray = x64WordArray.toX32();
  11248. */
  11249. toX32: function () {
  11250. // Shortcuts
  11251. var x64Words = this.words;
  11252. var x64WordsLength = x64Words.length;
  11253. // Convert
  11254. var x32Words = [];
  11255. for (var i = 0; i < x64WordsLength; i++) {
  11256. var x64Word = x64Words[i];
  11257. x32Words.push(x64Word.high);
  11258. x32Words.push(x64Word.low);
  11259. }
  11260. return X32WordArray.create(x32Words, this.sigBytes);
  11261. },
  11262. /**
  11263. * Creates a copy of this word array.
  11264. *
  11265. * @return {X64WordArray} The clone.
  11266. *
  11267. * @example
  11268. *
  11269. * var clone = x64WordArray.clone();
  11270. */
  11271. clone: function () {
  11272. var clone = Base.clone.call(this);
  11273. // Clone "words" array
  11274. var words = clone.words = this.words.slice(0);
  11275. // Clone each X64Word object
  11276. var wordsLength = words.length;
  11277. for (var i = 0; i < wordsLength; i++) {
  11278. words[i] = words[i].clone();
  11279. }
  11280. return clone;
  11281. }
  11282. });
  11283. }());
  11284. return CryptoJS;
  11285. }));
  11286. },{"./core":52}],84:[function(require,module,exports){
  11287. /*! https://mths.be/utf8js v2.0.0 by @mathias */
  11288. ;(function(root) {
  11289. // Detect free variables exports
  11290. var freeExports = typeof exports == 'object' && exports;
  11291. // Detect free variable module
  11292. var freeModule = typeof module == 'object' && module &&
  11293. module.exports == freeExports && module;
  11294. // Detect free variable global, from Node.js or Browserified code,
  11295. // and use it as root
  11296. var freeGlobal = typeof global == 'object' && global;
  11297. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  11298. root = freeGlobal;
  11299. }
  11300. /*--------------------------------------------------------------------------*/
  11301. var stringFromCharCode = String.fromCharCode;
  11302. // Taken from https://mths.be/punycode
  11303. function ucs2decode(string) {
  11304. var output = [];
  11305. var counter = 0;
  11306. var length = string.length;
  11307. var value;
  11308. var extra;
  11309. while (counter < length) {
  11310. value = string.charCodeAt(counter++);
  11311. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  11312. // high surrogate, and there is a next character
  11313. extra = string.charCodeAt(counter++);
  11314. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  11315. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  11316. } else {
  11317. // unmatched surrogate; only append this code unit, in case the next
  11318. // code unit is the high surrogate of a surrogate pair
  11319. output.push(value);
  11320. counter--;
  11321. }
  11322. } else {
  11323. output.push(value);
  11324. }
  11325. }
  11326. return output;
  11327. }
  11328. // Taken from https://mths.be/punycode
  11329. function ucs2encode(array) {
  11330. var length = array.length;
  11331. var index = -1;
  11332. var value;
  11333. var output = '';
  11334. while (++index < length) {
  11335. value = array[index];
  11336. if (value > 0xFFFF) {
  11337. value -= 0x10000;
  11338. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  11339. value = 0xDC00 | value & 0x3FF;
  11340. }
  11341. output += stringFromCharCode(value);
  11342. }
  11343. return output;
  11344. }
  11345. function checkScalarValue(codePoint) {
  11346. if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
  11347. throw Error(
  11348. 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
  11349. ' is not a scalar value'
  11350. );
  11351. }
  11352. }
  11353. /*--------------------------------------------------------------------------*/
  11354. function createByte(codePoint, shift) {
  11355. return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
  11356. }
  11357. function encodeCodePoint(codePoint) {
  11358. if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
  11359. return stringFromCharCode(codePoint);
  11360. }
  11361. var symbol = '';
  11362. if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
  11363. symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
  11364. }
  11365. else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
  11366. checkScalarValue(codePoint);
  11367. symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
  11368. symbol += createByte(codePoint, 6);
  11369. }
  11370. else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
  11371. symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
  11372. symbol += createByte(codePoint, 12);
  11373. symbol += createByte(codePoint, 6);
  11374. }
  11375. symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
  11376. return symbol;
  11377. }
  11378. function utf8encode(string) {
  11379. var codePoints = ucs2decode(string);
  11380. var length = codePoints.length;
  11381. var index = -1;
  11382. var codePoint;
  11383. var byteString = '';
  11384. while (++index < length) {
  11385. codePoint = codePoints[index];
  11386. byteString += encodeCodePoint(codePoint);
  11387. }
  11388. return byteString;
  11389. }
  11390. /*--------------------------------------------------------------------------*/
  11391. function readContinuationByte() {
  11392. if (byteIndex >= byteCount) {
  11393. throw Error('Invalid byte index');
  11394. }
  11395. var continuationByte = byteArray[byteIndex] & 0xFF;
  11396. byteIndex++;
  11397. if ((continuationByte & 0xC0) == 0x80) {
  11398. return continuationByte & 0x3F;
  11399. }
  11400. // If we end up here, it’s not a continuation byte
  11401. throw Error('Invalid continuation byte');
  11402. }
  11403. function decodeSymbol() {
  11404. var byte1;
  11405. var byte2;
  11406. var byte3;
  11407. var byte4;
  11408. var codePoint;
  11409. if (byteIndex > byteCount) {
  11410. throw Error('Invalid byte index');
  11411. }
  11412. if (byteIndex == byteCount) {
  11413. return false;
  11414. }
  11415. // Read first byte
  11416. byte1 = byteArray[byteIndex] & 0xFF;
  11417. byteIndex++;
  11418. // 1-byte sequence (no continuation bytes)
  11419. if ((byte1 & 0x80) == 0) {
  11420. return byte1;
  11421. }
  11422. // 2-byte sequence
  11423. if ((byte1 & 0xE0) == 0xC0) {
  11424. var byte2 = readContinuationByte();
  11425. codePoint = ((byte1 & 0x1F) << 6) | byte2;
  11426. if (codePoint >= 0x80) {
  11427. return codePoint;
  11428. } else {
  11429. throw Error('Invalid continuation byte');
  11430. }
  11431. }
  11432. // 3-byte sequence (may include unpaired surrogates)
  11433. if ((byte1 & 0xF0) == 0xE0) {
  11434. byte2 = readContinuationByte();
  11435. byte3 = readContinuationByte();
  11436. codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
  11437. if (codePoint >= 0x0800) {
  11438. checkScalarValue(codePoint);
  11439. return codePoint;
  11440. } else {
  11441. throw Error('Invalid continuation byte');
  11442. }
  11443. }
  11444. // 4-byte sequence
  11445. if ((byte1 & 0xF8) == 0xF0) {
  11446. byte2 = readContinuationByte();
  11447. byte3 = readContinuationByte();
  11448. byte4 = readContinuationByte();
  11449. codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
  11450. (byte3 << 0x06) | byte4;
  11451. if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
  11452. return codePoint;
  11453. }
  11454. }
  11455. throw Error('Invalid UTF-8 detected');
  11456. }
  11457. var byteArray;
  11458. var byteCount;
  11459. var byteIndex;
  11460. function utf8decode(byteString) {
  11461. byteArray = ucs2decode(byteString);
  11462. byteCount = byteArray.length;
  11463. byteIndex = 0;
  11464. var codePoints = [];
  11465. var tmp;
  11466. while ((tmp = decodeSymbol()) !== false) {
  11467. codePoints.push(tmp);
  11468. }
  11469. return ucs2encode(codePoints);
  11470. }
  11471. /*--------------------------------------------------------------------------*/
  11472. var utf8 = {
  11473. 'version': '2.0.0',
  11474. 'encode': utf8encode,
  11475. 'decode': utf8decode
  11476. };
  11477. // Some AMD build optimizers, like r.js, check for specific condition patterns
  11478. // like the following:
  11479. if (
  11480. typeof define == 'function' &&
  11481. typeof define.amd == 'object' &&
  11482. define.amd
  11483. ) {
  11484. define(function() {
  11485. return utf8;
  11486. });
  11487. } else if (freeExports && !freeExports.nodeType) {
  11488. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  11489. freeModule.exports = utf8;
  11490. } else { // in Narwhal or RingoJS v0.7.0-
  11491. var object = {};
  11492. var hasOwnProperty = object.hasOwnProperty;
  11493. for (var key in utf8) {
  11494. hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
  11495. }
  11496. }
  11497. } else { // in Rhino or a web browser
  11498. root.utf8 = utf8;
  11499. }
  11500. }(this));
  11501. },{}],"bignumber.js":[function(require,module,exports){
  11502. /*! bignumber.js v2.0.7 https://github.com/MikeMcl/bignumber.js/LICENCE */
  11503. ;(function (global) {
  11504. 'use strict';
  11505. /*
  11506. bignumber.js v2.0.7
  11507. A JavaScript library for arbitrary-precision arithmetic.
  11508. https://github.com/MikeMcl/bignumber.js
  11509. Copyright (c) 2015 Michael Mclaughlin <M8ch88l@gmail.com>
  11510. MIT Expat Licence
  11511. */
  11512. var BigNumber, crypto, parseNumeric,
  11513. isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
  11514. mathceil = Math.ceil,
  11515. mathfloor = Math.floor,
  11516. notBool = ' not a boolean or binary digit',
  11517. roundingMode = 'rounding mode',
  11518. tooManyDigits = 'number type has more than 15 significant digits',
  11519. ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_',
  11520. BASE = 1e14,
  11521. LOG_BASE = 14,
  11522. MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1
  11523. // MAX_INT32 = 0x7fffffff, // 2^31 - 1
  11524. POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],
  11525. SQRT_BASE = 1e7,
  11526. /*
  11527. * The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and
  11528. * the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an
  11529. * exception is thrown (if ERRORS is true).
  11530. */
  11531. MAX = 1E9; // 0 to MAX_INT32
  11532. /*
  11533. * Create and return a BigNumber constructor.
  11534. */
  11535. function another(configObj) {
  11536. var div,
  11537. // id tracks the caller function, so its name can be included in error messages.
  11538. id = 0,
  11539. P = BigNumber.prototype,
  11540. ONE = new BigNumber(1),
  11541. /********************************* EDITABLE DEFAULTS **********************************/
  11542. /*
  11543. * The default values below must be integers within the inclusive ranges stated.
  11544. * The values can also be changed at run-time using BigNumber.config.
  11545. */
  11546. // The maximum number of decimal places for operations involving division.
  11547. DECIMAL_PLACES = 20, // 0 to MAX
  11548. /*
  11549. * The rounding mode used when rounding to the above decimal places, and when using
  11550. * toExponential, toFixed, toFormat and toPrecision, and round (default value).
  11551. * UP 0 Away from zero.
  11552. * DOWN 1 Towards zero.
  11553. * CEIL 2 Towards +Infinity.
  11554. * FLOOR 3 Towards -Infinity.
  11555. * HALF_UP 4 Towards nearest neighbour. If equidistant, up.
  11556. * HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
  11557. * HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
  11558. * HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
  11559. * HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
  11560. */
  11561. ROUNDING_MODE = 4, // 0 to 8
  11562. // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
  11563. // The exponent value at and beneath which toString returns exponential notation.
  11564. // Number type: -7
  11565. TO_EXP_NEG = -7, // 0 to -MAX
  11566. // The exponent value at and above which toString returns exponential notation.
  11567. // Number type: 21
  11568. TO_EXP_POS = 21, // 0 to MAX
  11569. // RANGE : [MIN_EXP, MAX_EXP]
  11570. // The minimum exponent value, beneath which underflow to zero occurs.
  11571. // Number type: -324 (5e-324)
  11572. MIN_EXP = -1e7, // -1 to -MAX
  11573. // The maximum exponent value, above which overflow to Infinity occurs.
  11574. // Number type: 308 (1.7976931348623157e+308)
  11575. // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
  11576. MAX_EXP = 1e7, // 1 to MAX
  11577. // Whether BigNumber Errors are ever thrown.
  11578. ERRORS = true, // true or false
  11579. // Change to intValidatorNoErrors if ERRORS is false.
  11580. isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors
  11581. // Whether to use cryptographically-secure random number generation, if available.
  11582. CRYPTO = false, // true or false
  11583. /*
  11584. * The modulo mode used when calculating the modulus: a mod n.
  11585. * The quotient (q = a / n) is calculated according to the corresponding rounding mode.
  11586. * The remainder (r) is calculated as: r = a - n * q.
  11587. *
  11588. * UP 0 The remainder is positive if the dividend is negative, else is negative.
  11589. * DOWN 1 The remainder has the same sign as the dividend.
  11590. * This modulo mode is commonly known as 'truncated division' and is
  11591. * equivalent to (a % n) in JavaScript.
  11592. * FLOOR 3 The remainder has the same sign as the divisor (Python %).
  11593. * HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
  11594. * EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).
  11595. * The remainder is always positive.
  11596. *
  11597. * The truncated division, floored division, Euclidian division and IEEE 754 remainder
  11598. * modes are commonly used for the modulus operation.
  11599. * Although the other rounding modes can also be used, they may not give useful results.
  11600. */
  11601. MODULO_MODE = 1, // 0 to 9
  11602. // The maximum number of significant digits of the result of the toPower operation.
  11603. // If POW_PRECISION is 0, there will be unlimited significant digits.
  11604. POW_PRECISION = 100, // 0 to MAX
  11605. // The format specification used by the BigNumber.prototype.toFormat method.
  11606. FORMAT = {
  11607. decimalSeparator: '.',
  11608. groupSeparator: ',',
  11609. groupSize: 3,
  11610. secondaryGroupSize: 0,
  11611. fractionGroupSeparator: '\xA0', // non-breaking space
  11612. fractionGroupSize: 0
  11613. };
  11614. /******************************************************************************************/
  11615. // CONSTRUCTOR
  11616. /*
  11617. * The BigNumber constructor and exported function.
  11618. * Create and return a new instance of a BigNumber object.
  11619. *
  11620. * n {number|string|BigNumber} A numeric value.
  11621. * [b] {number} The base of n. Integer, 2 to 64 inclusive.
  11622. */
  11623. function BigNumber( n, b ) {
  11624. var c, e, i, num, len, str,
  11625. x = this;
  11626. // Enable constructor usage without new.
  11627. if ( !( x instanceof BigNumber ) ) {
  11628. // 'BigNumber() constructor call without new: {n}'
  11629. if (ERRORS) raise( 26, 'constructor call without new', n );
  11630. return new BigNumber( n, b );
  11631. }
  11632. // 'new BigNumber() base not an integer: {b}'
  11633. // 'new BigNumber() base out of range: {b}'
  11634. if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) {
  11635. // Duplicate.
  11636. if ( n instanceof BigNumber ) {
  11637. x.s = n.s;
  11638. x.e = n.e;
  11639. x.c = ( n = n.c ) ? n.slice() : n;
  11640. id = 0;
  11641. return;
  11642. }
  11643. if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) {
  11644. x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1;
  11645. // Fast path for integers.
  11646. if ( n === ~~n ) {
  11647. for ( e = 0, i = n; i >= 10; i /= 10, e++ );
  11648. x.e = e;
  11649. x.c = [n];
  11650. id = 0;
  11651. return;
  11652. }
  11653. str = n + '';
  11654. } else {
  11655. if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num );
  11656. x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
  11657. }
  11658. } else {
  11659. b = b | 0;
  11660. str = n + '';
  11661. // Ensure return value is rounded to DECIMAL_PLACES as with other bases.
  11662. // Allow exponential notation to be used with base 10 argument.
  11663. if ( b == 10 ) {
  11664. x = new BigNumber( n instanceof BigNumber ? n : str );
  11665. return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE );
  11666. }
  11667. // Avoid potential interpretation of Infinity and NaN as base 44+ values.
  11668. // Any number in exponential form will fail due to the [Ee][+-].
  11669. if ( ( num = typeof n == 'number' ) && n * 0 != 0 ||
  11670. !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) +
  11671. '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) {
  11672. return parseNumeric( x, str, num, b );
  11673. }
  11674. if (num) {
  11675. x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1;
  11676. if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) {
  11677. // 'new BigNumber() number type has more than 15 significant digits: {n}'
  11678. raise( id, tooManyDigits, n );
  11679. }
  11680. // Prevent later check for length on converted number.
  11681. num = false;
  11682. } else {
  11683. x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
  11684. }
  11685. str = convertBase( str, 10, b, x.s );
  11686. }
  11687. // Decimal point?
  11688. if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' );
  11689. // Exponential form?
  11690. if ( ( i = str.search( /e/i ) ) > 0 ) {
  11691. // Determine exponent.
  11692. if ( e < 0 ) e = i;
  11693. e += +str.slice( i + 1 );
  11694. str = str.substring( 0, i );
  11695. } else if ( e < 0 ) {
  11696. // Integer.
  11697. e = str.length;
  11698. }
  11699. // Determine leading zeros.
  11700. for ( i = 0; str.charCodeAt(i) === 48; i++ );
  11701. // Determine trailing zeros.
  11702. for ( len = str.length; str.charCodeAt(--len) === 48; );
  11703. str = str.slice( i, len + 1 );
  11704. if (str) {
  11705. len = str.length;
  11706. // Disallow numbers with over 15 significant digits if number type.
  11707. // 'new BigNumber() number type has more than 15 significant digits: {n}'
  11708. if ( num && ERRORS && len > 15 ) raise( id, tooManyDigits, x.s * n );
  11709. e = e - i - 1;
  11710. // Overflow?
  11711. if ( e > MAX_EXP ) {
  11712. // Infinity.
  11713. x.c = x.e = null;
  11714. // Underflow?
  11715. } else if ( e < MIN_EXP ) {
  11716. // Zero.
  11717. x.c = [ x.e = 0 ];
  11718. } else {
  11719. x.e = e;
  11720. x.c = [];
  11721. // Transform base
  11722. // e is the base 10 exponent.
  11723. // i is where to slice str to get the first element of the coefficient array.
  11724. i = ( e + 1 ) % LOG_BASE;
  11725. if ( e < 0 ) i += LOG_BASE;
  11726. if ( i < len ) {
  11727. if (i) x.c.push( +str.slice( 0, i ) );
  11728. for ( len -= LOG_BASE; i < len; ) {
  11729. x.c.push( +str.slice( i, i += LOG_BASE ) );
  11730. }
  11731. str = str.slice(i);
  11732. i = LOG_BASE - str.length;
  11733. } else {
  11734. i -= len;
  11735. }
  11736. for ( ; i--; str += '0' );
  11737. x.c.push( +str );
  11738. }
  11739. } else {
  11740. // Zero.
  11741. x.c = [ x.e = 0 ];
  11742. }
  11743. id = 0;
  11744. }
  11745. // CONSTRUCTOR PROPERTIES
  11746. BigNumber.another = another;
  11747. BigNumber.ROUND_UP = 0;
  11748. BigNumber.ROUND_DOWN = 1;
  11749. BigNumber.ROUND_CEIL = 2;
  11750. BigNumber.ROUND_FLOOR = 3;
  11751. BigNumber.ROUND_HALF_UP = 4;
  11752. BigNumber.ROUND_HALF_DOWN = 5;
  11753. BigNumber.ROUND_HALF_EVEN = 6;
  11754. BigNumber.ROUND_HALF_CEIL = 7;
  11755. BigNumber.ROUND_HALF_FLOOR = 8;
  11756. BigNumber.EUCLID = 9;
  11757. /*
  11758. * Configure infrequently-changing library-wide settings.
  11759. *
  11760. * Accept an object or an argument list, with one or many of the following properties or
  11761. * parameters respectively:
  11762. *
  11763. * DECIMAL_PLACES {number} Integer, 0 to MAX inclusive
  11764. * ROUNDING_MODE {number} Integer, 0 to 8 inclusive
  11765. * EXPONENTIAL_AT {number|number[]} Integer, -MAX to MAX inclusive or
  11766. * [integer -MAX to 0 incl., 0 to MAX incl.]
  11767. * RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
  11768. * [integer -MAX to -1 incl., integer 1 to MAX incl.]
  11769. * ERRORS {boolean|number} true, false, 1 or 0
  11770. * CRYPTO {boolean|number} true, false, 1 or 0
  11771. * MODULO_MODE {number} 0 to 9 inclusive
  11772. * POW_PRECISION {number} 0 to MAX inclusive
  11773. * FORMAT {object} See BigNumber.prototype.toFormat
  11774. * decimalSeparator {string}
  11775. * groupSeparator {string}
  11776. * groupSize {number}
  11777. * secondaryGroupSize {number}
  11778. * fractionGroupSeparator {string}
  11779. * fractionGroupSize {number}
  11780. *
  11781. * (The values assigned to the above FORMAT object properties are not checked for validity.)
  11782. *
  11783. * E.g.
  11784. * BigNumber.config(20, 4) is equivalent to
  11785. * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })
  11786. *
  11787. * Ignore properties/parameters set to null or undefined.
  11788. * Return an object with the properties current values.
  11789. */
  11790. BigNumber.config = function () {
  11791. var v, p,
  11792. i = 0,
  11793. r = {},
  11794. a = arguments,
  11795. o = a[0],
  11796. has = o && typeof o == 'object'
  11797. ? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; }
  11798. : function () { if ( a.length > i ) return ( v = a[i++] ) != null; };
  11799. // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.
  11800. // 'config() DECIMAL_PLACES not an integer: {v}'
  11801. // 'config() DECIMAL_PLACES out of range: {v}'
  11802. if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) {
  11803. DECIMAL_PLACES = v | 0;
  11804. }
  11805. r[p] = DECIMAL_PLACES;
  11806. // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.
  11807. // 'config() ROUNDING_MODE not an integer: {v}'
  11808. // 'config() ROUNDING_MODE out of range: {v}'
  11809. if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) {
  11810. ROUNDING_MODE = v | 0;
  11811. }
  11812. r[p] = ROUNDING_MODE;
  11813. // EXPONENTIAL_AT {number|number[]}
  11814. // Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive].
  11815. // 'config() EXPONENTIAL_AT not an integer: {v}'
  11816. // 'config() EXPONENTIAL_AT out of range: {v}'
  11817. if ( has( p = 'EXPONENTIAL_AT' ) ) {
  11818. if ( isArray(v) ) {
  11819. if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) {
  11820. TO_EXP_NEG = v[0] | 0;
  11821. TO_EXP_POS = v[1] | 0;
  11822. }
  11823. } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
  11824. TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 );
  11825. }
  11826. }
  11827. r[p] = [ TO_EXP_NEG, TO_EXP_POS ];
  11828. // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
  11829. // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].
  11830. // 'config() RANGE not an integer: {v}'
  11831. // 'config() RANGE cannot be zero: {v}'
  11832. // 'config() RANGE out of range: {v}'
  11833. if ( has( p = 'RANGE' ) ) {
  11834. if ( isArray(v) ) {
  11835. if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) {
  11836. MIN_EXP = v[0] | 0;
  11837. MAX_EXP = v[1] | 0;
  11838. }
  11839. } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
  11840. if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 );
  11841. else if (ERRORS) raise( 2, p + ' cannot be zero', v );
  11842. }
  11843. }
  11844. r[p] = [ MIN_EXP, MAX_EXP ];
  11845. // ERRORS {boolean|number} true, false, 1 or 0.
  11846. // 'config() ERRORS not a boolean or binary digit: {v}'
  11847. if ( has( p = 'ERRORS' ) ) {
  11848. if ( v === !!v || v === 1 || v === 0 ) {
  11849. id = 0;
  11850. isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors;
  11851. } else if (ERRORS) {
  11852. raise( 2, p + notBool, v );
  11853. }
  11854. }
  11855. r[p] = ERRORS;
  11856. // CRYPTO {boolean|number} true, false, 1 or 0.
  11857. // 'config() CRYPTO not a boolean or binary digit: {v}'
  11858. // 'config() crypto unavailable: {crypto}'
  11859. if ( has( p = 'CRYPTO' ) ) {
  11860. if ( v === !!v || v === 1 || v === 0 ) {
  11861. CRYPTO = !!( v && crypto && typeof crypto == 'object' );
  11862. if ( v && !CRYPTO && ERRORS ) raise( 2, 'crypto unavailable', crypto );
  11863. } else if (ERRORS) {
  11864. raise( 2, p + notBool, v );
  11865. }
  11866. }
  11867. r[p] = CRYPTO;
  11868. // MODULO_MODE {number} Integer, 0 to 9 inclusive.
  11869. // 'config() MODULO_MODE not an integer: {v}'
  11870. // 'config() MODULO_MODE out of range: {v}'
  11871. if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) {
  11872. MODULO_MODE = v | 0;
  11873. }
  11874. r[p] = MODULO_MODE;
  11875. // POW_PRECISION {number} Integer, 0 to MAX inclusive.
  11876. // 'config() POW_PRECISION not an integer: {v}'
  11877. // 'config() POW_PRECISION out of range: {v}'
  11878. if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) {
  11879. POW_PRECISION = v | 0;
  11880. }
  11881. r[p] = POW_PRECISION;
  11882. // FORMAT {object}
  11883. // 'config() FORMAT not an object: {v}'
  11884. if ( has( p = 'FORMAT' ) ) {
  11885. if ( typeof v == 'object' ) {
  11886. FORMAT = v;
  11887. } else if (ERRORS) {
  11888. raise( 2, p + ' not an object', v );
  11889. }
  11890. }
  11891. r[p] = FORMAT;
  11892. return r;
  11893. };
  11894. /*
  11895. * Return a new BigNumber whose value is the maximum of the arguments.
  11896. *
  11897. * arguments {number|string|BigNumber}
  11898. */
  11899. BigNumber.max = function () { return maxOrMin( arguments, P.lt ); };
  11900. /*
  11901. * Return a new BigNumber whose value is the minimum of the arguments.
  11902. *
  11903. * arguments {number|string|BigNumber}
  11904. */
  11905. BigNumber.min = function () { return maxOrMin( arguments, P.gt ); };
  11906. /*
  11907. * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,
  11908. * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing
  11909. * zeros are produced).
  11910. *
  11911. * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
  11912. *
  11913. * 'random() decimal places not an integer: {dp}'
  11914. * 'random() decimal places out of range: {dp}'
  11915. * 'random() crypto unavailable: {crypto}'
  11916. */
  11917. BigNumber.random = (function () {
  11918. var pow2_53 = 0x20000000000000;
  11919. // Return a 53 bit integer n, where 0 <= n < 9007199254740992.
  11920. // Check if Math.random() produces more than 32 bits of randomness.
  11921. // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.
  11922. // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.
  11923. var random53bitInt = (Math.random() * pow2_53) & 0x1fffff
  11924. ? function () { return mathfloor( Math.random() * pow2_53 ); }
  11925. : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +
  11926. (Math.random() * 0x800000 | 0); };
  11927. return function (dp) {
  11928. var a, b, e, k, v,
  11929. i = 0,
  11930. c = [],
  11931. rand = new BigNumber(ONE);
  11932. dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0;
  11933. k = mathceil( dp / LOG_BASE );
  11934. if (CRYPTO) {
  11935. // Browsers supporting crypto.getRandomValues.
  11936. if ( crypto && crypto.getRandomValues ) {
  11937. a = crypto.getRandomValues( new Uint32Array( k *= 2 ) );
  11938. for ( ; i < k; ) {
  11939. // 53 bits:
  11940. // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)
  11941. // 11111 11111111 11111111 11111111 11100000 00000000 00000000
  11942. // ((Math.pow(2, 32) - 1) >>> 11).toString(2)
  11943. // 11111 11111111 11111111
  11944. // 0x20000 is 2^21.
  11945. v = a[i] * 0x20000 + (a[i + 1] >>> 11);
  11946. // Rejection sampling:
  11947. // 0 <= v < 9007199254740992
  11948. // Probability that v >= 9e15, is
  11949. // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251
  11950. if ( v >= 9e15 ) {
  11951. b = crypto.getRandomValues( new Uint32Array(2) );
  11952. a[i] = b[0];
  11953. a[i + 1] = b[1];
  11954. } else {
  11955. // 0 <= v <= 8999999999999999
  11956. // 0 <= (v % 1e14) <= 99999999999999
  11957. c.push( v % 1e14 );
  11958. i += 2;
  11959. }
  11960. }
  11961. i = k / 2;
  11962. // Node.js supporting crypto.randomBytes.
  11963. } else if ( crypto && crypto.randomBytes ) {
  11964. // buffer
  11965. a = crypto.randomBytes( k *= 7 );
  11966. for ( ; i < k; ) {
  11967. // 0x1000000000000 is 2^48, 0x10000000000 is 2^40
  11968. // 0x100000000 is 2^32, 0x1000000 is 2^24
  11969. // 11111 11111111 11111111 11111111 11111111 11111111 11111111
  11970. // 0 <= v < 9007199254740992
  11971. v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) +
  11972. ( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) +
  11973. ( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6];
  11974. if ( v >= 9e15 ) {
  11975. crypto.randomBytes(7).copy( a, i );
  11976. } else {
  11977. // 0 <= (v % 1e14) <= 99999999999999
  11978. c.push( v % 1e14 );
  11979. i += 7;
  11980. }
  11981. }
  11982. i = k / 7;
  11983. } else if (ERRORS) {
  11984. raise( 14, 'crypto unavailable', crypto );
  11985. }
  11986. }
  11987. // Use Math.random: CRYPTO is false or crypto is unavailable and ERRORS is false.
  11988. if (!i) {
  11989. for ( ; i < k; ) {
  11990. v = random53bitInt();
  11991. if ( v < 9e15 ) c[i++] = v % 1e14;
  11992. }
  11993. }
  11994. k = c[--i];
  11995. dp %= LOG_BASE;
  11996. // Convert trailing digits to zeros according to dp.
  11997. if ( k && dp ) {
  11998. v = POWS_TEN[LOG_BASE - dp];
  11999. c[i] = mathfloor( k / v ) * v;
  12000. }
  12001. // Remove trailing elements which are zero.
  12002. for ( ; c[i] === 0; c.pop(), i-- );
  12003. // Zero?
  12004. if ( i < 0 ) {
  12005. c = [ e = 0 ];
  12006. } else {
  12007. // Remove leading elements which are zero and adjust exponent accordingly.
  12008. for ( e = -1 ; c[0] === 0; c.shift(), e -= LOG_BASE);
  12009. // Count the digits of the first element of c to determine leading zeros, and...
  12010. for ( i = 1, v = c[0]; v >= 10; v /= 10, i++);
  12011. // adjust the exponent accordingly.
  12012. if ( i < LOG_BASE ) e -= LOG_BASE - i;
  12013. }
  12014. rand.e = e;
  12015. rand.c = c;
  12016. return rand;
  12017. };
  12018. })();
  12019. // PRIVATE FUNCTIONS
  12020. // Convert a numeric string of baseIn to a numeric string of baseOut.
  12021. function convertBase( str, baseOut, baseIn, sign ) {
  12022. var d, e, k, r, x, xc, y,
  12023. i = str.indexOf( '.' ),
  12024. dp = DECIMAL_PLACES,
  12025. rm = ROUNDING_MODE;
  12026. if ( baseIn < 37 ) str = str.toLowerCase();
  12027. // Non-integer.
  12028. if ( i >= 0 ) {
  12029. k = POW_PRECISION;
  12030. // Unlimited precision.
  12031. POW_PRECISION = 0;
  12032. str = str.replace( '.', '' );
  12033. y = new BigNumber(baseIn);
  12034. x = y.pow( str.length - i );
  12035. POW_PRECISION = k;
  12036. // Convert str as if an integer, then restore the fraction part by dividing the
  12037. // result by its base raised to a power.
  12038. y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );
  12039. y.e = y.c.length;
  12040. }
  12041. // Convert the number as integer.
  12042. xc = toBaseOut( str, baseIn, baseOut );
  12043. e = k = xc.length;
  12044. // Remove trailing zeros.
  12045. for ( ; xc[--k] == 0; xc.pop() );
  12046. if ( !xc[0] ) return '0';
  12047. if ( i < 0 ) {
  12048. --e;
  12049. } else {
  12050. x.c = xc;
  12051. x.e = e;
  12052. // sign is needed for correct rounding.
  12053. x.s = sign;
  12054. x = div( x, y, dp, rm, baseOut );
  12055. xc = x.c;
  12056. r = x.r;
  12057. e = x.e;
  12058. }
  12059. d = e + dp + 1;
  12060. // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.
  12061. i = xc[d];
  12062. k = baseOut / 2;
  12063. r = r || d < 0 || xc[d + 1] != null;
  12064. r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
  12065. : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||
  12066. rm == ( x.s < 0 ? 8 : 7 ) );
  12067. if ( d < 1 || !xc[0] ) {
  12068. // 1^-dp or 0.
  12069. str = r ? toFixedPoint( '1', -dp ) : '0';
  12070. } else {
  12071. xc.length = d;
  12072. if (r) {
  12073. // Rounding up may mean the previous digit has to be rounded up and so on.
  12074. for ( --baseOut; ++xc[--d] > baseOut; ) {
  12075. xc[d] = 0;
  12076. if ( !d ) {
  12077. ++e;
  12078. xc.unshift(1);
  12079. }
  12080. }
  12081. }
  12082. // Determine trailing zeros.
  12083. for ( k = xc.length; !xc[--k]; );
  12084. // E.g. [4, 11, 15] becomes 4bf.
  12085. for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );
  12086. str = toFixedPoint( str, e );
  12087. }
  12088. // The caller will add the sign.
  12089. return str;
  12090. }
  12091. // Perform division in the specified base. Called by div and convertBase.
  12092. div = (function () {
  12093. // Assume non-zero x and k.
  12094. function multiply( x, k, base ) {
  12095. var m, temp, xlo, xhi,
  12096. carry = 0,
  12097. i = x.length,
  12098. klo = k % SQRT_BASE,
  12099. khi = k / SQRT_BASE | 0;
  12100. for ( x = x.slice(); i--; ) {
  12101. xlo = x[i] % SQRT_BASE;
  12102. xhi = x[i] / SQRT_BASE | 0;
  12103. m = khi * xlo + xhi * klo;
  12104. temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;
  12105. carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;
  12106. x[i] = temp % base;
  12107. }
  12108. if (carry) x.unshift(carry);
  12109. return x;
  12110. }
  12111. function compare( a, b, aL, bL ) {
  12112. var i, cmp;
  12113. if ( aL != bL ) {
  12114. cmp = aL > bL ? 1 : -1;
  12115. } else {
  12116. for ( i = cmp = 0; i < aL; i++ ) {
  12117. if ( a[i] != b[i] ) {
  12118. cmp = a[i] > b[i] ? 1 : -1;
  12119. break;
  12120. }
  12121. }
  12122. }
  12123. return cmp;
  12124. }
  12125. function subtract( a, b, aL, base ) {
  12126. var i = 0;
  12127. // Subtract b from a.
  12128. for ( ; aL--; ) {
  12129. a[aL] -= i;
  12130. i = a[aL] < b[aL] ? 1 : 0;
  12131. a[aL] = i * base + a[aL] - b[aL];
  12132. }
  12133. // Remove leading zeros.
  12134. for ( ; !a[0] && a.length > 1; a.shift() );
  12135. }
  12136. // x: dividend, y: divisor.
  12137. return function ( x, y, dp, rm, base ) {
  12138. var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,
  12139. yL, yz,
  12140. s = x.s == y.s ? 1 : -1,
  12141. xc = x.c,
  12142. yc = y.c;
  12143. // Either NaN, Infinity or 0?
  12144. if ( !xc || !xc[0] || !yc || !yc[0] ) {
  12145. return new BigNumber(
  12146. // Return NaN if either NaN, or both Infinity or 0.
  12147. !x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN :
  12148. // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
  12149. xc && xc[0] == 0 || !yc ? s * 0 : s / 0
  12150. );
  12151. }
  12152. q = new BigNumber(s);
  12153. qc = q.c = [];
  12154. e = x.e - y.e;
  12155. s = dp + e + 1;
  12156. if ( !base ) {
  12157. base = BASE;
  12158. e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE );
  12159. s = s / LOG_BASE | 0;
  12160. }
  12161. // Result exponent may be one less then the current value of e.
  12162. // The coefficients of the BigNumbers from convertBase may have trailing zeros.
  12163. for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ );
  12164. if ( yc[i] > ( xc[i] || 0 ) ) e--;
  12165. if ( s < 0 ) {
  12166. qc.push(1);
  12167. more = true;
  12168. } else {
  12169. xL = xc.length;
  12170. yL = yc.length;
  12171. i = 0;
  12172. s += 2;
  12173. // Normalise xc and yc so highest order digit of yc is >= base / 2.
  12174. n = mathfloor( base / ( yc[0] + 1 ) );
  12175. // Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1.
  12176. // if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) {
  12177. if ( n > 1 ) {
  12178. yc = multiply( yc, n, base );
  12179. xc = multiply( xc, n, base );
  12180. yL = yc.length;
  12181. xL = xc.length;
  12182. }
  12183. xi = yL;
  12184. rem = xc.slice( 0, yL );
  12185. remL = rem.length;
  12186. // Add zeros to make remainder as long as divisor.
  12187. for ( ; remL < yL; rem[remL++] = 0 );
  12188. yz = yc.slice();
  12189. yz.unshift(0);
  12190. yc0 = yc[0];
  12191. if ( yc[1] >= base / 2 ) yc0++;
  12192. // Not necessary, but to prevent trial digit n > base, when using base 3.
  12193. // else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15;
  12194. do {
  12195. n = 0;
  12196. // Compare divisor and remainder.
  12197. cmp = compare( yc, rem, yL, remL );
  12198. // If divisor < remainder.
  12199. if ( cmp < 0 ) {
  12200. // Calculate trial digit, n.
  12201. rem0 = rem[0];
  12202. if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 );
  12203. // n is how many times the divisor goes into the current remainder.
  12204. n = mathfloor( rem0 / yc0 );
  12205. // Algorithm:
  12206. // 1. product = divisor * trial digit (n)
  12207. // 2. if product > remainder: product -= divisor, n--
  12208. // 3. remainder -= product
  12209. // 4. if product was < remainder at 2:
  12210. // 5. compare new remainder and divisor
  12211. // 6. If remainder > divisor: remainder -= divisor, n++
  12212. if ( n > 1 ) {
  12213. // n may be > base only when base is 3.
  12214. if (n >= base) n = base - 1;
  12215. // product = divisor * trial digit.
  12216. prod = multiply( yc, n, base );
  12217. prodL = prod.length;
  12218. remL = rem.length;
  12219. // Compare product and remainder.
  12220. // If product > remainder.
  12221. // Trial digit n too high.
  12222. // n is 1 too high about 5% of the time, and is not known to have
  12223. // ever been more than 1 too high.
  12224. while ( compare( prod, rem, prodL, remL ) == 1 ) {
  12225. n--;
  12226. // Subtract divisor from product.
  12227. subtract( prod, yL < prodL ? yz : yc, prodL, base );
  12228. prodL = prod.length;
  12229. cmp = 1;
  12230. }
  12231. } else {
  12232. // n is 0 or 1, cmp is -1.
  12233. // If n is 0, there is no need to compare yc and rem again below,
  12234. // so change cmp to 1 to avoid it.
  12235. // If n is 1, leave cmp as -1, so yc and rem are compared again.
  12236. if ( n == 0 ) {
  12237. // divisor < remainder, so n must be at least 1.
  12238. cmp = n = 1;
  12239. }
  12240. // product = divisor
  12241. prod = yc.slice();
  12242. prodL = prod.length;
  12243. }
  12244. if ( prodL < remL ) prod.unshift(0);
  12245. // Subtract product from remainder.
  12246. subtract( rem, prod, remL, base );
  12247. remL = rem.length;
  12248. // If product was < remainder.
  12249. if ( cmp == -1 ) {
  12250. // Compare divisor and new remainder.
  12251. // If divisor < new remainder, subtract divisor from remainder.
  12252. // Trial digit n too low.
  12253. // n is 1 too low about 5% of the time, and very rarely 2 too low.
  12254. while ( compare( yc, rem, yL, remL ) < 1 ) {
  12255. n++;
  12256. // Subtract divisor from remainder.
  12257. subtract( rem, yL < remL ? yz : yc, remL, base );
  12258. remL = rem.length;
  12259. }
  12260. }
  12261. } else if ( cmp === 0 ) {
  12262. n++;
  12263. rem = [0];
  12264. } // else cmp === 1 and n will be 0
  12265. // Add the next digit, n, to the result array.
  12266. qc[i++] = n;
  12267. // Update the remainder.
  12268. if ( rem[0] ) {
  12269. rem[remL++] = xc[xi] || 0;
  12270. } else {
  12271. rem = [ xc[xi] ];
  12272. remL = 1;
  12273. }
  12274. } while ( ( xi++ < xL || rem[0] != null ) && s-- );
  12275. more = rem[0] != null;
  12276. // Leading zero?
  12277. if ( !qc[0] ) qc.shift();
  12278. }
  12279. if ( base == BASE ) {
  12280. // To calculate q.e, first get the number of digits of qc[0].
  12281. for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ );
  12282. round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more );
  12283. // Caller is convertBase.
  12284. } else {
  12285. q.e = e;
  12286. q.r = +more;
  12287. }
  12288. return q;
  12289. };
  12290. })();
  12291. /*
  12292. * Return a string representing the value of BigNumber n in fixed-point or exponential
  12293. * notation rounded to the specified decimal places or significant digits.
  12294. *
  12295. * n is a BigNumber.
  12296. * i is the index of the last digit required (i.e. the digit that may be rounded up).
  12297. * rm is the rounding mode.
  12298. * caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24.
  12299. */
  12300. function format( n, i, rm, caller ) {
  12301. var c0, e, ne, len, str;
  12302. rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode )
  12303. ? rm | 0 : ROUNDING_MODE;
  12304. if ( !n.c ) return n.toString();
  12305. c0 = n.c[0];
  12306. ne = n.e;
  12307. if ( i == null ) {
  12308. str = coeffToString( n.c );
  12309. str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG
  12310. ? toExponential( str, ne )
  12311. : toFixedPoint( str, ne );
  12312. } else {
  12313. n = round( new BigNumber(n), i, rm );
  12314. // n.e may have changed if the value was rounded up.
  12315. e = n.e;
  12316. str = coeffToString( n.c );
  12317. len = str.length;
  12318. // toPrecision returns exponential notation if the number of significant digits
  12319. // specified is less than the number of digits necessary to represent the integer
  12320. // part of the value in fixed-point notation.
  12321. // Exponential notation.
  12322. if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) {
  12323. // Append zeros?
  12324. for ( ; len < i; str += '0', len++ );
  12325. str = toExponential( str, e );
  12326. // Fixed-point notation.
  12327. } else {
  12328. i -= ne;
  12329. str = toFixedPoint( str, e );
  12330. // Append zeros?
  12331. if ( e + 1 > len ) {
  12332. if ( --i > 0 ) for ( str += '.'; i--; str += '0' );
  12333. } else {
  12334. i += e - len;
  12335. if ( i > 0 ) {
  12336. if ( e + 1 == len ) str += '.';
  12337. for ( ; i--; str += '0' );
  12338. }
  12339. }
  12340. }
  12341. }
  12342. return n.s < 0 && c0 ? '-' + str : str;
  12343. }
  12344. // Handle BigNumber.max and BigNumber.min.
  12345. function maxOrMin( args, method ) {
  12346. var m, n,
  12347. i = 0;
  12348. if ( isArray( args[0] ) ) args = args[0];
  12349. m = new BigNumber( args[0] );
  12350. for ( ; ++i < args.length; ) {
  12351. n = new BigNumber( args[i] );
  12352. // If any number is NaN, return NaN.
  12353. if ( !n.s ) {
  12354. m = n;
  12355. break;
  12356. } else if ( method.call( m, n ) ) {
  12357. m = n;
  12358. }
  12359. }
  12360. return m;
  12361. }
  12362. /*
  12363. * Return true if n is an integer in range, otherwise throw.
  12364. * Use for argument validation when ERRORS is true.
  12365. */
  12366. function intValidatorWithErrors( n, min, max, caller, name ) {
  12367. if ( n < min || n > max || n != truncate(n) ) {
  12368. raise( caller, ( name || 'decimal places' ) +
  12369. ( n < min || n > max ? ' out of range' : ' not an integer' ), n );
  12370. }
  12371. return true;
  12372. }
  12373. /*
  12374. * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.
  12375. * Called by minus, plus and times.
  12376. */
  12377. function normalise( n, c, e ) {
  12378. var i = 1,
  12379. j = c.length;
  12380. // Remove trailing zeros.
  12381. for ( ; !c[--j]; c.pop() );
  12382. // Calculate the base 10 exponent. First get the number of digits of c[0].
  12383. for ( j = c[0]; j >= 10; j /= 10, i++ );
  12384. // Overflow?
  12385. if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) {
  12386. // Infinity.
  12387. n.c = n.e = null;
  12388. // Underflow?
  12389. } else if ( e < MIN_EXP ) {
  12390. // Zero.
  12391. n.c = [ n.e = 0 ];
  12392. } else {
  12393. n.e = e;
  12394. n.c = c;
  12395. }
  12396. return n;
  12397. }
  12398. // Handle values that fail the validity test in BigNumber.
  12399. parseNumeric = (function () {
  12400. var basePrefix = /^(-?)0([xbo])/i,
  12401. dotAfter = /^([^.]+)\.$/,
  12402. dotBefore = /^\.([^.]+)$/,
  12403. isInfinityOrNaN = /^-?(Infinity|NaN)$/,
  12404. whitespaceOrPlus = /^\s*\+|^\s+|\s+$/g;
  12405. return function ( x, str, num, b ) {
  12406. var base,
  12407. s = num ? str : str.replace( whitespaceOrPlus, '' );
  12408. // No exception on ±Infinity or NaN.
  12409. if ( isInfinityOrNaN.test(s) ) {
  12410. x.s = isNaN(s) ? null : s < 0 ? -1 : 1;
  12411. } else {
  12412. if ( !num ) {
  12413. // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i
  12414. s = s.replace( basePrefix, function ( m, p1, p2 ) {
  12415. base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8;
  12416. return !b || b == base ? p1 : m;
  12417. });
  12418. if (b) {
  12419. base = b;
  12420. // E.g. '1.' to '1', '.1' to '0.1'
  12421. s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' );
  12422. }
  12423. if ( str != s ) return new BigNumber( s, base );
  12424. }
  12425. // 'new BigNumber() not a number: {n}'
  12426. // 'new BigNumber() not a base {b} number: {n}'
  12427. if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str );
  12428. x.s = null;
  12429. }
  12430. x.c = x.e = null;
  12431. id = 0;
  12432. }
  12433. })();
  12434. // Throw a BigNumber Error.
  12435. function raise( caller, msg, val ) {
  12436. var error = new Error( [
  12437. 'new BigNumber', // 0
  12438. 'cmp', // 1
  12439. 'config', // 2
  12440. 'div', // 3
  12441. 'divToInt', // 4
  12442. 'eq', // 5
  12443. 'gt', // 6
  12444. 'gte', // 7
  12445. 'lt', // 8
  12446. 'lte', // 9
  12447. 'minus', // 10
  12448. 'mod', // 11
  12449. 'plus', // 12
  12450. 'precision', // 13
  12451. 'random', // 14
  12452. 'round', // 15
  12453. 'shift', // 16
  12454. 'times', // 17
  12455. 'toDigits', // 18
  12456. 'toExponential', // 19
  12457. 'toFixed', // 20
  12458. 'toFormat', // 21
  12459. 'toFraction', // 22
  12460. 'pow', // 23
  12461. 'toPrecision', // 24
  12462. 'toString', // 25
  12463. 'BigNumber' // 26
  12464. ][caller] + '() ' + msg + ': ' + val );
  12465. error.name = 'BigNumber Error';
  12466. id = 0;
  12467. throw error;
  12468. }
  12469. /*
  12470. * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.
  12471. * If r is truthy, it is known that there are more digits after the rounding digit.
  12472. */
  12473. function round( x, sd, rm, r ) {
  12474. var d, i, j, k, n, ni, rd,
  12475. xc = x.c,
  12476. pows10 = POWS_TEN;
  12477. // if x is not Infinity or NaN...
  12478. if (xc) {
  12479. // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.
  12480. // n is a base 1e14 number, the value of the element of array x.c containing rd.
  12481. // ni is the index of n within x.c.
  12482. // d is the number of digits of n.
  12483. // i is the index of rd within n including leading zeros.
  12484. // j is the actual index of rd within n (if < 0, rd is a leading zero).
  12485. out: {
  12486. // Get the number of digits of the first element of xc.
  12487. for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ );
  12488. i = sd - d;
  12489. // If the rounding digit is in the first element of xc...
  12490. if ( i < 0 ) {
  12491. i += LOG_BASE;
  12492. j = sd;
  12493. n = xc[ ni = 0 ];
  12494. // Get the rounding digit at index j of n.
  12495. rd = n / pows10[ d - j - 1 ] % 10 | 0;
  12496. } else {
  12497. ni = mathceil( ( i + 1 ) / LOG_BASE );
  12498. if ( ni >= xc.length ) {
  12499. if (r) {
  12500. // Needed by sqrt.
  12501. for ( ; xc.length <= ni; xc.push(0) );
  12502. n = rd = 0;
  12503. d = 1;
  12504. i %= LOG_BASE;
  12505. j = i - LOG_BASE + 1;
  12506. } else {
  12507. break out;
  12508. }
  12509. } else {
  12510. n = k = xc[ni];
  12511. // Get the number of digits of n.
  12512. for ( d = 1; k >= 10; k /= 10, d++ );
  12513. // Get the index of rd within n.
  12514. i %= LOG_BASE;
  12515. // Get the index of rd within n, adjusted for leading zeros.
  12516. // The number of leading zeros of n is given by LOG_BASE - d.
  12517. j = i - LOG_BASE + d;
  12518. // Get the rounding digit at index j of n.
  12519. rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0;
  12520. }
  12521. }
  12522. r = r || sd < 0 ||
  12523. // Are there any non-zero digits after the rounding digit?
  12524. // The expression n % pows10[ d - j - 1 ] returns all digits of n to the right
  12525. // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
  12526. xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] );
  12527. r = rm < 4
  12528. ? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
  12529. : rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 &&
  12530. // Check whether the digit to the left of the rounding digit is odd.
  12531. ( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 ||
  12532. rm == ( x.s < 0 ? 8 : 7 ) );
  12533. if ( sd < 1 || !xc[0] ) {
  12534. xc.length = 0;
  12535. if (r) {
  12536. // Convert sd to decimal places.
  12537. sd -= x.e + 1;
  12538. // 1, 0.1, 0.01, 0.001, 0.0001 etc.
  12539. xc[0] = pows10[ sd % LOG_BASE ];
  12540. x.e = -sd || 0;
  12541. } else {
  12542. // Zero.
  12543. xc[0] = x.e = 0;
  12544. }
  12545. return x;
  12546. }
  12547. // Remove excess digits.
  12548. if ( i == 0 ) {
  12549. xc.length = ni;
  12550. k = 1;
  12551. ni--;
  12552. } else {
  12553. xc.length = ni + 1;
  12554. k = pows10[ LOG_BASE - i ];
  12555. // E.g. 56700 becomes 56000 if 7 is the rounding digit.
  12556. // j > 0 means i > number of leading zeros of n.
  12557. xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0;
  12558. }
  12559. // Round up?
  12560. if (r) {
  12561. for ( ; ; ) {
  12562. // If the digit to be rounded up is in the first element of xc...
  12563. if ( ni == 0 ) {
  12564. // i will be the length of xc[0] before k is added.
  12565. for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ );
  12566. j = xc[0] += k;
  12567. for ( k = 1; j >= 10; j /= 10, k++ );
  12568. // if i != k the length has increased.
  12569. if ( i != k ) {
  12570. x.e++;
  12571. if ( xc[0] == BASE ) xc[0] = 1;
  12572. }
  12573. break;
  12574. } else {
  12575. xc[ni] += k;
  12576. if ( xc[ni] != BASE ) break;
  12577. xc[ni--] = 0;
  12578. k = 1;
  12579. }
  12580. }
  12581. }
  12582. // Remove trailing zeros.
  12583. for ( i = xc.length; xc[--i] === 0; xc.pop() );
  12584. }
  12585. // Overflow? Infinity.
  12586. if ( x.e > MAX_EXP ) {
  12587. x.c = x.e = null;
  12588. // Underflow? Zero.
  12589. } else if ( x.e < MIN_EXP ) {
  12590. x.c = [ x.e = 0 ];
  12591. }
  12592. }
  12593. return x;
  12594. }
  12595. // PROTOTYPE/INSTANCE METHODS
  12596. /*
  12597. * Return a new BigNumber whose value is the absolute value of this BigNumber.
  12598. */
  12599. P.absoluteValue = P.abs = function () {
  12600. var x = new BigNumber(this);
  12601. if ( x.s < 0 ) x.s = 1;
  12602. return x;
  12603. };
  12604. /*
  12605. * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
  12606. * number in the direction of Infinity.
  12607. */
  12608. P.ceil = function () {
  12609. return round( new BigNumber(this), this.e + 1, 2 );
  12610. };
  12611. /*
  12612. * Return
  12613. * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),
  12614. * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),
  12615. * 0 if they have the same value,
  12616. * or null if the value of either is NaN.
  12617. */
  12618. P.comparedTo = P.cmp = function ( y, b ) {
  12619. id = 1;
  12620. return compare( this, new BigNumber( y, b ) );
  12621. };
  12622. /*
  12623. * Return the number of decimal places of the value of this BigNumber, or null if the value
  12624. * of this BigNumber is ±Infinity or NaN.
  12625. */
  12626. P.decimalPlaces = P.dp = function () {
  12627. var n, v,
  12628. c = this.c;
  12629. if ( !c ) return null;
  12630. n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE;
  12631. // Subtract the number of trailing zeros of the last number.
  12632. if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- );
  12633. if ( n < 0 ) n = 0;
  12634. return n;
  12635. };
  12636. /*
  12637. * n / 0 = I
  12638. * n / N = N
  12639. * n / I = 0
  12640. * 0 / n = 0
  12641. * 0 / 0 = N
  12642. * 0 / N = N
  12643. * 0 / I = 0
  12644. * N / n = N
  12645. * N / 0 = N
  12646. * N / N = N
  12647. * N / I = N
  12648. * I / n = I
  12649. * I / 0 = I
  12650. * I / N = N
  12651. * I / I = N
  12652. *
  12653. * Return a new BigNumber whose value is the value of this BigNumber divided by the value of
  12654. * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.
  12655. */
  12656. P.dividedBy = P.div = function ( y, b ) {
  12657. id = 3;
  12658. return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE );
  12659. };
  12660. /*
  12661. * Return a new BigNumber whose value is the integer part of dividing the value of this
  12662. * BigNumber by the value of BigNumber(y, b).
  12663. */
  12664. P.dividedToIntegerBy = P.divToInt = function ( y, b ) {
  12665. id = 4;
  12666. return div( this, new BigNumber( y, b ), 0, 1 );
  12667. };
  12668. /*
  12669. * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),
  12670. * otherwise returns false.
  12671. */
  12672. P.equals = P.eq = function ( y, b ) {
  12673. id = 5;
  12674. return compare( this, new BigNumber( y, b ) ) === 0;
  12675. };
  12676. /*
  12677. * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
  12678. * number in the direction of -Infinity.
  12679. */
  12680. P.floor = function () {
  12681. return round( new BigNumber(this), this.e + 1, 3 );
  12682. };
  12683. /*
  12684. * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),
  12685. * otherwise returns false.
  12686. */
  12687. P.greaterThan = P.gt = function ( y, b ) {
  12688. id = 6;
  12689. return compare( this, new BigNumber( y, b ) ) > 0;
  12690. };
  12691. /*
  12692. * Return true if the value of this BigNumber is greater than or equal to the value of
  12693. * BigNumber(y, b), otherwise returns false.
  12694. */
  12695. P.greaterThanOrEqualTo = P.gte = function ( y, b ) {
  12696. id = 7;
  12697. return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0;
  12698. };
  12699. /*
  12700. * Return true if the value of this BigNumber is a finite number, otherwise returns false.
  12701. */
  12702. P.isFinite = function () {
  12703. return !!this.c;
  12704. };
  12705. /*
  12706. * Return true if the value of this BigNumber is an integer, otherwise return false.
  12707. */
  12708. P.isInteger = P.isInt = function () {
  12709. return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2;
  12710. };
  12711. /*
  12712. * Return true if the value of this BigNumber is NaN, otherwise returns false.
  12713. */
  12714. P.isNaN = function () {
  12715. return !this.s;
  12716. };
  12717. /*
  12718. * Return true if the value of this BigNumber is negative, otherwise returns false.
  12719. */
  12720. P.isNegative = P.isNeg = function () {
  12721. return this.s < 0;
  12722. };
  12723. /*
  12724. * Return true if the value of this BigNumber is 0 or -0, otherwise returns false.
  12725. */
  12726. P.isZero = function () {
  12727. return !!this.c && this.c[0] == 0;
  12728. };
  12729. /*
  12730. * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),
  12731. * otherwise returns false.
  12732. */
  12733. P.lessThan = P.lt = function ( y, b ) {
  12734. id = 8;
  12735. return compare( this, new BigNumber( y, b ) ) < 0;
  12736. };
  12737. /*
  12738. * Return true if the value of this BigNumber is less than or equal to the value of
  12739. * BigNumber(y, b), otherwise returns false.
  12740. */
  12741. P.lessThanOrEqualTo = P.lte = function ( y, b ) {
  12742. id = 9;
  12743. return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0;
  12744. };
  12745. /*
  12746. * n - 0 = n
  12747. * n - N = N
  12748. * n - I = -I
  12749. * 0 - n = -n
  12750. * 0 - 0 = 0
  12751. * 0 - N = N
  12752. * 0 - I = -I
  12753. * N - n = N
  12754. * N - 0 = N
  12755. * N - N = N
  12756. * N - I = N
  12757. * I - n = I
  12758. * I - 0 = I
  12759. * I - N = N
  12760. * I - I = N
  12761. *
  12762. * Return a new BigNumber whose value is the value of this BigNumber minus the value of
  12763. * BigNumber(y, b).
  12764. */
  12765. P.minus = P.sub = function ( y, b ) {
  12766. var i, j, t, xLTy,
  12767. x = this,
  12768. a = x.s;
  12769. id = 10;
  12770. y = new BigNumber( y, b );
  12771. b = y.s;
  12772. // Either NaN?
  12773. if ( !a || !b ) return new BigNumber(NaN);
  12774. // Signs differ?
  12775. if ( a != b ) {
  12776. y.s = -b;
  12777. return x.plus(y);
  12778. }
  12779. var xe = x.e / LOG_BASE,
  12780. ye = y.e / LOG_BASE,
  12781. xc = x.c,
  12782. yc = y.c;
  12783. if ( !xe || !ye ) {
  12784. // Either Infinity?
  12785. if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN );
  12786. // Either zero?
  12787. if ( !xc[0] || !yc[0] ) {
  12788. // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
  12789. return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x :
  12790. // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
  12791. ROUNDING_MODE == 3 ? -0 : 0 );
  12792. }
  12793. }
  12794. xe = bitFloor(xe);
  12795. ye = bitFloor(ye);
  12796. xc = xc.slice();
  12797. // Determine which is the bigger number.
  12798. if ( a = xe - ye ) {
  12799. if ( xLTy = a < 0 ) {
  12800. a = -a;
  12801. t = xc;
  12802. } else {
  12803. ye = xe;
  12804. t = yc;
  12805. }
  12806. t.reverse();
  12807. // Prepend zeros to equalise exponents.
  12808. for ( b = a; b--; t.push(0) );
  12809. t.reverse();
  12810. } else {
  12811. // Exponents equal. Check digit by digit.
  12812. j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b;
  12813. for ( a = b = 0; b < j; b++ ) {
  12814. if ( xc[b] != yc[b] ) {
  12815. xLTy = xc[b] < yc[b];
  12816. break;
  12817. }
  12818. }
  12819. }
  12820. // x < y? Point xc to the array of the bigger number.
  12821. if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s;
  12822. b = ( j = yc.length ) - ( i = xc.length );
  12823. // Append zeros to xc if shorter.
  12824. // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.
  12825. if ( b > 0 ) for ( ; b--; xc[i++] = 0 );
  12826. b = BASE - 1;
  12827. // Subtract yc from xc.
  12828. for ( ; j > a; ) {
  12829. if ( xc[--j] < yc[j] ) {
  12830. for ( i = j; i && !xc[--i]; xc[i] = b );
  12831. --xc[i];
  12832. xc[j] += BASE;
  12833. }
  12834. xc[j] -= yc[j];
  12835. }
  12836. // Remove leading zeros and adjust exponent accordingly.
  12837. for ( ; xc[0] == 0; xc.shift(), --ye );
  12838. // Zero?
  12839. if ( !xc[0] ) {
  12840. // Following IEEE 754 (2008) 6.3,
  12841. // n - n = +0 but n - n = -0 when rounding towards -Infinity.
  12842. y.s = ROUNDING_MODE == 3 ? -1 : 1;
  12843. y.c = [ y.e = 0 ];
  12844. return y;
  12845. }
  12846. // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity
  12847. // for finite x and y.
  12848. return normalise( y, xc, ye );
  12849. };
  12850. /*
  12851. * n % 0 = N
  12852. * n % N = N
  12853. * n % I = n
  12854. * 0 % n = 0
  12855. * -0 % n = -0
  12856. * 0 % 0 = N
  12857. * 0 % N = N
  12858. * 0 % I = 0
  12859. * N % n = N
  12860. * N % 0 = N
  12861. * N % N = N
  12862. * N % I = N
  12863. * I % n = N
  12864. * I % 0 = N
  12865. * I % N = N
  12866. * I % I = N
  12867. *
  12868. * Return a new BigNumber whose value is the value of this BigNumber modulo the value of
  12869. * BigNumber(y, b). The result depends on the value of MODULO_MODE.
  12870. */
  12871. P.modulo = P.mod = function ( y, b ) {
  12872. var q, s,
  12873. x = this;
  12874. id = 11;
  12875. y = new BigNumber( y, b );
  12876. // Return NaN if x is Infinity or NaN, or y is NaN or zero.
  12877. if ( !x.c || !y.s || y.c && !y.c[0] ) {
  12878. return new BigNumber(NaN);
  12879. // Return x if y is Infinity or x is zero.
  12880. } else if ( !y.c || x.c && !x.c[0] ) {
  12881. return new BigNumber(x);
  12882. }
  12883. if ( MODULO_MODE == 9 ) {
  12884. // Euclidian division: q = sign(y) * floor(x / abs(y))
  12885. // r = x - qy where 0 <= r < abs(y)
  12886. s = y.s;
  12887. y.s = 1;
  12888. q = div( x, y, 0, 3 );
  12889. y.s = s;
  12890. q.s *= s;
  12891. } else {
  12892. q = div( x, y, 0, MODULO_MODE );
  12893. }
  12894. return x.minus( q.times(y) );
  12895. };
  12896. /*
  12897. * Return a new BigNumber whose value is the value of this BigNumber negated,
  12898. * i.e. multiplied by -1.
  12899. */
  12900. P.negated = P.neg = function () {
  12901. var x = new BigNumber(this);
  12902. x.s = -x.s || null;
  12903. return x;
  12904. };
  12905. /*
  12906. * n + 0 = n
  12907. * n + N = N
  12908. * n + I = I
  12909. * 0 + n = n
  12910. * 0 + 0 = 0
  12911. * 0 + N = N
  12912. * 0 + I = I
  12913. * N + n = N
  12914. * N + 0 = N
  12915. * N + N = N
  12916. * N + I = N
  12917. * I + n = I
  12918. * I + 0 = I
  12919. * I + N = N
  12920. * I + I = I
  12921. *
  12922. * Return a new BigNumber whose value is the value of this BigNumber plus the value of
  12923. * BigNumber(y, b).
  12924. */
  12925. P.plus = P.add = function ( y, b ) {
  12926. var t,
  12927. x = this,
  12928. a = x.s;
  12929. id = 12;
  12930. y = new BigNumber( y, b );
  12931. b = y.s;
  12932. // Either NaN?
  12933. if ( !a || !b ) return new BigNumber(NaN);
  12934. // Signs differ?
  12935. if ( a != b ) {
  12936. y.s = -b;
  12937. return x.minus(y);
  12938. }
  12939. var xe = x.e / LOG_BASE,
  12940. ye = y.e / LOG_BASE,
  12941. xc = x.c,
  12942. yc = y.c;
  12943. if ( !xe || !ye ) {
  12944. // Return ±Infinity if either ±Infinity.
  12945. if ( !xc || !yc ) return new BigNumber( a / 0 );
  12946. // Either zero?
  12947. // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
  12948. if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 );
  12949. }
  12950. xe = bitFloor(xe);
  12951. ye = bitFloor(ye);
  12952. xc = xc.slice();
  12953. // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.
  12954. if ( a = xe - ye ) {
  12955. if ( a > 0 ) {
  12956. ye = xe;
  12957. t = yc;
  12958. } else {
  12959. a = -a;
  12960. t = xc;
  12961. }
  12962. t.reverse();
  12963. for ( ; a--; t.push(0) );
  12964. t.reverse();
  12965. }
  12966. a = xc.length;
  12967. b = yc.length;
  12968. // Point xc to the longer array, and b to the shorter length.
  12969. if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a;
  12970. // Only start adding at yc.length - 1 as the further digits of xc can be ignored.
  12971. for ( a = 0; b; ) {
  12972. a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0;
  12973. xc[b] %= BASE;
  12974. }
  12975. if (a) {
  12976. xc.unshift(a);
  12977. ++ye;
  12978. }
  12979. // No need to check for zero, as +x + +y != 0 && -x + -y != 0
  12980. // ye = MAX_EXP + 1 possible
  12981. return normalise( y, xc, ye );
  12982. };
  12983. /*
  12984. * Return the number of significant digits of the value of this BigNumber.
  12985. *
  12986. * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
  12987. */
  12988. P.precision = P.sd = function (z) {
  12989. var n, v,
  12990. x = this,
  12991. c = x.c;
  12992. // 'precision() argument not a boolean or binary digit: {z}'
  12993. if ( z != null && z !== !!z && z !== 1 && z !== 0 ) {
  12994. if (ERRORS) raise( 13, 'argument' + notBool, z );
  12995. if ( z != !!z ) z = null;
  12996. }
  12997. if ( !c ) return null;
  12998. v = c.length - 1;
  12999. n = v * LOG_BASE + 1;
  13000. if ( v = c[v] ) {
  13001. // Subtract the number of trailing zeros of the last element.
  13002. for ( ; v % 10 == 0; v /= 10, n-- );
  13003. // Add the number of digits of the first element.
  13004. for ( v = c[0]; v >= 10; v /= 10, n++ );
  13005. }
  13006. if ( z && x.e + 1 > n ) n = x.e + 1;
  13007. return n;
  13008. };
  13009. /*
  13010. * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
  13011. * dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if
  13012. * omitted.
  13013. *
  13014. * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
  13015. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  13016. *
  13017. * 'round() decimal places out of range: {dp}'
  13018. * 'round() decimal places not an integer: {dp}'
  13019. * 'round() rounding mode not an integer: {rm}'
  13020. * 'round() rounding mode out of range: {rm}'
  13021. */
  13022. P.round = function ( dp, rm ) {
  13023. var n = new BigNumber(this);
  13024. if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) {
  13025. round( n, ~~dp + this.e + 1, rm == null ||
  13026. !isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 );
  13027. }
  13028. return n;
  13029. };
  13030. /*
  13031. * Return a new BigNumber whose value is the value of this BigNumber shifted by k places
  13032. * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.
  13033. *
  13034. * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
  13035. *
  13036. * If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity
  13037. * otherwise.
  13038. *
  13039. * 'shift() argument not an integer: {k}'
  13040. * 'shift() argument out of range: {k}'
  13041. */
  13042. P.shift = function (k) {
  13043. var n = this;
  13044. return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' )
  13045. // k < 1e+21, or truncate(k) will produce exponential notation.
  13046. ? n.times( '1e' + truncate(k) )
  13047. : new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER )
  13048. ? n.s * ( k < 0 ? 0 : 1 / 0 )
  13049. : n );
  13050. };
  13051. /*
  13052. * sqrt(-n) = N
  13053. * sqrt( N) = N
  13054. * sqrt(-I) = N
  13055. * sqrt( I) = I
  13056. * sqrt( 0) = 0
  13057. * sqrt(-0) = -0
  13058. *
  13059. * Return a new BigNumber whose value is the square root of the value of this BigNumber,
  13060. * rounded according to DECIMAL_PLACES and ROUNDING_MODE.
  13061. */
  13062. P.squareRoot = P.sqrt = function () {
  13063. var m, n, r, rep, t,
  13064. x = this,
  13065. c = x.c,
  13066. s = x.s,
  13067. e = x.e,
  13068. dp = DECIMAL_PLACES + 4,
  13069. half = new BigNumber('0.5');
  13070. // Negative/NaN/Infinity/zero?
  13071. if ( s !== 1 || !c || !c[0] ) {
  13072. return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 );
  13073. }
  13074. // Initial estimate.
  13075. s = Math.sqrt( +x );
  13076. // Math.sqrt underflow/overflow?
  13077. // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
  13078. if ( s == 0 || s == 1 / 0 ) {
  13079. n = coeffToString(c);
  13080. if ( ( n.length + e ) % 2 == 0 ) n += '0';
  13081. s = Math.sqrt(n);
  13082. e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 );
  13083. if ( s == 1 / 0 ) {
  13084. n = '1e' + e;
  13085. } else {
  13086. n = s.toExponential();
  13087. n = n.slice( 0, n.indexOf('e') + 1 ) + e;
  13088. }
  13089. r = new BigNumber(n);
  13090. } else {
  13091. r = new BigNumber( s + '' );
  13092. }
  13093. // Check for zero.
  13094. // r could be zero if MIN_EXP is changed after the this value was created.
  13095. // This would cause a division by zero (x/t) and hence Infinity below, which would cause
  13096. // coeffToString to throw.
  13097. if ( r.c[0] ) {
  13098. e = r.e;
  13099. s = e + dp;
  13100. if ( s < 3 ) s = 0;
  13101. // Newton-Raphson iteration.
  13102. for ( ; ; ) {
  13103. t = r;
  13104. r = half.times( t.plus( div( x, t, dp, 1 ) ) );
  13105. if ( coeffToString( t.c ).slice( 0, s ) === ( n =
  13106. coeffToString( r.c ) ).slice( 0, s ) ) {
  13107. // The exponent of r may here be one less than the final result exponent,
  13108. // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits
  13109. // are indexed correctly.
  13110. if ( r.e < e ) --s;
  13111. n = n.slice( s - 3, s + 1 );
  13112. // The 4th rounding digit may be in error by -1 so if the 4 rounding digits
  13113. // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the
  13114. // iteration.
  13115. if ( n == '9999' || !rep && n == '4999' ) {
  13116. // On the first iteration only, check to see if rounding up gives the
  13117. // exact result as the nines may infinitely repeat.
  13118. if ( !rep ) {
  13119. round( t, t.e + DECIMAL_PLACES + 2, 0 );
  13120. if ( t.times(t).eq(x) ) {
  13121. r = t;
  13122. break;
  13123. }
  13124. }
  13125. dp += 4;
  13126. s += 4;
  13127. rep = 1;
  13128. } else {
  13129. // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact
  13130. // result. If not, then there are further digits and m will be truthy.
  13131. if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) {
  13132. // Truncate to the first rounding digit.
  13133. round( r, r.e + DECIMAL_PLACES + 2, 1 );
  13134. m = !r.times(r).eq(x);
  13135. }
  13136. break;
  13137. }
  13138. }
  13139. }
  13140. }
  13141. return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m );
  13142. };
  13143. /*
  13144. * n * 0 = 0
  13145. * n * N = N
  13146. * n * I = I
  13147. * 0 * n = 0
  13148. * 0 * 0 = 0
  13149. * 0 * N = N
  13150. * 0 * I = N
  13151. * N * n = N
  13152. * N * 0 = N
  13153. * N * N = N
  13154. * N * I = N
  13155. * I * n = I
  13156. * I * 0 = N
  13157. * I * N = N
  13158. * I * I = I
  13159. *
  13160. * Return a new BigNumber whose value is the value of this BigNumber times the value of
  13161. * BigNumber(y, b).
  13162. */
  13163. P.times = P.mul = function ( y, b ) {
  13164. var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,
  13165. base, sqrtBase,
  13166. x = this,
  13167. xc = x.c,
  13168. yc = ( id = 17, y = new BigNumber( y, b ) ).c;
  13169. // Either NaN, ±Infinity or ±0?
  13170. if ( !xc || !yc || !xc[0] || !yc[0] ) {
  13171. // Return NaN if either is NaN, or one is 0 and the other is Infinity.
  13172. if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) {
  13173. y.c = y.e = y.s = null;
  13174. } else {
  13175. y.s *= x.s;
  13176. // Return ±Infinity if either is ±Infinity.
  13177. if ( !xc || !yc ) {
  13178. y.c = y.e = null;
  13179. // Return ±0 if either is ±0.
  13180. } else {
  13181. y.c = [0];
  13182. y.e = 0;
  13183. }
  13184. }
  13185. return y;
  13186. }
  13187. e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE );
  13188. y.s *= x.s;
  13189. xcL = xc.length;
  13190. ycL = yc.length;
  13191. // Ensure xc points to longer array and xcL to its length.
  13192. if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i;
  13193. // Initialise the result array with zeros.
  13194. for ( i = xcL + ycL, zc = []; i--; zc.push(0) );
  13195. base = BASE;
  13196. sqrtBase = SQRT_BASE;
  13197. for ( i = ycL; --i >= 0; ) {
  13198. c = 0;
  13199. ylo = yc[i] % sqrtBase;
  13200. yhi = yc[i] / sqrtBase | 0;
  13201. for ( k = xcL, j = i + k; j > i; ) {
  13202. xlo = xc[--k] % sqrtBase;
  13203. xhi = xc[k] / sqrtBase | 0;
  13204. m = yhi * xlo + xhi * ylo;
  13205. xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c;
  13206. c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi;
  13207. zc[j--] = xlo % base;
  13208. }
  13209. zc[j] = c;
  13210. }
  13211. if (c) {
  13212. ++e;
  13213. } else {
  13214. zc.shift();
  13215. }
  13216. return normalise( y, zc, e );
  13217. };
  13218. /*
  13219. * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
  13220. * sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted.
  13221. *
  13222. * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
  13223. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  13224. *
  13225. * 'toDigits() precision out of range: {sd}'
  13226. * 'toDigits() precision not an integer: {sd}'
  13227. * 'toDigits() rounding mode not an integer: {rm}'
  13228. * 'toDigits() rounding mode out of range: {rm}'
  13229. */
  13230. P.toDigits = function ( sd, rm ) {
  13231. var n = new BigNumber(this);
  13232. sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0;
  13233. rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0;
  13234. return sd ? round( n, sd, rm ) : n;
  13235. };
  13236. /*
  13237. * Return a string representing the value of this BigNumber in exponential notation and
  13238. * rounded using ROUNDING_MODE to dp fixed decimal places.
  13239. *
  13240. * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
  13241. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  13242. *
  13243. * 'toExponential() decimal places not an integer: {dp}'
  13244. * 'toExponential() decimal places out of range: {dp}'
  13245. * 'toExponential() rounding mode not an integer: {rm}'
  13246. * 'toExponential() rounding mode out of range: {rm}'
  13247. */
  13248. P.toExponential = function ( dp, rm ) {
  13249. return format( this,
  13250. dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 );
  13251. };
  13252. /*
  13253. * Return a string representing the value of this BigNumber in fixed-point notation rounding
  13254. * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.
  13255. *
  13256. * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',
  13257. * but e.g. (-0.00001).toFixed(0) is '-0'.
  13258. *
  13259. * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
  13260. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  13261. *
  13262. * 'toFixed() decimal places not an integer: {dp}'
  13263. * 'toFixed() decimal places out of range: {dp}'
  13264. * 'toFixed() rounding mode not an integer: {rm}'
  13265. * 'toFixed() rounding mode out of range: {rm}'
  13266. */
  13267. P.toFixed = function ( dp, rm ) {
  13268. return format( this, dp != null && isValidInt( dp, 0, MAX, 20 )
  13269. ? ~~dp + this.e + 1 : null, rm, 20 );
  13270. };
  13271. /*
  13272. * Return a string representing the value of this BigNumber in fixed-point notation rounded
  13273. * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties
  13274. * of the FORMAT object (see BigNumber.config).
  13275. *
  13276. * FORMAT = {
  13277. * decimalSeparator : '.',
  13278. * groupSeparator : ',',
  13279. * groupSize : 3,
  13280. * secondaryGroupSize : 0,
  13281. * fractionGroupSeparator : '\xA0', // non-breaking space
  13282. * fractionGroupSize : 0
  13283. * };
  13284. *
  13285. * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
  13286. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  13287. *
  13288. * 'toFormat() decimal places not an integer: {dp}'
  13289. * 'toFormat() decimal places out of range: {dp}'
  13290. * 'toFormat() rounding mode not an integer: {rm}'
  13291. * 'toFormat() rounding mode out of range: {rm}'
  13292. */
  13293. P.toFormat = function ( dp, rm ) {
  13294. var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 )
  13295. ? ~~dp + this.e + 1 : null, rm, 21 );
  13296. if ( this.c ) {
  13297. var i,
  13298. arr = str.split('.'),
  13299. g1 = +FORMAT.groupSize,
  13300. g2 = +FORMAT.secondaryGroupSize,
  13301. groupSeparator = FORMAT.groupSeparator,
  13302. intPart = arr[0],
  13303. fractionPart = arr[1],
  13304. isNeg = this.s < 0,
  13305. intDigits = isNeg ? intPart.slice(1) : intPart,
  13306. len = intDigits.length;
  13307. if (g2) i = g1, g1 = g2, g2 = i, len -= i;
  13308. if ( g1 > 0 && len > 0 ) {
  13309. i = len % g1 || g1;
  13310. intPart = intDigits.substr( 0, i );
  13311. for ( ; i < len; i += g1 ) {
  13312. intPart += groupSeparator + intDigits.substr( i, g1 );
  13313. }
  13314. if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i);
  13315. if (isNeg) intPart = '-' + intPart;
  13316. }
  13317. str = fractionPart
  13318. ? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize )
  13319. ? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ),
  13320. '$&' + FORMAT.fractionGroupSeparator )
  13321. : fractionPart )
  13322. : intPart;
  13323. }
  13324. return str;
  13325. };
  13326. /*
  13327. * Return a string array representing the value of this BigNumber as a simple fraction with
  13328. * an integer numerator and an integer denominator. The denominator will be a positive
  13329. * non-zero value less than or equal to the specified maximum denominator. If a maximum
  13330. * denominator is not specified, the denominator will be the lowest value necessary to
  13331. * represent the number exactly.
  13332. *
  13333. * [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator.
  13334. *
  13335. * 'toFraction() max denominator not an integer: {md}'
  13336. * 'toFraction() max denominator out of range: {md}'
  13337. */
  13338. P.toFraction = function (md) {
  13339. var arr, d0, d2, e, exp, n, n0, q, s,
  13340. k = ERRORS,
  13341. x = this,
  13342. xc = x.c,
  13343. d = new BigNumber(ONE),
  13344. n1 = d0 = new BigNumber(ONE),
  13345. d1 = n0 = new BigNumber(ONE);
  13346. if ( md != null ) {
  13347. ERRORS = false;
  13348. n = new BigNumber(md);
  13349. ERRORS = k;
  13350. if ( !( k = n.isInt() ) || n.lt(ONE) ) {
  13351. if (ERRORS) {
  13352. raise( 22,
  13353. 'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md );
  13354. }
  13355. // ERRORS is false:
  13356. // If md is a finite non-integer >= 1, round it to an integer and use it.
  13357. md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null;
  13358. }
  13359. }
  13360. if ( !xc ) return x.toString();
  13361. s = coeffToString(xc);
  13362. // Determine initial denominator.
  13363. // d is a power of 10 and the minimum max denominator that specifies the value exactly.
  13364. e = d.e = s.length - x.e - 1;
  13365. d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ];
  13366. md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n;
  13367. exp = MAX_EXP;
  13368. MAX_EXP = 1 / 0;
  13369. n = new BigNumber(s);
  13370. // n0 = d1 = 0
  13371. n0.c[0] = 0;
  13372. for ( ; ; ) {
  13373. q = div( n, d, 0, 1 );
  13374. d2 = d0.plus( q.times(d1) );
  13375. if ( d2.cmp(md) == 1 ) break;
  13376. d0 = d1;
  13377. d1 = d2;
  13378. n1 = n0.plus( q.times( d2 = n1 ) );
  13379. n0 = d2;
  13380. d = n.minus( q.times( d2 = d ) );
  13381. n = d2;
  13382. }
  13383. d2 = div( md.minus(d0), d1, 0, 1 );
  13384. n0 = n0.plus( d2.times(n1) );
  13385. d0 = d0.plus( d2.times(d1) );
  13386. n0.s = n1.s = x.s;
  13387. e *= 2;
  13388. // Determine which fraction is closer to x, n0/d0 or n1/d1
  13389. arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp(
  13390. div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1
  13391. ? [ n1.toString(), d1.toString() ]
  13392. : [ n0.toString(), d0.toString() ];
  13393. MAX_EXP = exp;
  13394. return arr;
  13395. };
  13396. /*
  13397. * Return the value of this BigNumber converted to a number primitive.
  13398. */
  13399. P.toNumber = function () {
  13400. var x = this;
  13401. // Ensure zero has correct sign.
  13402. return +x || ( x.s ? x.s * 0 : NaN );
  13403. };
  13404. /*
  13405. * Return a BigNumber whose value is the value of this BigNumber raised to the power n.
  13406. * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.
  13407. * If POW_PRECISION is not 0, round to POW_PRECISION using ROUNDING_MODE.
  13408. *
  13409. * n {number} Integer, -9007199254740992 to 9007199254740992 inclusive.
  13410. * (Performs 54 loop iterations for n of 9007199254740992.)
  13411. *
  13412. * 'pow() exponent not an integer: {n}'
  13413. * 'pow() exponent out of range: {n}'
  13414. */
  13415. P.toPower = P.pow = function (n) {
  13416. var k, y,
  13417. i = mathfloor( n < 0 ? -n : +n ),
  13418. x = this;
  13419. // Pass ±Infinity to Math.pow if exponent is out of range.
  13420. if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) &&
  13421. ( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) ||
  13422. parseFloat(n) != n && !( n = NaN ) ) ) {
  13423. return new BigNumber( Math.pow( +x, n ) );
  13424. }
  13425. // Truncating each coefficient array to a length of k after each multiplication equates
  13426. // to truncating significant digits to POW_PRECISION + [28, 41], i.e. there will be a
  13427. // minimum of 28 guard digits retained. (Using + 1.5 would give [9, 21] guard digits.)
  13428. k = POW_PRECISION ? mathceil( POW_PRECISION / LOG_BASE + 2 ) : 0;
  13429. y = new BigNumber(ONE);
  13430. for ( ; ; ) {
  13431. if ( i % 2 ) {
  13432. y = y.times(x);
  13433. if ( !y.c ) break;
  13434. if ( k && y.c.length > k ) y.c.length = k;
  13435. }
  13436. i = mathfloor( i / 2 );
  13437. if ( !i ) break;
  13438. x = x.times(x);
  13439. if ( k && x.c && x.c.length > k ) x.c.length = k;
  13440. }
  13441. if ( n < 0 ) y = ONE.div(y);
  13442. return k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y;
  13443. };
  13444. /*
  13445. * Return a string representing the value of this BigNumber rounded to sd significant digits
  13446. * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits
  13447. * necessary to represent the integer part of the value in fixed-point notation, then use
  13448. * exponential notation.
  13449. *
  13450. * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
  13451. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  13452. *
  13453. * 'toPrecision() precision not an integer: {sd}'
  13454. * 'toPrecision() precision out of range: {sd}'
  13455. * 'toPrecision() rounding mode not an integer: {rm}'
  13456. * 'toPrecision() rounding mode out of range: {rm}'
  13457. */
  13458. P.toPrecision = function ( sd, rm ) {
  13459. return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' )
  13460. ? sd | 0 : null, rm, 24 );
  13461. };
  13462. /*
  13463. * Return a string representing the value of this BigNumber in base b, or base 10 if b is
  13464. * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and
  13465. * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent
  13466. * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than
  13467. * TO_EXP_NEG, return exponential notation.
  13468. *
  13469. * [b] {number} Integer, 2 to 64 inclusive.
  13470. *
  13471. * 'toString() base not an integer: {b}'
  13472. * 'toString() base out of range: {b}'
  13473. */
  13474. P.toString = function (b) {
  13475. var str,
  13476. n = this,
  13477. s = n.s,
  13478. e = n.e;
  13479. // Infinity or NaN?
  13480. if ( e === null ) {
  13481. if (s) {
  13482. str = 'Infinity';
  13483. if ( s < 0 ) str = '-' + str;
  13484. } else {
  13485. str = 'NaN';
  13486. }
  13487. } else {
  13488. str = coeffToString( n.c );
  13489. if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) {
  13490. str = e <= TO_EXP_NEG || e >= TO_EXP_POS
  13491. ? toExponential( str, e )
  13492. : toFixedPoint( str, e );
  13493. } else {
  13494. str = convertBase( toFixedPoint( str, e ), b | 0, 10, s );
  13495. }
  13496. if ( s < 0 && n.c[0] ) str = '-' + str;
  13497. }
  13498. return str;
  13499. };
  13500. /*
  13501. * Return a new BigNumber whose value is the value of this BigNumber truncated to a whole
  13502. * number.
  13503. */
  13504. P.truncated = P.trunc = function () {
  13505. return round( new BigNumber(this), this.e + 1, 1 );
  13506. };
  13507. /*
  13508. * Return as toString, but do not accept a base argument.
  13509. */
  13510. P.valueOf = P.toJSON = function () {
  13511. return this.toString();
  13512. };
  13513. // Aliases for BigDecimal methods.
  13514. //P.add = P.plus; // P.add included above
  13515. //P.subtract = P.minus; // P.sub included above
  13516. //P.multiply = P.times; // P.mul included above
  13517. //P.divide = P.div;
  13518. //P.remainder = P.mod;
  13519. //P.compareTo = P.cmp;
  13520. //P.negate = P.neg;
  13521. if ( configObj != null ) BigNumber.config(configObj);
  13522. return BigNumber;
  13523. }
  13524. // PRIVATE HELPER FUNCTIONS
  13525. function bitFloor(n) {
  13526. var i = n | 0;
  13527. return n > 0 || n === i ? i : i - 1;
  13528. }
  13529. // Return a coefficient array as a string of base 10 digits.
  13530. function coeffToString(a) {
  13531. var s, z,
  13532. i = 1,
  13533. j = a.length,
  13534. r = a[0] + '';
  13535. for ( ; i < j; ) {
  13536. s = a[i++] + '';
  13537. z = LOG_BASE - s.length;
  13538. for ( ; z--; s = '0' + s );
  13539. r += s;
  13540. }
  13541. // Determine trailing zeros.
  13542. for ( j = r.length; r.charCodeAt(--j) === 48; );
  13543. return r.slice( 0, j + 1 || 1 );
  13544. }
  13545. // Compare the value of BigNumbers x and y.
  13546. function compare( x, y ) {
  13547. var a, b,
  13548. xc = x.c,
  13549. yc = y.c,
  13550. i = x.s,
  13551. j = y.s,
  13552. k = x.e,
  13553. l = y.e;
  13554. // Either NaN?
  13555. if ( !i || !j ) return null;
  13556. a = xc && !xc[0];
  13557. b = yc && !yc[0];
  13558. // Either zero?
  13559. if ( a || b ) return a ? b ? 0 : -j : i;
  13560. // Signs differ?
  13561. if ( i != j ) return i;
  13562. a = i < 0;
  13563. b = k == l;
  13564. // Either Infinity?
  13565. if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1;
  13566. // Compare exponents.
  13567. if ( !b ) return k > l ^ a ? 1 : -1;
  13568. j = ( k = xc.length ) < ( l = yc.length ) ? k : l;
  13569. // Compare digit by digit.
  13570. for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1;
  13571. // Compare lengths.
  13572. return k == l ? 0 : k > l ^ a ? 1 : -1;
  13573. }
  13574. /*
  13575. * Return true if n is a valid number in range, otherwise false.
  13576. * Use for argument validation when ERRORS is false.
  13577. * Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10.
  13578. */
  13579. function intValidatorNoErrors( n, min, max ) {
  13580. return ( n = truncate(n) ) >= min && n <= max;
  13581. }
  13582. function isArray(obj) {
  13583. return Object.prototype.toString.call(obj) == '[object Array]';
  13584. }
  13585. /*
  13586. * Convert string of baseIn to an array of numbers of baseOut.
  13587. * Eg. convertBase('255', 10, 16) returns [15, 15].
  13588. * Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
  13589. */
  13590. function toBaseOut( str, baseIn, baseOut ) {
  13591. var j,
  13592. arr = [0],
  13593. arrL,
  13594. i = 0,
  13595. len = str.length;
  13596. for ( ; i < len; ) {
  13597. for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn );
  13598. arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) );
  13599. for ( ; j < arr.length; j++ ) {
  13600. if ( arr[j] > baseOut - 1 ) {
  13601. if ( arr[j + 1] == null ) arr[j + 1] = 0;
  13602. arr[j + 1] += arr[j] / baseOut | 0;
  13603. arr[j] %= baseOut;
  13604. }
  13605. }
  13606. }
  13607. return arr.reverse();
  13608. }
  13609. function toExponential( str, e ) {
  13610. return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) +
  13611. ( e < 0 ? 'e' : 'e+' ) + e;
  13612. }
  13613. function toFixedPoint( str, e ) {
  13614. var len, z;
  13615. // Negative exponent?
  13616. if ( e < 0 ) {
  13617. // Prepend zeros.
  13618. for ( z = '0.'; ++e; z += '0' );
  13619. str = z + str;
  13620. // Positive exponent
  13621. } else {
  13622. len = str.length;
  13623. // Append zeros.
  13624. if ( ++e > len ) {
  13625. for ( z = '0', e -= len; --e; z += '0' );
  13626. str += z;
  13627. } else if ( e < len ) {
  13628. str = str.slice( 0, e ) + '.' + str.slice(e);
  13629. }
  13630. }
  13631. return str;
  13632. }
  13633. function truncate(n) {
  13634. n = parseFloat(n);
  13635. return n < 0 ? mathceil(n) : mathfloor(n);
  13636. }
  13637. // EXPORT
  13638. BigNumber = another();
  13639. // AMD.
  13640. if ( typeof define == 'function' && define.amd ) {
  13641. define( function () { return BigNumber; } );
  13642. // Node and other environments that support module.exports.
  13643. } else if ( typeof module != 'undefined' && module.exports ) {
  13644. module.exports = BigNumber;
  13645. if ( !crypto ) try { crypto = require('crypto'); } catch (e) {}
  13646. // Browser.
  13647. } else {
  13648. global.BigNumber = BigNumber;
  13649. }
  13650. })(this);
  13651. },{"crypto":49}],"web3":[function(require,module,exports){
  13652. var Web3 = require('./lib/web3');
  13653. // dont override global variable
  13654. if (typeof window !== 'undefined' && typeof window.Web3 === 'undefined') {
  13655. window.Web3 = Web3;
  13656. }
  13657. module.exports = Web3;
  13658. },{"./lib/web3":22}]},{},["web3"])
  13659. //# sourceMappingURL=web3.js.map
  13660. `