basen.js 968 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.boot = f()}})(function(){var define,module,exports;return (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){
  2. var asn1 = exports;
  3. asn1.bignum = require('bn.js');
  4. asn1.define = require('./asn1/api').define;
  5. asn1.base = require('./asn1/base');
  6. asn1.constants = require('./asn1/constants');
  7. asn1.decoders = require('./asn1/decoders');
  8. asn1.encoders = require('./asn1/encoders');
  9. },{"./asn1/api":2,"./asn1/base":4,"./asn1/constants":8,"./asn1/decoders":10,"./asn1/encoders":13,"bn.js":17}],2:[function(require,module,exports){
  10. var asn1 = require('../asn1');
  11. var inherits = require('inherits');
  12. var api = exports;
  13. api.define = function define(name, body) {
  14. return new Entity(name, body);
  15. };
  16. function Entity(name, body) {
  17. this.name = name;
  18. this.body = body;
  19. this.decoders = {};
  20. this.encoders = {};
  21. };
  22. Entity.prototype._createNamed = function createNamed(base) {
  23. var named;
  24. try {
  25. named = require('vm').runInThisContext(
  26. '(function ' + this.name + '(entity) {\n' +
  27. ' this._initNamed(entity);\n' +
  28. '})'
  29. );
  30. } catch (e) {
  31. named = function (entity) {
  32. this._initNamed(entity);
  33. };
  34. }
  35. inherits(named, base);
  36. named.prototype._initNamed = function initnamed(entity) {
  37. base.call(this, entity);
  38. };
  39. return new named(this);
  40. };
  41. Entity.prototype._getDecoder = function _getDecoder(enc) {
  42. enc = enc || 'der';
  43. // Lazily create decoder
  44. if (!this.decoders.hasOwnProperty(enc))
  45. this.decoders[enc] = this._createNamed(asn1.decoders[enc]);
  46. return this.decoders[enc];
  47. };
  48. Entity.prototype.decode = function decode(data, enc, options) {
  49. return this._getDecoder(enc).decode(data, options);
  50. };
  51. Entity.prototype._getEncoder = function _getEncoder(enc) {
  52. enc = enc || 'der';
  53. // Lazily create encoder
  54. if (!this.encoders.hasOwnProperty(enc))
  55. this.encoders[enc] = this._createNamed(asn1.encoders[enc]);
  56. return this.encoders[enc];
  57. };
  58. Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) {
  59. return this._getEncoder(enc).encode(data, reporter);
  60. };
  61. },{"../asn1":1,"inherits":104,"vm":172}],3:[function(require,module,exports){
  62. var inherits = require('inherits');
  63. var Reporter = require('../base').Reporter;
  64. var Buffer = require('buffer').Buffer;
  65. function DecoderBuffer(base, options) {
  66. Reporter.call(this, options);
  67. if (!Buffer.isBuffer(base)) {
  68. this.error('Input not Buffer');
  69. return;
  70. }
  71. this.base = base;
  72. this.offset = 0;
  73. this.length = base.length;
  74. }
  75. inherits(DecoderBuffer, Reporter);
  76. exports.DecoderBuffer = DecoderBuffer;
  77. DecoderBuffer.prototype.save = function save() {
  78. return { offset: this.offset, reporter: Reporter.prototype.save.call(this) };
  79. };
  80. DecoderBuffer.prototype.restore = function restore(save) {
  81. // Return skipped data
  82. var res = new DecoderBuffer(this.base);
  83. res.offset = save.offset;
  84. res.length = this.offset;
  85. this.offset = save.offset;
  86. Reporter.prototype.restore.call(this, save.reporter);
  87. return res;
  88. };
  89. DecoderBuffer.prototype.isEmpty = function isEmpty() {
  90. return this.offset === this.length;
  91. };
  92. DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) {
  93. if (this.offset + 1 <= this.length)
  94. return this.base.readUInt8(this.offset++, true);
  95. else
  96. return this.error(fail || 'DecoderBuffer overrun');
  97. }
  98. DecoderBuffer.prototype.skip = function skip(bytes, fail) {
  99. if (!(this.offset + bytes <= this.length))
  100. return this.error(fail || 'DecoderBuffer overrun');
  101. var res = new DecoderBuffer(this.base);
  102. // Share reporter state
  103. res._reporterState = this._reporterState;
  104. res.offset = this.offset;
  105. res.length = this.offset + bytes;
  106. this.offset += bytes;
  107. return res;
  108. }
  109. DecoderBuffer.prototype.raw = function raw(save) {
  110. return this.base.slice(save ? save.offset : this.offset, this.length);
  111. }
  112. function EncoderBuffer(value, reporter) {
  113. if (Array.isArray(value)) {
  114. this.length = 0;
  115. this.value = value.map(function(item) {
  116. if (!(item instanceof EncoderBuffer))
  117. item = new EncoderBuffer(item, reporter);
  118. this.length += item.length;
  119. return item;
  120. }, this);
  121. } else if (typeof value === 'number') {
  122. if (!(0 <= value && value <= 0xff))
  123. return reporter.error('non-byte EncoderBuffer value');
  124. this.value = value;
  125. this.length = 1;
  126. } else if (typeof value === 'string') {
  127. this.value = value;
  128. this.length = Buffer.byteLength(value);
  129. } else if (Buffer.isBuffer(value)) {
  130. this.value = value;
  131. this.length = value.length;
  132. } else {
  133. return reporter.error('Unsupported type: ' + typeof value);
  134. }
  135. }
  136. exports.EncoderBuffer = EncoderBuffer;
  137. EncoderBuffer.prototype.join = function join(out, offset) {
  138. if (!out)
  139. out = new Buffer(this.length);
  140. if (!offset)
  141. offset = 0;
  142. if (this.length === 0)
  143. return out;
  144. if (Array.isArray(this.value)) {
  145. this.value.forEach(function(item) {
  146. item.join(out, offset);
  147. offset += item.length;
  148. });
  149. } else {
  150. if (typeof this.value === 'number')
  151. out[offset] = this.value;
  152. else if (typeof this.value === 'string')
  153. out.write(this.value, offset);
  154. else if (Buffer.isBuffer(this.value))
  155. this.value.copy(out, offset);
  156. offset += this.length;
  157. }
  158. return out;
  159. };
  160. },{"../base":4,"buffer":50,"inherits":104}],4:[function(require,module,exports){
  161. var base = exports;
  162. base.Reporter = require('./reporter').Reporter;
  163. base.DecoderBuffer = require('./buffer').DecoderBuffer;
  164. base.EncoderBuffer = require('./buffer').EncoderBuffer;
  165. base.Node = require('./node');
  166. },{"./buffer":3,"./node":5,"./reporter":6}],5:[function(require,module,exports){
  167. var Reporter = require('../base').Reporter;
  168. var EncoderBuffer = require('../base').EncoderBuffer;
  169. var DecoderBuffer = require('../base').DecoderBuffer;
  170. var assert = require('minimalistic-assert');
  171. // Supported tags
  172. var tags = [
  173. 'seq', 'seqof', 'set', 'setof', 'objid', 'bool',
  174. 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc',
  175. 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str',
  176. 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr'
  177. ];
  178. // Public methods list
  179. var methods = [
  180. 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice',
  181. 'any', 'contains'
  182. ].concat(tags);
  183. // Overrided methods list
  184. var overrided = [
  185. '_peekTag', '_decodeTag', '_use',
  186. '_decodeStr', '_decodeObjid', '_decodeTime',
  187. '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList',
  188. '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime',
  189. '_encodeNull', '_encodeInt', '_encodeBool'
  190. ];
  191. function Node(enc, parent) {
  192. var state = {};
  193. this._baseState = state;
  194. state.enc = enc;
  195. state.parent = parent || null;
  196. state.children = null;
  197. // State
  198. state.tag = null;
  199. state.args = null;
  200. state.reverseArgs = null;
  201. state.choice = null;
  202. state.optional = false;
  203. state.any = false;
  204. state.obj = false;
  205. state.use = null;
  206. state.useDecoder = null;
  207. state.key = null;
  208. state['default'] = null;
  209. state.explicit = null;
  210. state.implicit = null;
  211. state.contains = null;
  212. // Should create new instance on each method
  213. if (!state.parent) {
  214. state.children = [];
  215. this._wrap();
  216. }
  217. }
  218. module.exports = Node;
  219. var stateProps = [
  220. 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice',
  221. 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit',
  222. 'implicit', 'contains'
  223. ];
  224. Node.prototype.clone = function clone() {
  225. var state = this._baseState;
  226. var cstate = {};
  227. stateProps.forEach(function(prop) {
  228. cstate[prop] = state[prop];
  229. });
  230. var res = new this.constructor(cstate.parent);
  231. res._baseState = cstate;
  232. return res;
  233. };
  234. Node.prototype._wrap = function wrap() {
  235. var state = this._baseState;
  236. methods.forEach(function(method) {
  237. this[method] = function _wrappedMethod() {
  238. var clone = new this.constructor(this);
  239. state.children.push(clone);
  240. return clone[method].apply(clone, arguments);
  241. };
  242. }, this);
  243. };
  244. Node.prototype._init = function init(body) {
  245. var state = this._baseState;
  246. assert(state.parent === null);
  247. body.call(this);
  248. // Filter children
  249. state.children = state.children.filter(function(child) {
  250. return child._baseState.parent === this;
  251. }, this);
  252. assert.equal(state.children.length, 1, 'Root node can have only one child');
  253. };
  254. Node.prototype._useArgs = function useArgs(args) {
  255. var state = this._baseState;
  256. // Filter children and args
  257. var children = args.filter(function(arg) {
  258. return arg instanceof this.constructor;
  259. }, this);
  260. args = args.filter(function(arg) {
  261. return !(arg instanceof this.constructor);
  262. }, this);
  263. if (children.length !== 0) {
  264. assert(state.children === null);
  265. state.children = children;
  266. // Replace parent to maintain backward link
  267. children.forEach(function(child) {
  268. child._baseState.parent = this;
  269. }, this);
  270. }
  271. if (args.length !== 0) {
  272. assert(state.args === null);
  273. state.args = args;
  274. state.reverseArgs = args.map(function(arg) {
  275. if (typeof arg !== 'object' || arg.constructor !== Object)
  276. return arg;
  277. var res = {};
  278. Object.keys(arg).forEach(function(key) {
  279. if (key == (key | 0))
  280. key |= 0;
  281. var value = arg[key];
  282. res[value] = key;
  283. });
  284. return res;
  285. });
  286. }
  287. };
  288. //
  289. // Overrided methods
  290. //
  291. overrided.forEach(function(method) {
  292. Node.prototype[method] = function _overrided() {
  293. var state = this._baseState;
  294. throw new Error(method + ' not implemented for encoding: ' + state.enc);
  295. };
  296. });
  297. //
  298. // Public methods
  299. //
  300. tags.forEach(function(tag) {
  301. Node.prototype[tag] = function _tagMethod() {
  302. var state = this._baseState;
  303. var args = Array.prototype.slice.call(arguments);
  304. assert(state.tag === null);
  305. state.tag = tag;
  306. this._useArgs(args);
  307. return this;
  308. };
  309. });
  310. Node.prototype.use = function use(item) {
  311. assert(item);
  312. var state = this._baseState;
  313. assert(state.use === null);
  314. state.use = item;
  315. return this;
  316. };
  317. Node.prototype.optional = function optional() {
  318. var state = this._baseState;
  319. state.optional = true;
  320. return this;
  321. };
  322. Node.prototype.def = function def(val) {
  323. var state = this._baseState;
  324. assert(state['default'] === null);
  325. state['default'] = val;
  326. state.optional = true;
  327. return this;
  328. };
  329. Node.prototype.explicit = function explicit(num) {
  330. var state = this._baseState;
  331. assert(state.explicit === null && state.implicit === null);
  332. state.explicit = num;
  333. return this;
  334. };
  335. Node.prototype.implicit = function implicit(num) {
  336. var state = this._baseState;
  337. assert(state.explicit === null && state.implicit === null);
  338. state.implicit = num;
  339. return this;
  340. };
  341. Node.prototype.obj = function obj() {
  342. var state = this._baseState;
  343. var args = Array.prototype.slice.call(arguments);
  344. state.obj = true;
  345. if (args.length !== 0)
  346. this._useArgs(args);
  347. return this;
  348. };
  349. Node.prototype.key = function key(newKey) {
  350. var state = this._baseState;
  351. assert(state.key === null);
  352. state.key = newKey;
  353. return this;
  354. };
  355. Node.prototype.any = function any() {
  356. var state = this._baseState;
  357. state.any = true;
  358. return this;
  359. };
  360. Node.prototype.choice = function choice(obj) {
  361. var state = this._baseState;
  362. assert(state.choice === null);
  363. state.choice = obj;
  364. this._useArgs(Object.keys(obj).map(function(key) {
  365. return obj[key];
  366. }));
  367. return this;
  368. };
  369. Node.prototype.contains = function contains(item) {
  370. var state = this._baseState;
  371. assert(state.use === null);
  372. state.contains = item;
  373. return this;
  374. };
  375. //
  376. // Decoding
  377. //
  378. Node.prototype._decode = function decode(input, options) {
  379. var state = this._baseState;
  380. // Decode root node
  381. if (state.parent === null)
  382. return input.wrapResult(state.children[0]._decode(input, options));
  383. var result = state['default'];
  384. var present = true;
  385. var prevKey = null;
  386. if (state.key !== null)
  387. prevKey = input.enterKey(state.key);
  388. // Check if tag is there
  389. if (state.optional) {
  390. var tag = null;
  391. if (state.explicit !== null)
  392. tag = state.explicit;
  393. else if (state.implicit !== null)
  394. tag = state.implicit;
  395. else if (state.tag !== null)
  396. tag = state.tag;
  397. if (tag === null && !state.any) {
  398. // Trial and Error
  399. var save = input.save();
  400. try {
  401. if (state.choice === null)
  402. this._decodeGeneric(state.tag, input, options);
  403. else
  404. this._decodeChoice(input, options);
  405. present = true;
  406. } catch (e) {
  407. present = false;
  408. }
  409. input.restore(save);
  410. } else {
  411. present = this._peekTag(input, tag, state.any);
  412. if (input.isError(present))
  413. return present;
  414. }
  415. }
  416. // Push object on stack
  417. var prevObj;
  418. if (state.obj && present)
  419. prevObj = input.enterObject();
  420. if (present) {
  421. // Unwrap explicit values
  422. if (state.explicit !== null) {
  423. var explicit = this._decodeTag(input, state.explicit);
  424. if (input.isError(explicit))
  425. return explicit;
  426. input = explicit;
  427. }
  428. var start = input.offset;
  429. // Unwrap implicit and normal values
  430. if (state.use === null && state.choice === null) {
  431. if (state.any)
  432. var save = input.save();
  433. var body = this._decodeTag(
  434. input,
  435. state.implicit !== null ? state.implicit : state.tag,
  436. state.any
  437. );
  438. if (input.isError(body))
  439. return body;
  440. if (state.any)
  441. result = input.raw(save);
  442. else
  443. input = body;
  444. }
  445. if (options && options.track && state.tag !== null)
  446. options.track(input.path(), start, input.length, 'tagged');
  447. if (options && options.track && state.tag !== null)
  448. options.track(input.path(), input.offset, input.length, 'content');
  449. // Select proper method for tag
  450. if (state.any)
  451. result = result;
  452. else if (state.choice === null)
  453. result = this._decodeGeneric(state.tag, input, options);
  454. else
  455. result = this._decodeChoice(input, options);
  456. if (input.isError(result))
  457. return result;
  458. // Decode children
  459. if (!state.any && state.choice === null && state.children !== null) {
  460. state.children.forEach(function decodeChildren(child) {
  461. // NOTE: We are ignoring errors here, to let parser continue with other
  462. // parts of encoded data
  463. child._decode(input, options);
  464. });
  465. }
  466. // Decode contained/encoded by schema, only in bit or octet strings
  467. if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) {
  468. var data = new DecoderBuffer(result);
  469. result = this._getUse(state.contains, input._reporterState.obj)
  470. ._decode(data, options);
  471. }
  472. }
  473. // Pop object
  474. if (state.obj && present)
  475. result = input.leaveObject(prevObj);
  476. // Set key
  477. if (state.key !== null && (result !== null || present === true))
  478. input.leaveKey(prevKey, state.key, result);
  479. else if (prevKey !== null)
  480. input.exitKey(prevKey);
  481. return result;
  482. };
  483. Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) {
  484. var state = this._baseState;
  485. if (tag === 'seq' || tag === 'set')
  486. return null;
  487. if (tag === 'seqof' || tag === 'setof')
  488. return this._decodeList(input, tag, state.args[0], options);
  489. else if (/str$/.test(tag))
  490. return this._decodeStr(input, tag, options);
  491. else if (tag === 'objid' && state.args)
  492. return this._decodeObjid(input, state.args[0], state.args[1], options);
  493. else if (tag === 'objid')
  494. return this._decodeObjid(input, null, null, options);
  495. else if (tag === 'gentime' || tag === 'utctime')
  496. return this._decodeTime(input, tag, options);
  497. else if (tag === 'null_')
  498. return this._decodeNull(input, options);
  499. else if (tag === 'bool')
  500. return this._decodeBool(input, options);
  501. else if (tag === 'objDesc')
  502. return this._decodeStr(input, tag, options);
  503. else if (tag === 'int' || tag === 'enum')
  504. return this._decodeInt(input, state.args && state.args[0], options);
  505. if (state.use !== null) {
  506. return this._getUse(state.use, input._reporterState.obj)
  507. ._decode(input, options);
  508. } else {
  509. return input.error('unknown tag: ' + tag);
  510. }
  511. };
  512. Node.prototype._getUse = function _getUse(entity, obj) {
  513. var state = this._baseState;
  514. // Create altered use decoder if implicit is set
  515. state.useDecoder = this._use(entity, obj);
  516. assert(state.useDecoder._baseState.parent === null);
  517. state.useDecoder = state.useDecoder._baseState.children[0];
  518. if (state.implicit !== state.useDecoder._baseState.implicit) {
  519. state.useDecoder = state.useDecoder.clone();
  520. state.useDecoder._baseState.implicit = state.implicit;
  521. }
  522. return state.useDecoder;
  523. };
  524. Node.prototype._decodeChoice = function decodeChoice(input, options) {
  525. var state = this._baseState;
  526. var result = null;
  527. var match = false;
  528. Object.keys(state.choice).some(function(key) {
  529. var save = input.save();
  530. var node = state.choice[key];
  531. try {
  532. var value = node._decode(input, options);
  533. if (input.isError(value))
  534. return false;
  535. result = { type: key, value: value };
  536. match = true;
  537. } catch (e) {
  538. input.restore(save);
  539. return false;
  540. }
  541. return true;
  542. }, this);
  543. if (!match)
  544. return input.error('Choice not matched');
  545. return result;
  546. };
  547. //
  548. // Encoding
  549. //
  550. Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) {
  551. return new EncoderBuffer(data, this.reporter);
  552. };
  553. Node.prototype._encode = function encode(data, reporter, parent) {
  554. var state = this._baseState;
  555. if (state['default'] !== null && state['default'] === data)
  556. return;
  557. var result = this._encodeValue(data, reporter, parent);
  558. if (result === undefined)
  559. return;
  560. if (this._skipDefault(result, reporter, parent))
  561. return;
  562. return result;
  563. };
  564. Node.prototype._encodeValue = function encode(data, reporter, parent) {
  565. var state = this._baseState;
  566. // Decode root node
  567. if (state.parent === null)
  568. return state.children[0]._encode(data, reporter || new Reporter());
  569. var result = null;
  570. // Set reporter to share it with a child class
  571. this.reporter = reporter;
  572. // Check if data is there
  573. if (state.optional && data === undefined) {
  574. if (state['default'] !== null)
  575. data = state['default']
  576. else
  577. return;
  578. }
  579. // Encode children first
  580. var content = null;
  581. var primitive = false;
  582. if (state.any) {
  583. // Anything that was given is translated to buffer
  584. result = this._createEncoderBuffer(data);
  585. } else if (state.choice) {
  586. result = this._encodeChoice(data, reporter);
  587. } else if (state.contains) {
  588. content = this._getUse(state.contains, parent)._encode(data, reporter);
  589. primitive = true;
  590. } else if (state.children) {
  591. content = state.children.map(function(child) {
  592. if (child._baseState.tag === 'null_')
  593. return child._encode(null, reporter, data);
  594. if (child._baseState.key === null)
  595. return reporter.error('Child should have a key');
  596. var prevKey = reporter.enterKey(child._baseState.key);
  597. if (typeof data !== 'object')
  598. return reporter.error('Child expected, but input is not object');
  599. var res = child._encode(data[child._baseState.key], reporter, data);
  600. reporter.leaveKey(prevKey);
  601. return res;
  602. }, this).filter(function(child) {
  603. return child;
  604. });
  605. content = this._createEncoderBuffer(content);
  606. } else {
  607. if (state.tag === 'seqof' || state.tag === 'setof') {
  608. // TODO(indutny): this should be thrown on DSL level
  609. if (!(state.args && state.args.length === 1))
  610. return reporter.error('Too many args for : ' + state.tag);
  611. if (!Array.isArray(data))
  612. return reporter.error('seqof/setof, but data is not Array');
  613. var child = this.clone();
  614. child._baseState.implicit = null;
  615. content = this._createEncoderBuffer(data.map(function(item) {
  616. var state = this._baseState;
  617. return this._getUse(state.args[0], data)._encode(item, reporter);
  618. }, child));
  619. } else if (state.use !== null) {
  620. result = this._getUse(state.use, parent)._encode(data, reporter);
  621. } else {
  622. content = this._encodePrimitive(state.tag, data);
  623. primitive = true;
  624. }
  625. }
  626. // Encode data itself
  627. var result;
  628. if (!state.any && state.choice === null) {
  629. var tag = state.implicit !== null ? state.implicit : state.tag;
  630. var cls = state.implicit === null ? 'universal' : 'context';
  631. if (tag === null) {
  632. if (state.use === null)
  633. reporter.error('Tag could be omitted only for .use()');
  634. } else {
  635. if (state.use === null)
  636. result = this._encodeComposite(tag, primitive, cls, content);
  637. }
  638. }
  639. // Wrap in explicit
  640. if (state.explicit !== null)
  641. result = this._encodeComposite(state.explicit, false, 'context', result);
  642. return result;
  643. };
  644. Node.prototype._encodeChoice = function encodeChoice(data, reporter) {
  645. var state = this._baseState;
  646. var node = state.choice[data.type];
  647. if (!node) {
  648. assert(
  649. false,
  650. data.type + ' not found in ' +
  651. JSON.stringify(Object.keys(state.choice)));
  652. }
  653. return node._encode(data.value, reporter);
  654. };
  655. Node.prototype._encodePrimitive = function encodePrimitive(tag, data) {
  656. var state = this._baseState;
  657. if (/str$/.test(tag))
  658. return this._encodeStr(data, tag);
  659. else if (tag === 'objid' && state.args)
  660. return this._encodeObjid(data, state.reverseArgs[0], state.args[1]);
  661. else if (tag === 'objid')
  662. return this._encodeObjid(data, null, null);
  663. else if (tag === 'gentime' || tag === 'utctime')
  664. return this._encodeTime(data, tag);
  665. else if (tag === 'null_')
  666. return this._encodeNull();
  667. else if (tag === 'int' || tag === 'enum')
  668. return this._encodeInt(data, state.args && state.reverseArgs[0]);
  669. else if (tag === 'bool')
  670. return this._encodeBool(data);
  671. else if (tag === 'objDesc')
  672. return this._encodeStr(data, tag);
  673. else
  674. throw new Error('Unsupported tag: ' + tag);
  675. };
  676. Node.prototype._isNumstr = function isNumstr(str) {
  677. return /^[0-9 ]*$/.test(str);
  678. };
  679. Node.prototype._isPrintstr = function isPrintstr(str) {
  680. return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str);
  681. };
  682. },{"../base":4,"minimalistic-assert":110}],6:[function(require,module,exports){
  683. var inherits = require('inherits');
  684. function Reporter(options) {
  685. this._reporterState = {
  686. obj: null,
  687. path: [],
  688. options: options || {},
  689. errors: []
  690. };
  691. }
  692. exports.Reporter = Reporter;
  693. Reporter.prototype.isError = function isError(obj) {
  694. return obj instanceof ReporterError;
  695. };
  696. Reporter.prototype.save = function save() {
  697. var state = this._reporterState;
  698. return { obj: state.obj, pathLen: state.path.length };
  699. };
  700. Reporter.prototype.restore = function restore(data) {
  701. var state = this._reporterState;
  702. state.obj = data.obj;
  703. state.path = state.path.slice(0, data.pathLen);
  704. };
  705. Reporter.prototype.enterKey = function enterKey(key) {
  706. return this._reporterState.path.push(key);
  707. };
  708. Reporter.prototype.exitKey = function exitKey(index) {
  709. var state = this._reporterState;
  710. state.path = state.path.slice(0, index - 1);
  711. };
  712. Reporter.prototype.leaveKey = function leaveKey(index, key, value) {
  713. var state = this._reporterState;
  714. this.exitKey(index);
  715. if (state.obj !== null)
  716. state.obj[key] = value;
  717. };
  718. Reporter.prototype.path = function path() {
  719. return this._reporterState.path.join('/');
  720. };
  721. Reporter.prototype.enterObject = function enterObject() {
  722. var state = this._reporterState;
  723. var prev = state.obj;
  724. state.obj = {};
  725. return prev;
  726. };
  727. Reporter.prototype.leaveObject = function leaveObject(prev) {
  728. var state = this._reporterState;
  729. var now = state.obj;
  730. state.obj = prev;
  731. return now;
  732. };
  733. Reporter.prototype.error = function error(msg) {
  734. var err;
  735. var state = this._reporterState;
  736. var inherited = msg instanceof ReporterError;
  737. if (inherited) {
  738. err = msg;
  739. } else {
  740. err = new ReporterError(state.path.map(function(elem) {
  741. return '[' + JSON.stringify(elem) + ']';
  742. }).join(''), msg.message || msg, msg.stack);
  743. }
  744. if (!state.options.partial)
  745. throw err;
  746. if (!inherited)
  747. state.errors.push(err);
  748. return err;
  749. };
  750. Reporter.prototype.wrapResult = function wrapResult(result) {
  751. var state = this._reporterState;
  752. if (!state.options.partial)
  753. return result;
  754. return {
  755. result: this.isError(result) ? null : result,
  756. errors: state.errors
  757. };
  758. };
  759. function ReporterError(path, msg) {
  760. this.path = path;
  761. this.rethrow(msg);
  762. };
  763. inherits(ReporterError, Error);
  764. ReporterError.prototype.rethrow = function rethrow(msg) {
  765. this.message = msg + ' at: ' + (this.path || '(shallow)');
  766. if (Error.captureStackTrace)
  767. Error.captureStackTrace(this, ReporterError);
  768. if (!this.stack) {
  769. try {
  770. // IE only adds stack when thrown
  771. throw new Error(this.message);
  772. } catch (e) {
  773. this.stack = e.stack;
  774. }
  775. }
  776. return this;
  777. };
  778. },{"inherits":104}],7:[function(require,module,exports){
  779. var constants = require('../constants');
  780. exports.tagClass = {
  781. 0: 'universal',
  782. 1: 'application',
  783. 2: 'context',
  784. 3: 'private'
  785. };
  786. exports.tagClassByName = constants._reverse(exports.tagClass);
  787. exports.tag = {
  788. 0x00: 'end',
  789. 0x01: 'bool',
  790. 0x02: 'int',
  791. 0x03: 'bitstr',
  792. 0x04: 'octstr',
  793. 0x05: 'null_',
  794. 0x06: 'objid',
  795. 0x07: 'objDesc',
  796. 0x08: 'external',
  797. 0x09: 'real',
  798. 0x0a: 'enum',
  799. 0x0b: 'embed',
  800. 0x0c: 'utf8str',
  801. 0x0d: 'relativeOid',
  802. 0x10: 'seq',
  803. 0x11: 'set',
  804. 0x12: 'numstr',
  805. 0x13: 'printstr',
  806. 0x14: 't61str',
  807. 0x15: 'videostr',
  808. 0x16: 'ia5str',
  809. 0x17: 'utctime',
  810. 0x18: 'gentime',
  811. 0x19: 'graphstr',
  812. 0x1a: 'iso646str',
  813. 0x1b: 'genstr',
  814. 0x1c: 'unistr',
  815. 0x1d: 'charstr',
  816. 0x1e: 'bmpstr'
  817. };
  818. exports.tagByName = constants._reverse(exports.tag);
  819. },{"../constants":8}],8:[function(require,module,exports){
  820. var constants = exports;
  821. // Helper
  822. constants._reverse = function reverse(map) {
  823. var res = {};
  824. Object.keys(map).forEach(function(key) {
  825. // Convert key to integer if it is stringified
  826. if ((key | 0) == key)
  827. key = key | 0;
  828. var value = map[key];
  829. res[value] = key;
  830. });
  831. return res;
  832. };
  833. constants.der = require('./der');
  834. },{"./der":7}],9:[function(require,module,exports){
  835. var inherits = require('inherits');
  836. var asn1 = require('../../asn1');
  837. var base = asn1.base;
  838. var bignum = asn1.bignum;
  839. // Import DER constants
  840. var der = asn1.constants.der;
  841. function DERDecoder(entity) {
  842. this.enc = 'der';
  843. this.name = entity.name;
  844. this.entity = entity;
  845. // Construct base tree
  846. this.tree = new DERNode();
  847. this.tree._init(entity.body);
  848. };
  849. module.exports = DERDecoder;
  850. DERDecoder.prototype.decode = function decode(data, options) {
  851. if (!(data instanceof base.DecoderBuffer))
  852. data = new base.DecoderBuffer(data, options);
  853. return this.tree._decode(data, options);
  854. };
  855. // Tree methods
  856. function DERNode(parent) {
  857. base.Node.call(this, 'der', parent);
  858. }
  859. inherits(DERNode, base.Node);
  860. DERNode.prototype._peekTag = function peekTag(buffer, tag, any) {
  861. if (buffer.isEmpty())
  862. return false;
  863. var state = buffer.save();
  864. var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"');
  865. if (buffer.isError(decodedTag))
  866. return decodedTag;
  867. buffer.restore(state);
  868. return decodedTag.tag === tag || decodedTag.tagStr === tag ||
  869. (decodedTag.tagStr + 'of') === tag || any;
  870. };
  871. DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) {
  872. var decodedTag = derDecodeTag(buffer,
  873. 'Failed to decode tag of "' + tag + '"');
  874. if (buffer.isError(decodedTag))
  875. return decodedTag;
  876. var len = derDecodeLen(buffer,
  877. decodedTag.primitive,
  878. 'Failed to get length of "' + tag + '"');
  879. // Failure
  880. if (buffer.isError(len))
  881. return len;
  882. if (!any &&
  883. decodedTag.tag !== tag &&
  884. decodedTag.tagStr !== tag &&
  885. decodedTag.tagStr + 'of' !== tag) {
  886. return buffer.error('Failed to match tag: "' + tag + '"');
  887. }
  888. if (decodedTag.primitive || len !== null)
  889. return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
  890. // Indefinite length... find END tag
  891. var state = buffer.save();
  892. var res = this._skipUntilEnd(
  893. buffer,
  894. 'Failed to skip indefinite length body: "' + this.tag + '"');
  895. if (buffer.isError(res))
  896. return res;
  897. len = buffer.offset - state.offset;
  898. buffer.restore(state);
  899. return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
  900. };
  901. DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) {
  902. while (true) {
  903. var tag = derDecodeTag(buffer, fail);
  904. if (buffer.isError(tag))
  905. return tag;
  906. var len = derDecodeLen(buffer, tag.primitive, fail);
  907. if (buffer.isError(len))
  908. return len;
  909. var res;
  910. if (tag.primitive || len !== null)
  911. res = buffer.skip(len)
  912. else
  913. res = this._skipUntilEnd(buffer, fail);
  914. // Failure
  915. if (buffer.isError(res))
  916. return res;
  917. if (tag.tagStr === 'end')
  918. break;
  919. }
  920. };
  921. DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder,
  922. options) {
  923. var result = [];
  924. while (!buffer.isEmpty()) {
  925. var possibleEnd = this._peekTag(buffer, 'end');
  926. if (buffer.isError(possibleEnd))
  927. return possibleEnd;
  928. var res = decoder.decode(buffer, 'der', options);
  929. if (buffer.isError(res) && possibleEnd)
  930. break;
  931. result.push(res);
  932. }
  933. return result;
  934. };
  935. DERNode.prototype._decodeStr = function decodeStr(buffer, tag) {
  936. if (tag === 'bitstr') {
  937. var unused = buffer.readUInt8();
  938. if (buffer.isError(unused))
  939. return unused;
  940. return { unused: unused, data: buffer.raw() };
  941. } else if (tag === 'bmpstr') {
  942. var raw = buffer.raw();
  943. if (raw.length % 2 === 1)
  944. return buffer.error('Decoding of string type: bmpstr length mismatch');
  945. var str = '';
  946. for (var i = 0; i < raw.length / 2; i++) {
  947. str += String.fromCharCode(raw.readUInt16BE(i * 2));
  948. }
  949. return str;
  950. } else if (tag === 'numstr') {
  951. var numstr = buffer.raw().toString('ascii');
  952. if (!this._isNumstr(numstr)) {
  953. return buffer.error('Decoding of string type: ' +
  954. 'numstr unsupported characters');
  955. }
  956. return numstr;
  957. } else if (tag === 'octstr') {
  958. return buffer.raw();
  959. } else if (tag === 'objDesc') {
  960. return buffer.raw();
  961. } else if (tag === 'printstr') {
  962. var printstr = buffer.raw().toString('ascii');
  963. if (!this._isPrintstr(printstr)) {
  964. return buffer.error('Decoding of string type: ' +
  965. 'printstr unsupported characters');
  966. }
  967. return printstr;
  968. } else if (/str$/.test(tag)) {
  969. return buffer.raw().toString();
  970. } else {
  971. return buffer.error('Decoding of string type: ' + tag + ' unsupported');
  972. }
  973. };
  974. DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) {
  975. var result;
  976. var identifiers = [];
  977. var ident = 0;
  978. while (!buffer.isEmpty()) {
  979. var subident = buffer.readUInt8();
  980. ident <<= 7;
  981. ident |= subident & 0x7f;
  982. if ((subident & 0x80) === 0) {
  983. identifiers.push(ident);
  984. ident = 0;
  985. }
  986. }
  987. if (subident & 0x80)
  988. identifiers.push(ident);
  989. var first = (identifiers[0] / 40) | 0;
  990. var second = identifiers[0] % 40;
  991. if (relative)
  992. result = identifiers;
  993. else
  994. result = [first, second].concat(identifiers.slice(1));
  995. if (values) {
  996. var tmp = values[result.join(' ')];
  997. if (tmp === undefined)
  998. tmp = values[result.join('.')];
  999. if (tmp !== undefined)
  1000. result = tmp;
  1001. }
  1002. return result;
  1003. };
  1004. DERNode.prototype._decodeTime = function decodeTime(buffer, tag) {
  1005. var str = buffer.raw().toString();
  1006. if (tag === 'gentime') {
  1007. var year = str.slice(0, 4) | 0;
  1008. var mon = str.slice(4, 6) | 0;
  1009. var day = str.slice(6, 8) | 0;
  1010. var hour = str.slice(8, 10) | 0;
  1011. var min = str.slice(10, 12) | 0;
  1012. var sec = str.slice(12, 14) | 0;
  1013. } else if (tag === 'utctime') {
  1014. var year = str.slice(0, 2) | 0;
  1015. var mon = str.slice(2, 4) | 0;
  1016. var day = str.slice(4, 6) | 0;
  1017. var hour = str.slice(6, 8) | 0;
  1018. var min = str.slice(8, 10) | 0;
  1019. var sec = str.slice(10, 12) | 0;
  1020. if (year < 70)
  1021. year = 2000 + year;
  1022. else
  1023. year = 1900 + year;
  1024. } else {
  1025. return buffer.error('Decoding ' + tag + ' time is not supported yet');
  1026. }
  1027. return Date.UTC(year, mon - 1, day, hour, min, sec, 0);
  1028. };
  1029. DERNode.prototype._decodeNull = function decodeNull(buffer) {
  1030. return null;
  1031. };
  1032. DERNode.prototype._decodeBool = function decodeBool(buffer) {
  1033. var res = buffer.readUInt8();
  1034. if (buffer.isError(res))
  1035. return res;
  1036. else
  1037. return res !== 0;
  1038. };
  1039. DERNode.prototype._decodeInt = function decodeInt(buffer, values) {
  1040. // Bigint, return as it is (assume big endian)
  1041. var raw = buffer.raw();
  1042. var res = new bignum(raw);
  1043. if (values)
  1044. res = values[res.toString(10)] || res;
  1045. return res;
  1046. };
  1047. DERNode.prototype._use = function use(entity, obj) {
  1048. if (typeof entity === 'function')
  1049. entity = entity(obj);
  1050. return entity._getDecoder('der').tree;
  1051. };
  1052. // Utility methods
  1053. function derDecodeTag(buf, fail) {
  1054. var tag = buf.readUInt8(fail);
  1055. if (buf.isError(tag))
  1056. return tag;
  1057. var cls = der.tagClass[tag >> 6];
  1058. var primitive = (tag & 0x20) === 0;
  1059. // Multi-octet tag - load
  1060. if ((tag & 0x1f) === 0x1f) {
  1061. var oct = tag;
  1062. tag = 0;
  1063. while ((oct & 0x80) === 0x80) {
  1064. oct = buf.readUInt8(fail);
  1065. if (buf.isError(oct))
  1066. return oct;
  1067. tag <<= 7;
  1068. tag |= oct & 0x7f;
  1069. }
  1070. } else {
  1071. tag &= 0x1f;
  1072. }
  1073. var tagStr = der.tag[tag];
  1074. return {
  1075. cls: cls,
  1076. primitive: primitive,
  1077. tag: tag,
  1078. tagStr: tagStr
  1079. };
  1080. }
  1081. function derDecodeLen(buf, primitive, fail) {
  1082. var len = buf.readUInt8(fail);
  1083. if (buf.isError(len))
  1084. return len;
  1085. // Indefinite form
  1086. if (!primitive && len === 0x80)
  1087. return null;
  1088. // Definite form
  1089. if ((len & 0x80) === 0) {
  1090. // Short form
  1091. return len;
  1092. }
  1093. // Long form
  1094. var num = len & 0x7f;
  1095. if (num > 4)
  1096. return buf.error('length octect is too long');
  1097. len = 0;
  1098. for (var i = 0; i < num; i++) {
  1099. len <<= 8;
  1100. var j = buf.readUInt8(fail);
  1101. if (buf.isError(j))
  1102. return j;
  1103. len |= j;
  1104. }
  1105. return len;
  1106. }
  1107. },{"../../asn1":1,"inherits":104}],10:[function(require,module,exports){
  1108. var decoders = exports;
  1109. decoders.der = require('./der');
  1110. decoders.pem = require('./pem');
  1111. },{"./der":9,"./pem":11}],11:[function(require,module,exports){
  1112. var inherits = require('inherits');
  1113. var Buffer = require('buffer').Buffer;
  1114. var DERDecoder = require('./der');
  1115. function PEMDecoder(entity) {
  1116. DERDecoder.call(this, entity);
  1117. this.enc = 'pem';
  1118. };
  1119. inherits(PEMDecoder, DERDecoder);
  1120. module.exports = PEMDecoder;
  1121. PEMDecoder.prototype.decode = function decode(data, options) {
  1122. var lines = data.toString().split(/[\r\n]+/g);
  1123. var label = options.label.toUpperCase();
  1124. var re = /^-----(BEGIN|END) ([^-]+)-----$/;
  1125. var start = -1;
  1126. var end = -1;
  1127. for (var i = 0; i < lines.length; i++) {
  1128. var match = lines[i].match(re);
  1129. if (match === null)
  1130. continue;
  1131. if (match[2] !== label)
  1132. continue;
  1133. if (start === -1) {
  1134. if (match[1] !== 'BEGIN')
  1135. break;
  1136. start = i;
  1137. } else {
  1138. if (match[1] !== 'END')
  1139. break;
  1140. end = i;
  1141. break;
  1142. }
  1143. }
  1144. if (start === -1 || end === -1)
  1145. throw new Error('PEM section not found for: ' + label);
  1146. var base64 = lines.slice(start + 1, end).join('');
  1147. // Remove excessive symbols
  1148. base64.replace(/[^a-z0-9\+\/=]+/gi, '');
  1149. var input = new Buffer(base64, 'base64');
  1150. return DERDecoder.prototype.decode.call(this, input, options);
  1151. };
  1152. },{"./der":9,"buffer":50,"inherits":104}],12:[function(require,module,exports){
  1153. var inherits = require('inherits');
  1154. var Buffer = require('buffer').Buffer;
  1155. var asn1 = require('../../asn1');
  1156. var base = asn1.base;
  1157. // Import DER constants
  1158. var der = asn1.constants.der;
  1159. function DEREncoder(entity) {
  1160. this.enc = 'der';
  1161. this.name = entity.name;
  1162. this.entity = entity;
  1163. // Construct base tree
  1164. this.tree = new DERNode();
  1165. this.tree._init(entity.body);
  1166. };
  1167. module.exports = DEREncoder;
  1168. DEREncoder.prototype.encode = function encode(data, reporter) {
  1169. return this.tree._encode(data, reporter).join();
  1170. };
  1171. // Tree methods
  1172. function DERNode(parent) {
  1173. base.Node.call(this, 'der', parent);
  1174. }
  1175. inherits(DERNode, base.Node);
  1176. DERNode.prototype._encodeComposite = function encodeComposite(tag,
  1177. primitive,
  1178. cls,
  1179. content) {
  1180. var encodedTag = encodeTag(tag, primitive, cls, this.reporter);
  1181. // Short form
  1182. if (content.length < 0x80) {
  1183. var header = new Buffer(2);
  1184. header[0] = encodedTag;
  1185. header[1] = content.length;
  1186. return this._createEncoderBuffer([ header, content ]);
  1187. }
  1188. // Long form
  1189. // Count octets required to store length
  1190. var lenOctets = 1;
  1191. for (var i = content.length; i >= 0x100; i >>= 8)
  1192. lenOctets++;
  1193. var header = new Buffer(1 + 1 + lenOctets);
  1194. header[0] = encodedTag;
  1195. header[1] = 0x80 | lenOctets;
  1196. for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8)
  1197. header[i] = j & 0xff;
  1198. return this._createEncoderBuffer([ header, content ]);
  1199. };
  1200. DERNode.prototype._encodeStr = function encodeStr(str, tag) {
  1201. if (tag === 'bitstr') {
  1202. return this._createEncoderBuffer([ str.unused | 0, str.data ]);
  1203. } else if (tag === 'bmpstr') {
  1204. var buf = new Buffer(str.length * 2);
  1205. for (var i = 0; i < str.length; i++) {
  1206. buf.writeUInt16BE(str.charCodeAt(i), i * 2);
  1207. }
  1208. return this._createEncoderBuffer(buf);
  1209. } else if (tag === 'numstr') {
  1210. if (!this._isNumstr(str)) {
  1211. return this.reporter.error('Encoding of string type: numstr supports ' +
  1212. 'only digits and space');
  1213. }
  1214. return this._createEncoderBuffer(str);
  1215. } else if (tag === 'printstr') {
  1216. if (!this._isPrintstr(str)) {
  1217. return this.reporter.error('Encoding of string type: printstr supports ' +
  1218. 'only latin upper and lower case letters, ' +
  1219. 'digits, space, apostrophe, left and rigth ' +
  1220. 'parenthesis, plus sign, comma, hyphen, ' +
  1221. 'dot, slash, colon, equal sign, ' +
  1222. 'question mark');
  1223. }
  1224. return this._createEncoderBuffer(str);
  1225. } else if (/str$/.test(tag)) {
  1226. return this._createEncoderBuffer(str);
  1227. } else if (tag === 'objDesc') {
  1228. return this._createEncoderBuffer(str);
  1229. } else {
  1230. return this.reporter.error('Encoding of string type: ' + tag +
  1231. ' unsupported');
  1232. }
  1233. };
  1234. DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) {
  1235. if (typeof id === 'string') {
  1236. if (!values)
  1237. return this.reporter.error('string objid given, but no values map found');
  1238. if (!values.hasOwnProperty(id))
  1239. return this.reporter.error('objid not found in values map');
  1240. id = values[id].split(/[\s\.]+/g);
  1241. for (var i = 0; i < id.length; i++)
  1242. id[i] |= 0;
  1243. } else if (Array.isArray(id)) {
  1244. id = id.slice();
  1245. for (var i = 0; i < id.length; i++)
  1246. id[i] |= 0;
  1247. }
  1248. if (!Array.isArray(id)) {
  1249. return this.reporter.error('objid() should be either array or string, ' +
  1250. 'got: ' + JSON.stringify(id));
  1251. }
  1252. if (!relative) {
  1253. if (id[1] >= 40)
  1254. return this.reporter.error('Second objid identifier OOB');
  1255. id.splice(0, 2, id[0] * 40 + id[1]);
  1256. }
  1257. // Count number of octets
  1258. var size = 0;
  1259. for (var i = 0; i < id.length; i++) {
  1260. var ident = id[i];
  1261. for (size++; ident >= 0x80; ident >>= 7)
  1262. size++;
  1263. }
  1264. var objid = new Buffer(size);
  1265. var offset = objid.length - 1;
  1266. for (var i = id.length - 1; i >= 0; i--) {
  1267. var ident = id[i];
  1268. objid[offset--] = ident & 0x7f;
  1269. while ((ident >>= 7) > 0)
  1270. objid[offset--] = 0x80 | (ident & 0x7f);
  1271. }
  1272. return this._createEncoderBuffer(objid);
  1273. };
  1274. function two(num) {
  1275. if (num < 10)
  1276. return '0' + num;
  1277. else
  1278. return num;
  1279. }
  1280. DERNode.prototype._encodeTime = function encodeTime(time, tag) {
  1281. var str;
  1282. var date = new Date(time);
  1283. if (tag === 'gentime') {
  1284. str = [
  1285. two(date.getFullYear()),
  1286. two(date.getUTCMonth() + 1),
  1287. two(date.getUTCDate()),
  1288. two(date.getUTCHours()),
  1289. two(date.getUTCMinutes()),
  1290. two(date.getUTCSeconds()),
  1291. 'Z'
  1292. ].join('');
  1293. } else if (tag === 'utctime') {
  1294. str = [
  1295. two(date.getFullYear() % 100),
  1296. two(date.getUTCMonth() + 1),
  1297. two(date.getUTCDate()),
  1298. two(date.getUTCHours()),
  1299. two(date.getUTCMinutes()),
  1300. two(date.getUTCSeconds()),
  1301. 'Z'
  1302. ].join('');
  1303. } else {
  1304. this.reporter.error('Encoding ' + tag + ' time is not supported yet');
  1305. }
  1306. return this._encodeStr(str, 'octstr');
  1307. };
  1308. DERNode.prototype._encodeNull = function encodeNull() {
  1309. return this._createEncoderBuffer('');
  1310. };
  1311. DERNode.prototype._encodeInt = function encodeInt(num, values) {
  1312. if (typeof num === 'string') {
  1313. if (!values)
  1314. return this.reporter.error('String int or enum given, but no values map');
  1315. if (!values.hasOwnProperty(num)) {
  1316. return this.reporter.error('Values map doesn\'t contain: ' +
  1317. JSON.stringify(num));
  1318. }
  1319. num = values[num];
  1320. }
  1321. // Bignum, assume big endian
  1322. if (typeof num !== 'number' && !Buffer.isBuffer(num)) {
  1323. var numArray = num.toArray();
  1324. if (!num.sign && numArray[0] & 0x80) {
  1325. numArray.unshift(0);
  1326. }
  1327. num = new Buffer(numArray);
  1328. }
  1329. if (Buffer.isBuffer(num)) {
  1330. var size = num.length;
  1331. if (num.length === 0)
  1332. size++;
  1333. var out = new Buffer(size);
  1334. num.copy(out);
  1335. if (num.length === 0)
  1336. out[0] = 0
  1337. return this._createEncoderBuffer(out);
  1338. }
  1339. if (num < 0x80)
  1340. return this._createEncoderBuffer(num);
  1341. if (num < 0x100)
  1342. return this._createEncoderBuffer([0, num]);
  1343. var size = 1;
  1344. for (var i = num; i >= 0x100; i >>= 8)
  1345. size++;
  1346. var out = new Array(size);
  1347. for (var i = out.length - 1; i >= 0; i--) {
  1348. out[i] = num & 0xff;
  1349. num >>= 8;
  1350. }
  1351. if(out[0] & 0x80) {
  1352. out.unshift(0);
  1353. }
  1354. return this._createEncoderBuffer(new Buffer(out));
  1355. };
  1356. DERNode.prototype._encodeBool = function encodeBool(value) {
  1357. return this._createEncoderBuffer(value ? 0xff : 0);
  1358. };
  1359. DERNode.prototype._use = function use(entity, obj) {
  1360. if (typeof entity === 'function')
  1361. entity = entity(obj);
  1362. return entity._getEncoder('der').tree;
  1363. };
  1364. DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) {
  1365. var state = this._baseState;
  1366. var i;
  1367. if (state['default'] === null)
  1368. return false;
  1369. var data = dataBuffer.join();
  1370. if (state.defaultBuffer === undefined)
  1371. state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join();
  1372. if (data.length !== state.defaultBuffer.length)
  1373. return false;
  1374. for (i=0; i < data.length; i++)
  1375. if (data[i] !== state.defaultBuffer[i])
  1376. return false;
  1377. return true;
  1378. };
  1379. // Utility methods
  1380. function encodeTag(tag, primitive, cls, reporter) {
  1381. var res;
  1382. if (tag === 'seqof')
  1383. tag = 'seq';
  1384. else if (tag === 'setof')
  1385. tag = 'set';
  1386. if (der.tagByName.hasOwnProperty(tag))
  1387. res = der.tagByName[tag];
  1388. else if (typeof tag === 'number' && (tag | 0) === tag)
  1389. res = tag;
  1390. else
  1391. return reporter.error('Unknown tag: ' + tag);
  1392. if (res >= 0x1f)
  1393. return reporter.error('Multi-octet tag encoding unsupported');
  1394. if (!primitive)
  1395. res |= 0x20;
  1396. res |= (der.tagClassByName[cls || 'universal'] << 6);
  1397. return res;
  1398. }
  1399. },{"../../asn1":1,"buffer":50,"inherits":104}],13:[function(require,module,exports){
  1400. var encoders = exports;
  1401. encoders.der = require('./der');
  1402. encoders.pem = require('./pem');
  1403. },{"./der":12,"./pem":14}],14:[function(require,module,exports){
  1404. var inherits = require('inherits');
  1405. var DEREncoder = require('./der');
  1406. function PEMEncoder(entity) {
  1407. DEREncoder.call(this, entity);
  1408. this.enc = 'pem';
  1409. };
  1410. inherits(PEMEncoder, DEREncoder);
  1411. module.exports = PEMEncoder;
  1412. PEMEncoder.prototype.encode = function encode(data, options) {
  1413. var buf = DEREncoder.prototype.encode.call(this, data);
  1414. var p = buf.toString('base64');
  1415. var out = [ '-----BEGIN ' + options.label + '-----' ];
  1416. for (var i = 0; i < p.length; i += 64)
  1417. out.push(p.slice(i, i + 64));
  1418. out.push('-----END ' + options.label + '-----');
  1419. return out.join('\n');
  1420. };
  1421. },{"./der":12,"inherits":104}],15:[function(require,module,exports){
  1422. (function (global){
  1423. 'use strict';
  1424. // compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
  1425. // original notice:
  1426. /*!
  1427. * The buffer module from node.js, for the browser.
  1428. *
  1429. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  1430. * @license MIT
  1431. */
  1432. function compare(a, b) {
  1433. if (a === b) {
  1434. return 0;
  1435. }
  1436. var x = a.length;
  1437. var y = b.length;
  1438. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  1439. if (a[i] !== b[i]) {
  1440. x = a[i];
  1441. y = b[i];
  1442. break;
  1443. }
  1444. }
  1445. if (x < y) {
  1446. return -1;
  1447. }
  1448. if (y < x) {
  1449. return 1;
  1450. }
  1451. return 0;
  1452. }
  1453. function isBuffer(b) {
  1454. if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
  1455. return global.Buffer.isBuffer(b);
  1456. }
  1457. return !!(b != null && b._isBuffer);
  1458. }
  1459. // based on node assert, original notice:
  1460. // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
  1461. //
  1462. // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
  1463. //
  1464. // Originally from narwhal.js (http://narwhaljs.org)
  1465. // Copyright (c) 2009 Thomas Robinson <280north.com>
  1466. //
  1467. // Permission is hereby granted, free of charge, to any person obtaining a copy
  1468. // of this software and associated documentation files (the 'Software'), to
  1469. // deal in the Software without restriction, including without limitation the
  1470. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  1471. // sell copies of the Software, and to permit persons to whom the Software is
  1472. // furnished to do so, subject to the following conditions:
  1473. //
  1474. // The above copyright notice and this permission notice shall be included in
  1475. // all copies or substantial portions of the Software.
  1476. //
  1477. // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1478. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1479. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  1480. // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  1481. // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  1482. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  1483. var util = require('util/');
  1484. var hasOwn = Object.prototype.hasOwnProperty;
  1485. var pSlice = Array.prototype.slice;
  1486. var functionsHaveNames = (function () {
  1487. return function foo() {}.name === 'foo';
  1488. }());
  1489. function pToString (obj) {
  1490. return Object.prototype.toString.call(obj);
  1491. }
  1492. function isView(arrbuf) {
  1493. if (isBuffer(arrbuf)) {
  1494. return false;
  1495. }
  1496. if (typeof global.ArrayBuffer !== 'function') {
  1497. return false;
  1498. }
  1499. if (typeof ArrayBuffer.isView === 'function') {
  1500. return ArrayBuffer.isView(arrbuf);
  1501. }
  1502. if (!arrbuf) {
  1503. return false;
  1504. }
  1505. if (arrbuf instanceof DataView) {
  1506. return true;
  1507. }
  1508. if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
  1509. return true;
  1510. }
  1511. return false;
  1512. }
  1513. // 1. The assert module provides functions that throw
  1514. // AssertionError's when particular conditions are not met. The
  1515. // assert module must conform to the following interface.
  1516. var assert = module.exports = ok;
  1517. // 2. The AssertionError is defined in assert.
  1518. // new assert.AssertionError({ message: message,
  1519. // actual: actual,
  1520. // expected: expected })
  1521. var regex = /\s*function\s+([^\(\s]*)\s*/;
  1522. // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
  1523. function getName(func) {
  1524. if (!util.isFunction(func)) {
  1525. return;
  1526. }
  1527. if (functionsHaveNames) {
  1528. return func.name;
  1529. }
  1530. var str = func.toString();
  1531. var match = str.match(regex);
  1532. return match && match[1];
  1533. }
  1534. assert.AssertionError = function AssertionError(options) {
  1535. this.name = 'AssertionError';
  1536. this.actual = options.actual;
  1537. this.expected = options.expected;
  1538. this.operator = options.operator;
  1539. if (options.message) {
  1540. this.message = options.message;
  1541. this.generatedMessage = false;
  1542. } else {
  1543. this.message = getMessage(this);
  1544. this.generatedMessage = true;
  1545. }
  1546. var stackStartFunction = options.stackStartFunction || fail;
  1547. if (Error.captureStackTrace) {
  1548. Error.captureStackTrace(this, stackStartFunction);
  1549. } else {
  1550. // non v8 browsers so we can have a stacktrace
  1551. var err = new Error();
  1552. if (err.stack) {
  1553. var out = err.stack;
  1554. // try to strip useless frames
  1555. var fn_name = getName(stackStartFunction);
  1556. var idx = out.indexOf('\n' + fn_name);
  1557. if (idx >= 0) {
  1558. // once we have located the function frame
  1559. // we need to strip out everything before it (and its line)
  1560. var next_line = out.indexOf('\n', idx + 1);
  1561. out = out.substring(next_line + 1);
  1562. }
  1563. this.stack = out;
  1564. }
  1565. }
  1566. };
  1567. // assert.AssertionError instanceof Error
  1568. util.inherits(assert.AssertionError, Error);
  1569. function truncate(s, n) {
  1570. if (typeof s === 'string') {
  1571. return s.length < n ? s : s.slice(0, n);
  1572. } else {
  1573. return s;
  1574. }
  1575. }
  1576. function inspect(something) {
  1577. if (functionsHaveNames || !util.isFunction(something)) {
  1578. return util.inspect(something);
  1579. }
  1580. var rawname = getName(something);
  1581. var name = rawname ? ': ' + rawname : '';
  1582. return '[Function' + name + ']';
  1583. }
  1584. function getMessage(self) {
  1585. return truncate(inspect(self.actual), 128) + ' ' +
  1586. self.operator + ' ' +
  1587. truncate(inspect(self.expected), 128);
  1588. }
  1589. // At present only the three keys mentioned above are used and
  1590. // understood by the spec. Implementations or sub modules can pass
  1591. // other keys to the AssertionError's constructor - they will be
  1592. // ignored.
  1593. // 3. All of the following functions must throw an AssertionError
  1594. // when a corresponding condition is not met, with a message that
  1595. // may be undefined if not provided. All assertion methods provide
  1596. // both the actual and expected values to the assertion error for
  1597. // display purposes.
  1598. function fail(actual, expected, message, operator, stackStartFunction) {
  1599. throw new assert.AssertionError({
  1600. message: message,
  1601. actual: actual,
  1602. expected: expected,
  1603. operator: operator,
  1604. stackStartFunction: stackStartFunction
  1605. });
  1606. }
  1607. // EXTENSION! allows for well behaved errors defined elsewhere.
  1608. assert.fail = fail;
  1609. // 4. Pure assertion tests whether a value is truthy, as determined
  1610. // by !!guard.
  1611. // assert.ok(guard, message_opt);
  1612. // This statement is equivalent to assert.equal(true, !!guard,
  1613. // message_opt);. To test strictly for the value true, use
  1614. // assert.strictEqual(true, guard, message_opt);.
  1615. function ok(value, message) {
  1616. if (!value) fail(value, true, message, '==', assert.ok);
  1617. }
  1618. assert.ok = ok;
  1619. // 5. The equality assertion tests shallow, coercive equality with
  1620. // ==.
  1621. // assert.equal(actual, expected, message_opt);
  1622. assert.equal = function equal(actual, expected, message) {
  1623. if (actual != expected) fail(actual, expected, message, '==', assert.equal);
  1624. };
  1625. // 6. The non-equality assertion tests for whether two objects are not equal
  1626. // with != assert.notEqual(actual, expected, message_opt);
  1627. assert.notEqual = function notEqual(actual, expected, message) {
  1628. if (actual == expected) {
  1629. fail(actual, expected, message, '!=', assert.notEqual);
  1630. }
  1631. };
  1632. // 7. The equivalence assertion tests a deep equality relation.
  1633. // assert.deepEqual(actual, expected, message_opt);
  1634. assert.deepEqual = function deepEqual(actual, expected, message) {
  1635. if (!_deepEqual(actual, expected, false)) {
  1636. fail(actual, expected, message, 'deepEqual', assert.deepEqual);
  1637. }
  1638. };
  1639. assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
  1640. if (!_deepEqual(actual, expected, true)) {
  1641. fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
  1642. }
  1643. };
  1644. function _deepEqual(actual, expected, strict, memos) {
  1645. // 7.1. All identical values are equivalent, as determined by ===.
  1646. if (actual === expected) {
  1647. return true;
  1648. } else if (isBuffer(actual) && isBuffer(expected)) {
  1649. return compare(actual, expected) === 0;
  1650. // 7.2. If the expected value is a Date object, the actual value is
  1651. // equivalent if it is also a Date object that refers to the same time.
  1652. } else if (util.isDate(actual) && util.isDate(expected)) {
  1653. return actual.getTime() === expected.getTime();
  1654. // 7.3 If the expected value is a RegExp object, the actual value is
  1655. // equivalent if it is also a RegExp object with the same source and
  1656. // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
  1657. } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
  1658. return actual.source === expected.source &&
  1659. actual.global === expected.global &&
  1660. actual.multiline === expected.multiline &&
  1661. actual.lastIndex === expected.lastIndex &&
  1662. actual.ignoreCase === expected.ignoreCase;
  1663. // 7.4. Other pairs that do not both pass typeof value == 'object',
  1664. // equivalence is determined by ==.
  1665. } else if ((actual === null || typeof actual !== 'object') &&
  1666. (expected === null || typeof expected !== 'object')) {
  1667. return strict ? actual === expected : actual == expected;
  1668. // If both values are instances of typed arrays, wrap their underlying
  1669. // ArrayBuffers in a Buffer each to increase performance
  1670. // This optimization requires the arrays to have the same type as checked by
  1671. // Object.prototype.toString (aka pToString). Never perform binary
  1672. // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
  1673. // bit patterns are not identical.
  1674. } else if (isView(actual) && isView(expected) &&
  1675. pToString(actual) === pToString(expected) &&
  1676. !(actual instanceof Float32Array ||
  1677. actual instanceof Float64Array)) {
  1678. return compare(new Uint8Array(actual.buffer),
  1679. new Uint8Array(expected.buffer)) === 0;
  1680. // 7.5 For all other Object pairs, including Array objects, equivalence is
  1681. // determined by having the same number of owned properties (as verified
  1682. // with Object.prototype.hasOwnProperty.call), the same set of keys
  1683. // (although not necessarily the same order), equivalent values for every
  1684. // corresponding key, and an identical 'prototype' property. Note: this
  1685. // accounts for both named and indexed properties on Arrays.
  1686. } else if (isBuffer(actual) !== isBuffer(expected)) {
  1687. return false;
  1688. } else {
  1689. memos = memos || {actual: [], expected: []};
  1690. var actualIndex = memos.actual.indexOf(actual);
  1691. if (actualIndex !== -1) {
  1692. if (actualIndex === memos.expected.indexOf(expected)) {
  1693. return true;
  1694. }
  1695. }
  1696. memos.actual.push(actual);
  1697. memos.expected.push(expected);
  1698. return objEquiv(actual, expected, strict, memos);
  1699. }
  1700. }
  1701. function isArguments(object) {
  1702. return Object.prototype.toString.call(object) == '[object Arguments]';
  1703. }
  1704. function objEquiv(a, b, strict, actualVisitedObjects) {
  1705. if (a === null || a === undefined || b === null || b === undefined)
  1706. return false;
  1707. // if one is a primitive, the other must be same
  1708. if (util.isPrimitive(a) || util.isPrimitive(b))
  1709. return a === b;
  1710. if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
  1711. return false;
  1712. var aIsArgs = isArguments(a);
  1713. var bIsArgs = isArguments(b);
  1714. if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
  1715. return false;
  1716. if (aIsArgs) {
  1717. a = pSlice.call(a);
  1718. b = pSlice.call(b);
  1719. return _deepEqual(a, b, strict);
  1720. }
  1721. var ka = objectKeys(a);
  1722. var kb = objectKeys(b);
  1723. var key, i;
  1724. // having the same number of owned properties (keys incorporates
  1725. // hasOwnProperty)
  1726. if (ka.length !== kb.length)
  1727. return false;
  1728. //the same set of keys (although not necessarily the same order),
  1729. ka.sort();
  1730. kb.sort();
  1731. //~~~cheap key test
  1732. for (i = ka.length - 1; i >= 0; i--) {
  1733. if (ka[i] !== kb[i])
  1734. return false;
  1735. }
  1736. //equivalent values for every corresponding key, and
  1737. //~~~possibly expensive deep test
  1738. for (i = ka.length - 1; i >= 0; i--) {
  1739. key = ka[i];
  1740. if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
  1741. return false;
  1742. }
  1743. return true;
  1744. }
  1745. // 8. The non-equivalence assertion tests for any deep inequality.
  1746. // assert.notDeepEqual(actual, expected, message_opt);
  1747. assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
  1748. if (_deepEqual(actual, expected, false)) {
  1749. fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
  1750. }
  1751. };
  1752. assert.notDeepStrictEqual = notDeepStrictEqual;
  1753. function notDeepStrictEqual(actual, expected, message) {
  1754. if (_deepEqual(actual, expected, true)) {
  1755. fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
  1756. }
  1757. }
  1758. // 9. The strict equality assertion tests strict equality, as determined by ===.
  1759. // assert.strictEqual(actual, expected, message_opt);
  1760. assert.strictEqual = function strictEqual(actual, expected, message) {
  1761. if (actual !== expected) {
  1762. fail(actual, expected, message, '===', assert.strictEqual);
  1763. }
  1764. };
  1765. // 10. The strict non-equality assertion tests for strict inequality, as
  1766. // determined by !==. assert.notStrictEqual(actual, expected, message_opt);
  1767. assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
  1768. if (actual === expected) {
  1769. fail(actual, expected, message, '!==', assert.notStrictEqual);
  1770. }
  1771. };
  1772. function expectedException(actual, expected) {
  1773. if (!actual || !expected) {
  1774. return false;
  1775. }
  1776. if (Object.prototype.toString.call(expected) == '[object RegExp]') {
  1777. return expected.test(actual);
  1778. }
  1779. try {
  1780. if (actual instanceof expected) {
  1781. return true;
  1782. }
  1783. } catch (e) {
  1784. // Ignore. The instanceof check doesn't work for arrow functions.
  1785. }
  1786. if (Error.isPrototypeOf(expected)) {
  1787. return false;
  1788. }
  1789. return expected.call({}, actual) === true;
  1790. }
  1791. function _tryBlock(block) {
  1792. var error;
  1793. try {
  1794. block();
  1795. } catch (e) {
  1796. error = e;
  1797. }
  1798. return error;
  1799. }
  1800. function _throws(shouldThrow, block, expected, message) {
  1801. var actual;
  1802. if (typeof block !== 'function') {
  1803. throw new TypeError('"block" argument must be a function');
  1804. }
  1805. if (typeof expected === 'string') {
  1806. message = expected;
  1807. expected = null;
  1808. }
  1809. actual = _tryBlock(block);
  1810. message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
  1811. (message ? ' ' + message : '.');
  1812. if (shouldThrow && !actual) {
  1813. fail(actual, expected, 'Missing expected exception' + message);
  1814. }
  1815. var userProvidedMessage = typeof message === 'string';
  1816. var isUnwantedException = !shouldThrow && util.isError(actual);
  1817. var isUnexpectedException = !shouldThrow && actual && !expected;
  1818. if ((isUnwantedException &&
  1819. userProvidedMessage &&
  1820. expectedException(actual, expected)) ||
  1821. isUnexpectedException) {
  1822. fail(actual, expected, 'Got unwanted exception' + message);
  1823. }
  1824. if ((shouldThrow && actual && expected &&
  1825. !expectedException(actual, expected)) || (!shouldThrow && actual)) {
  1826. throw actual;
  1827. }
  1828. }
  1829. // 11. Expected to throw an error:
  1830. // assert.throws(block, Error_opt, message_opt);
  1831. assert.throws = function(block, /*optional*/error, /*optional*/message) {
  1832. _throws(true, block, error, message);
  1833. };
  1834. // EXTENSION! This is annoying to write outside this module.
  1835. assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
  1836. _throws(false, block, error, message);
  1837. };
  1838. assert.ifError = function(err) { if (err) throw err; };
  1839. var objectKeys = Object.keys || function (obj) {
  1840. var keys = [];
  1841. for (var key in obj) {
  1842. if (hasOwn.call(obj, key)) keys.push(key);
  1843. }
  1844. return keys;
  1845. };
  1846. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1847. },{"util/":171}],16:[function(require,module,exports){
  1848. 'use strict'
  1849. exports.byteLength = byteLength
  1850. exports.toByteArray = toByteArray
  1851. exports.fromByteArray = fromByteArray
  1852. var lookup = []
  1853. var revLookup = []
  1854. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  1855. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  1856. for (var i = 0, len = code.length; i < len; ++i) {
  1857. lookup[i] = code[i]
  1858. revLookup[code.charCodeAt(i)] = i
  1859. }
  1860. revLookup['-'.charCodeAt(0)] = 62
  1861. revLookup['_'.charCodeAt(0)] = 63
  1862. function placeHoldersCount (b64) {
  1863. var len = b64.length
  1864. if (len % 4 > 0) {
  1865. throw new Error('Invalid string. Length must be a multiple of 4')
  1866. }
  1867. // the number of equal signs (place holders)
  1868. // if there are two placeholders, than the two characters before it
  1869. // represent one byte
  1870. // if there is only one, then the three characters before it represent 2 bytes
  1871. // this is just a cheap hack to not do indexOf twice
  1872. return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  1873. }
  1874. function byteLength (b64) {
  1875. // base64 is 4/3 + up to two characters of the original data
  1876. return (b64.length * 3 / 4) - placeHoldersCount(b64)
  1877. }
  1878. function toByteArray (b64) {
  1879. var i, l, tmp, placeHolders, arr
  1880. var len = b64.length
  1881. placeHolders = placeHoldersCount(b64)
  1882. arr = new Arr((len * 3 / 4) - placeHolders)
  1883. // if there are placeholders, only get up to the last complete 4 chars
  1884. l = placeHolders > 0 ? len - 4 : len
  1885. var L = 0
  1886. for (i = 0; i < l; i += 4) {
  1887. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  1888. arr[L++] = (tmp >> 16) & 0xFF
  1889. arr[L++] = (tmp >> 8) & 0xFF
  1890. arr[L++] = tmp & 0xFF
  1891. }
  1892. if (placeHolders === 2) {
  1893. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  1894. arr[L++] = tmp & 0xFF
  1895. } else if (placeHolders === 1) {
  1896. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  1897. arr[L++] = (tmp >> 8) & 0xFF
  1898. arr[L++] = tmp & 0xFF
  1899. }
  1900. return arr
  1901. }
  1902. function tripletToBase64 (num) {
  1903. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  1904. }
  1905. function encodeChunk (uint8, start, end) {
  1906. var tmp
  1907. var output = []
  1908. for (var i = start; i < end; i += 3) {
  1909. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  1910. output.push(tripletToBase64(tmp))
  1911. }
  1912. return output.join('')
  1913. }
  1914. function fromByteArray (uint8) {
  1915. var tmp
  1916. var len = uint8.length
  1917. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  1918. var output = ''
  1919. var parts = []
  1920. var maxChunkLength = 16383 // must be multiple of 3
  1921. // go through the array every three bytes, we'll deal with trailing stuff later
  1922. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  1923. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  1924. }
  1925. // pad the end with zeros, but make sure to not forget the extra bytes
  1926. if (extraBytes === 1) {
  1927. tmp = uint8[len - 1]
  1928. output += lookup[tmp >> 2]
  1929. output += lookup[(tmp << 4) & 0x3F]
  1930. output += '=='
  1931. } else if (extraBytes === 2) {
  1932. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  1933. output += lookup[tmp >> 10]
  1934. output += lookup[(tmp >> 4) & 0x3F]
  1935. output += lookup[(tmp << 2) & 0x3F]
  1936. output += '='
  1937. }
  1938. parts.push(output)
  1939. return parts.join('')
  1940. }
  1941. },{}],17:[function(require,module,exports){
  1942. (function (module, exports) {
  1943. 'use strict';
  1944. // Utils
  1945. function assert (val, msg) {
  1946. if (!val) throw new Error(msg || 'Assertion failed');
  1947. }
  1948. // Could use `inherits` module, but don't want to move from single file
  1949. // architecture yet.
  1950. function inherits (ctor, superCtor) {
  1951. ctor.super_ = superCtor;
  1952. var TempCtor = function () {};
  1953. TempCtor.prototype = superCtor.prototype;
  1954. ctor.prototype = new TempCtor();
  1955. ctor.prototype.constructor = ctor;
  1956. }
  1957. // BN
  1958. function BN (number, base, endian) {
  1959. if (BN.isBN(number)) {
  1960. return number;
  1961. }
  1962. this.negative = 0;
  1963. this.words = null;
  1964. this.length = 0;
  1965. // Reduction context
  1966. this.red = null;
  1967. if (number !== null) {
  1968. if (base === 'le' || base === 'be') {
  1969. endian = base;
  1970. base = 10;
  1971. }
  1972. this._init(number || 0, base || 10, endian || 'be');
  1973. }
  1974. }
  1975. if (typeof module === 'object') {
  1976. module.exports = BN;
  1977. } else {
  1978. exports.BN = BN;
  1979. }
  1980. BN.BN = BN;
  1981. BN.wordSize = 26;
  1982. var Buffer;
  1983. try {
  1984. Buffer = require('buffer').Buffer;
  1985. } catch (e) {
  1986. }
  1987. BN.isBN = function isBN (num) {
  1988. if (num instanceof BN) {
  1989. return true;
  1990. }
  1991. return num !== null && typeof num === 'object' &&
  1992. num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
  1993. };
  1994. BN.max = function max (left, right) {
  1995. if (left.cmp(right) > 0) return left;
  1996. return right;
  1997. };
  1998. BN.min = function min (left, right) {
  1999. if (left.cmp(right) < 0) return left;
  2000. return right;
  2001. };
  2002. BN.prototype._init = function init (number, base, endian) {
  2003. if (typeof number === 'number') {
  2004. return this._initNumber(number, base, endian);
  2005. }
  2006. if (typeof number === 'object') {
  2007. return this._initArray(number, base, endian);
  2008. }
  2009. if (base === 'hex') {
  2010. base = 16;
  2011. }
  2012. assert(base === (base | 0) && base >= 2 && base <= 36);
  2013. number = number.toString().replace(/\s+/g, '');
  2014. var start = 0;
  2015. if (number[0] === '-') {
  2016. start++;
  2017. }
  2018. if (base === 16) {
  2019. this._parseHex(number, start);
  2020. } else {
  2021. this._parseBase(number, base, start);
  2022. }
  2023. if (number[0] === '-') {
  2024. this.negative = 1;
  2025. }
  2026. this.strip();
  2027. if (endian !== 'le') return;
  2028. this._initArray(this.toArray(), base, endian);
  2029. };
  2030. BN.prototype._initNumber = function _initNumber (number, base, endian) {
  2031. if (number < 0) {
  2032. this.negative = 1;
  2033. number = -number;
  2034. }
  2035. if (number < 0x4000000) {
  2036. this.words = [ number & 0x3ffffff ];
  2037. this.length = 1;
  2038. } else if (number < 0x10000000000000) {
  2039. this.words = [
  2040. number & 0x3ffffff,
  2041. (number / 0x4000000) & 0x3ffffff
  2042. ];
  2043. this.length = 2;
  2044. } else {
  2045. assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
  2046. this.words = [
  2047. number & 0x3ffffff,
  2048. (number / 0x4000000) & 0x3ffffff,
  2049. 1
  2050. ];
  2051. this.length = 3;
  2052. }
  2053. if (endian !== 'le') return;
  2054. // Reverse the bytes
  2055. this._initArray(this.toArray(), base, endian);
  2056. };
  2057. BN.prototype._initArray = function _initArray (number, base, endian) {
  2058. // Perhaps a Uint8Array
  2059. assert(typeof number.length === 'number');
  2060. if (number.length <= 0) {
  2061. this.words = [ 0 ];
  2062. this.length = 1;
  2063. return this;
  2064. }
  2065. this.length = Math.ceil(number.length / 3);
  2066. this.words = new Array(this.length);
  2067. for (var i = 0; i < this.length; i++) {
  2068. this.words[i] = 0;
  2069. }
  2070. var j, w;
  2071. var off = 0;
  2072. if (endian === 'be') {
  2073. for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
  2074. w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
  2075. this.words[j] |= (w << off) & 0x3ffffff;
  2076. this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
  2077. off += 24;
  2078. if (off >= 26) {
  2079. off -= 26;
  2080. j++;
  2081. }
  2082. }
  2083. } else if (endian === 'le') {
  2084. for (i = 0, j = 0; i < number.length; i += 3) {
  2085. w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
  2086. this.words[j] |= (w << off) & 0x3ffffff;
  2087. this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
  2088. off += 24;
  2089. if (off >= 26) {
  2090. off -= 26;
  2091. j++;
  2092. }
  2093. }
  2094. }
  2095. return this.strip();
  2096. };
  2097. function parseHex (str, start, end) {
  2098. var r = 0;
  2099. var len = Math.min(str.length, end);
  2100. for (var i = start; i < len; i++) {
  2101. var c = str.charCodeAt(i) - 48;
  2102. r <<= 4;
  2103. // 'a' - 'f'
  2104. if (c >= 49 && c <= 54) {
  2105. r |= c - 49 + 0xa;
  2106. // 'A' - 'F'
  2107. } else if (c >= 17 && c <= 22) {
  2108. r |= c - 17 + 0xa;
  2109. // '0' - '9'
  2110. } else {
  2111. r |= c & 0xf;
  2112. }
  2113. }
  2114. return r;
  2115. }
  2116. BN.prototype._parseHex = function _parseHex (number, start) {
  2117. // Create possibly bigger array to ensure that it fits the number
  2118. this.length = Math.ceil((number.length - start) / 6);
  2119. this.words = new Array(this.length);
  2120. for (var i = 0; i < this.length; i++) {
  2121. this.words[i] = 0;
  2122. }
  2123. var j, w;
  2124. // Scan 24-bit chunks and add them to the number
  2125. var off = 0;
  2126. for (i = number.length - 6, j = 0; i >= start; i -= 6) {
  2127. w = parseHex(number, i, i + 6);
  2128. this.words[j] |= (w << off) & 0x3ffffff;
  2129. // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
  2130. this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
  2131. off += 24;
  2132. if (off >= 26) {
  2133. off -= 26;
  2134. j++;
  2135. }
  2136. }
  2137. if (i + 6 !== start) {
  2138. w = parseHex(number, start, i + 6);
  2139. this.words[j] |= (w << off) & 0x3ffffff;
  2140. this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
  2141. }
  2142. this.strip();
  2143. };
  2144. function parseBase (str, start, end, mul) {
  2145. var r = 0;
  2146. var len = Math.min(str.length, end);
  2147. for (var i = start; i < len; i++) {
  2148. var c = str.charCodeAt(i) - 48;
  2149. r *= mul;
  2150. // 'a'
  2151. if (c >= 49) {
  2152. r += c - 49 + 0xa;
  2153. // 'A'
  2154. } else if (c >= 17) {
  2155. r += c - 17 + 0xa;
  2156. // '0' - '9'
  2157. } else {
  2158. r += c;
  2159. }
  2160. }
  2161. return r;
  2162. }
  2163. BN.prototype._parseBase = function _parseBase (number, base, start) {
  2164. // Initialize as zero
  2165. this.words = [ 0 ];
  2166. this.length = 1;
  2167. // Find length of limb in base
  2168. for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
  2169. limbLen++;
  2170. }
  2171. limbLen--;
  2172. limbPow = (limbPow / base) | 0;
  2173. var total = number.length - start;
  2174. var mod = total % limbLen;
  2175. var end = Math.min(total, total - mod) + start;
  2176. var word = 0;
  2177. for (var i = start; i < end; i += limbLen) {
  2178. word = parseBase(number, i, i + limbLen, base);
  2179. this.imuln(limbPow);
  2180. if (this.words[0] + word < 0x4000000) {
  2181. this.words[0] += word;
  2182. } else {
  2183. this._iaddn(word);
  2184. }
  2185. }
  2186. if (mod !== 0) {
  2187. var pow = 1;
  2188. word = parseBase(number, i, number.length, base);
  2189. for (i = 0; i < mod; i++) {
  2190. pow *= base;
  2191. }
  2192. this.imuln(pow);
  2193. if (this.words[0] + word < 0x4000000) {
  2194. this.words[0] += word;
  2195. } else {
  2196. this._iaddn(word);
  2197. }
  2198. }
  2199. };
  2200. BN.prototype.copy = function copy (dest) {
  2201. dest.words = new Array(this.length);
  2202. for (var i = 0; i < this.length; i++) {
  2203. dest.words[i] = this.words[i];
  2204. }
  2205. dest.length = this.length;
  2206. dest.negative = this.negative;
  2207. dest.red = this.red;
  2208. };
  2209. BN.prototype.clone = function clone () {
  2210. var r = new BN(null);
  2211. this.copy(r);
  2212. return r;
  2213. };
  2214. BN.prototype._expand = function _expand (size) {
  2215. while (this.length < size) {
  2216. this.words[this.length++] = 0;
  2217. }
  2218. return this;
  2219. };
  2220. // Remove leading `0` from `this`
  2221. BN.prototype.strip = function strip () {
  2222. while (this.length > 1 && this.words[this.length - 1] === 0) {
  2223. this.length--;
  2224. }
  2225. return this._normSign();
  2226. };
  2227. BN.prototype._normSign = function _normSign () {
  2228. // -0 = 0
  2229. if (this.length === 1 && this.words[0] === 0) {
  2230. this.negative = 0;
  2231. }
  2232. return this;
  2233. };
  2234. BN.prototype.inspect = function inspect () {
  2235. return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
  2236. };
  2237. /*
  2238. var zeros = [];
  2239. var groupSizes = [];
  2240. var groupBases = [];
  2241. var s = '';
  2242. var i = -1;
  2243. while (++i < BN.wordSize) {
  2244. zeros[i] = s;
  2245. s += '0';
  2246. }
  2247. groupSizes[0] = 0;
  2248. groupSizes[1] = 0;
  2249. groupBases[0] = 0;
  2250. groupBases[1] = 0;
  2251. var base = 2 - 1;
  2252. while (++base < 36 + 1) {
  2253. var groupSize = 0;
  2254. var groupBase = 1;
  2255. while (groupBase < (1 << BN.wordSize) / base) {
  2256. groupBase *= base;
  2257. groupSize += 1;
  2258. }
  2259. groupSizes[base] = groupSize;
  2260. groupBases[base] = groupBase;
  2261. }
  2262. */
  2263. var zeros = [
  2264. '',
  2265. '0',
  2266. '00',
  2267. '000',
  2268. '0000',
  2269. '00000',
  2270. '000000',
  2271. '0000000',
  2272. '00000000',
  2273. '000000000',
  2274. '0000000000',
  2275. '00000000000',
  2276. '000000000000',
  2277. '0000000000000',
  2278. '00000000000000',
  2279. '000000000000000',
  2280. '0000000000000000',
  2281. '00000000000000000',
  2282. '000000000000000000',
  2283. '0000000000000000000',
  2284. '00000000000000000000',
  2285. '000000000000000000000',
  2286. '0000000000000000000000',
  2287. '00000000000000000000000',
  2288. '000000000000000000000000',
  2289. '0000000000000000000000000'
  2290. ];
  2291. var groupSizes = [
  2292. 0, 0,
  2293. 25, 16, 12, 11, 10, 9, 8,
  2294. 8, 7, 7, 7, 7, 6, 6,
  2295. 6, 6, 6, 6, 6, 5, 5,
  2296. 5, 5, 5, 5, 5, 5, 5,
  2297. 5, 5, 5, 5, 5, 5, 5
  2298. ];
  2299. var groupBases = [
  2300. 0, 0,
  2301. 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
  2302. 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
  2303. 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
  2304. 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
  2305. 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
  2306. ];
  2307. BN.prototype.toString = function toString (base, padding) {
  2308. base = base || 10;
  2309. padding = padding | 0 || 1;
  2310. var out;
  2311. if (base === 16 || base === 'hex') {
  2312. out = '';
  2313. var off = 0;
  2314. var carry = 0;
  2315. for (var i = 0; i < this.length; i++) {
  2316. var w = this.words[i];
  2317. var word = (((w << off) | carry) & 0xffffff).toString(16);
  2318. carry = (w >>> (24 - off)) & 0xffffff;
  2319. if (carry !== 0 || i !== this.length - 1) {
  2320. out = zeros[6 - word.length] + word + out;
  2321. } else {
  2322. out = word + out;
  2323. }
  2324. off += 2;
  2325. if (off >= 26) {
  2326. off -= 26;
  2327. i--;
  2328. }
  2329. }
  2330. if (carry !== 0) {
  2331. out = carry.toString(16) + out;
  2332. }
  2333. while (out.length % padding !== 0) {
  2334. out = '0' + out;
  2335. }
  2336. if (this.negative !== 0) {
  2337. out = '-' + out;
  2338. }
  2339. return out;
  2340. }
  2341. if (base === (base | 0) && base >= 2 && base <= 36) {
  2342. // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
  2343. var groupSize = groupSizes[base];
  2344. // var groupBase = Math.pow(base, groupSize);
  2345. var groupBase = groupBases[base];
  2346. out = '';
  2347. var c = this.clone();
  2348. c.negative = 0;
  2349. while (!c.isZero()) {
  2350. var r = c.modn(groupBase).toString(base);
  2351. c = c.idivn(groupBase);
  2352. if (!c.isZero()) {
  2353. out = zeros[groupSize - r.length] + r + out;
  2354. } else {
  2355. out = r + out;
  2356. }
  2357. }
  2358. if (this.isZero()) {
  2359. out = '0' + out;
  2360. }
  2361. while (out.length % padding !== 0) {
  2362. out = '0' + out;
  2363. }
  2364. if (this.negative !== 0) {
  2365. out = '-' + out;
  2366. }
  2367. return out;
  2368. }
  2369. assert(false, 'Base should be between 2 and 36');
  2370. };
  2371. BN.prototype.toNumber = function toNumber () {
  2372. var ret = this.words[0];
  2373. if (this.length === 2) {
  2374. ret += this.words[1] * 0x4000000;
  2375. } else if (this.length === 3 && this.words[2] === 0x01) {
  2376. // NOTE: at this stage it is known that the top bit is set
  2377. ret += 0x10000000000000 + (this.words[1] * 0x4000000);
  2378. } else if (this.length > 2) {
  2379. assert(false, 'Number can only safely store up to 53 bits');
  2380. }
  2381. return (this.negative !== 0) ? -ret : ret;
  2382. };
  2383. BN.prototype.toJSON = function toJSON () {
  2384. return this.toString(16);
  2385. };
  2386. BN.prototype.toBuffer = function toBuffer (endian, length) {
  2387. assert(typeof Buffer !== 'undefined');
  2388. return this.toArrayLike(Buffer, endian, length);
  2389. };
  2390. BN.prototype.toArray = function toArray (endian, length) {
  2391. return this.toArrayLike(Array, endian, length);
  2392. };
  2393. BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
  2394. var byteLength = this.byteLength();
  2395. var reqLength = length || Math.max(1, byteLength);
  2396. assert(byteLength <= reqLength, 'byte array longer than desired length');
  2397. assert(reqLength > 0, 'Requested array length <= 0');
  2398. this.strip();
  2399. var littleEndian = endian === 'le';
  2400. var res = new ArrayType(reqLength);
  2401. var b, i;
  2402. var q = this.clone();
  2403. if (!littleEndian) {
  2404. // Assume big-endian
  2405. for (i = 0; i < reqLength - byteLength; i++) {
  2406. res[i] = 0;
  2407. }
  2408. for (i = 0; !q.isZero(); i++) {
  2409. b = q.andln(0xff);
  2410. q.iushrn(8);
  2411. res[reqLength - i - 1] = b;
  2412. }
  2413. } else {
  2414. for (i = 0; !q.isZero(); i++) {
  2415. b = q.andln(0xff);
  2416. q.iushrn(8);
  2417. res[i] = b;
  2418. }
  2419. for (; i < reqLength; i++) {
  2420. res[i] = 0;
  2421. }
  2422. }
  2423. return res;
  2424. };
  2425. if (Math.clz32) {
  2426. BN.prototype._countBits = function _countBits (w) {
  2427. return 32 - Math.clz32(w);
  2428. };
  2429. } else {
  2430. BN.prototype._countBits = function _countBits (w) {
  2431. var t = w;
  2432. var r = 0;
  2433. if (t >= 0x1000) {
  2434. r += 13;
  2435. t >>>= 13;
  2436. }
  2437. if (t >= 0x40) {
  2438. r += 7;
  2439. t >>>= 7;
  2440. }
  2441. if (t >= 0x8) {
  2442. r += 4;
  2443. t >>>= 4;
  2444. }
  2445. if (t >= 0x02) {
  2446. r += 2;
  2447. t >>>= 2;
  2448. }
  2449. return r + t;
  2450. };
  2451. }
  2452. BN.prototype._zeroBits = function _zeroBits (w) {
  2453. // Short-cut
  2454. if (w === 0) return 26;
  2455. var t = w;
  2456. var r = 0;
  2457. if ((t & 0x1fff) === 0) {
  2458. r += 13;
  2459. t >>>= 13;
  2460. }
  2461. if ((t & 0x7f) === 0) {
  2462. r += 7;
  2463. t >>>= 7;
  2464. }
  2465. if ((t & 0xf) === 0) {
  2466. r += 4;
  2467. t >>>= 4;
  2468. }
  2469. if ((t & 0x3) === 0) {
  2470. r += 2;
  2471. t >>>= 2;
  2472. }
  2473. if ((t & 0x1) === 0) {
  2474. r++;
  2475. }
  2476. return r;
  2477. };
  2478. // Return number of used bits in a BN
  2479. BN.prototype.bitLength = function bitLength () {
  2480. var w = this.words[this.length - 1];
  2481. var hi = this._countBits(w);
  2482. return (this.length - 1) * 26 + hi;
  2483. };
  2484. function toBitArray (num) {
  2485. var w = new Array(num.bitLength());
  2486. for (var bit = 0; bit < w.length; bit++) {
  2487. var off = (bit / 26) | 0;
  2488. var wbit = bit % 26;
  2489. w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
  2490. }
  2491. return w;
  2492. }
  2493. // Number of trailing zero bits
  2494. BN.prototype.zeroBits = function zeroBits () {
  2495. if (this.isZero()) return 0;
  2496. var r = 0;
  2497. for (var i = 0; i < this.length; i++) {
  2498. var b = this._zeroBits(this.words[i]);
  2499. r += b;
  2500. if (b !== 26) break;
  2501. }
  2502. return r;
  2503. };
  2504. BN.prototype.byteLength = function byteLength () {
  2505. return Math.ceil(this.bitLength() / 8);
  2506. };
  2507. BN.prototype.toTwos = function toTwos (width) {
  2508. if (this.negative !== 0) {
  2509. return this.abs().inotn(width).iaddn(1);
  2510. }
  2511. return this.clone();
  2512. };
  2513. BN.prototype.fromTwos = function fromTwos (width) {
  2514. if (this.testn(width - 1)) {
  2515. return this.notn(width).iaddn(1).ineg();
  2516. }
  2517. return this.clone();
  2518. };
  2519. BN.prototype.isNeg = function isNeg () {
  2520. return this.negative !== 0;
  2521. };
  2522. // Return negative clone of `this`
  2523. BN.prototype.neg = function neg () {
  2524. return this.clone().ineg();
  2525. };
  2526. BN.prototype.ineg = function ineg () {
  2527. if (!this.isZero()) {
  2528. this.negative ^= 1;
  2529. }
  2530. return this;
  2531. };
  2532. // Or `num` with `this` in-place
  2533. BN.prototype.iuor = function iuor (num) {
  2534. while (this.length < num.length) {
  2535. this.words[this.length++] = 0;
  2536. }
  2537. for (var i = 0; i < num.length; i++) {
  2538. this.words[i] = this.words[i] | num.words[i];
  2539. }
  2540. return this.strip();
  2541. };
  2542. BN.prototype.ior = function ior (num) {
  2543. assert((this.negative | num.negative) === 0);
  2544. return this.iuor(num);
  2545. };
  2546. // Or `num` with `this`
  2547. BN.prototype.or = function or (num) {
  2548. if (this.length > num.length) return this.clone().ior(num);
  2549. return num.clone().ior(this);
  2550. };
  2551. BN.prototype.uor = function uor (num) {
  2552. if (this.length > num.length) return this.clone().iuor(num);
  2553. return num.clone().iuor(this);
  2554. };
  2555. // And `num` with `this` in-place
  2556. BN.prototype.iuand = function iuand (num) {
  2557. // b = min-length(num, this)
  2558. var b;
  2559. if (this.length > num.length) {
  2560. b = num;
  2561. } else {
  2562. b = this;
  2563. }
  2564. for (var i = 0; i < b.length; i++) {
  2565. this.words[i] = this.words[i] & num.words[i];
  2566. }
  2567. this.length = b.length;
  2568. return this.strip();
  2569. };
  2570. BN.prototype.iand = function iand (num) {
  2571. assert((this.negative | num.negative) === 0);
  2572. return this.iuand(num);
  2573. };
  2574. // And `num` with `this`
  2575. BN.prototype.and = function and (num) {
  2576. if (this.length > num.length) return this.clone().iand(num);
  2577. return num.clone().iand(this);
  2578. };
  2579. BN.prototype.uand = function uand (num) {
  2580. if (this.length > num.length) return this.clone().iuand(num);
  2581. return num.clone().iuand(this);
  2582. };
  2583. // Xor `num` with `this` in-place
  2584. BN.prototype.iuxor = function iuxor (num) {
  2585. // a.length > b.length
  2586. var a;
  2587. var b;
  2588. if (this.length > num.length) {
  2589. a = this;
  2590. b = num;
  2591. } else {
  2592. a = num;
  2593. b = this;
  2594. }
  2595. for (var i = 0; i < b.length; i++) {
  2596. this.words[i] = a.words[i] ^ b.words[i];
  2597. }
  2598. if (this !== a) {
  2599. for (; i < a.length; i++) {
  2600. this.words[i] = a.words[i];
  2601. }
  2602. }
  2603. this.length = a.length;
  2604. return this.strip();
  2605. };
  2606. BN.prototype.ixor = function ixor (num) {
  2607. assert((this.negative | num.negative) === 0);
  2608. return this.iuxor(num);
  2609. };
  2610. // Xor `num` with `this`
  2611. BN.prototype.xor = function xor (num) {
  2612. if (this.length > num.length) return this.clone().ixor(num);
  2613. return num.clone().ixor(this);
  2614. };
  2615. BN.prototype.uxor = function uxor (num) {
  2616. if (this.length > num.length) return this.clone().iuxor(num);
  2617. return num.clone().iuxor(this);
  2618. };
  2619. // Not ``this`` with ``width`` bitwidth
  2620. BN.prototype.inotn = function inotn (width) {
  2621. assert(typeof width === 'number' && width >= 0);
  2622. var bytesNeeded = Math.ceil(width / 26) | 0;
  2623. var bitsLeft = width % 26;
  2624. // Extend the buffer with leading zeroes
  2625. this._expand(bytesNeeded);
  2626. if (bitsLeft > 0) {
  2627. bytesNeeded--;
  2628. }
  2629. // Handle complete words
  2630. for (var i = 0; i < bytesNeeded; i++) {
  2631. this.words[i] = ~this.words[i] & 0x3ffffff;
  2632. }
  2633. // Handle the residue
  2634. if (bitsLeft > 0) {
  2635. this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
  2636. }
  2637. // And remove leading zeroes
  2638. return this.strip();
  2639. };
  2640. BN.prototype.notn = function notn (width) {
  2641. return this.clone().inotn(width);
  2642. };
  2643. // Set `bit` of `this`
  2644. BN.prototype.setn = function setn (bit, val) {
  2645. assert(typeof bit === 'number' && bit >= 0);
  2646. var off = (bit / 26) | 0;
  2647. var wbit = bit % 26;
  2648. this._expand(off + 1);
  2649. if (val) {
  2650. this.words[off] = this.words[off] | (1 << wbit);
  2651. } else {
  2652. this.words[off] = this.words[off] & ~(1 << wbit);
  2653. }
  2654. return this.strip();
  2655. };
  2656. // Add `num` to `this` in-place
  2657. BN.prototype.iadd = function iadd (num) {
  2658. var r;
  2659. // negative + positive
  2660. if (this.negative !== 0 && num.negative === 0) {
  2661. this.negative = 0;
  2662. r = this.isub(num);
  2663. this.negative ^= 1;
  2664. return this._normSign();
  2665. // positive + negative
  2666. } else if (this.negative === 0 && num.negative !== 0) {
  2667. num.negative = 0;
  2668. r = this.isub(num);
  2669. num.negative = 1;
  2670. return r._normSign();
  2671. }
  2672. // a.length > b.length
  2673. var a, b;
  2674. if (this.length > num.length) {
  2675. a = this;
  2676. b = num;
  2677. } else {
  2678. a = num;
  2679. b = this;
  2680. }
  2681. var carry = 0;
  2682. for (var i = 0; i < b.length; i++) {
  2683. r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
  2684. this.words[i] = r & 0x3ffffff;
  2685. carry = r >>> 26;
  2686. }
  2687. for (; carry !== 0 && i < a.length; i++) {
  2688. r = (a.words[i] | 0) + carry;
  2689. this.words[i] = r & 0x3ffffff;
  2690. carry = r >>> 26;
  2691. }
  2692. this.length = a.length;
  2693. if (carry !== 0) {
  2694. this.words[this.length] = carry;
  2695. this.length++;
  2696. // Copy the rest of the words
  2697. } else if (a !== this) {
  2698. for (; i < a.length; i++) {
  2699. this.words[i] = a.words[i];
  2700. }
  2701. }
  2702. return this;
  2703. };
  2704. // Add `num` to `this`
  2705. BN.prototype.add = function add (num) {
  2706. var res;
  2707. if (num.negative !== 0 && this.negative === 0) {
  2708. num.negative = 0;
  2709. res = this.sub(num);
  2710. num.negative ^= 1;
  2711. return res;
  2712. } else if (num.negative === 0 && this.negative !== 0) {
  2713. this.negative = 0;
  2714. res = num.sub(this);
  2715. this.negative = 1;
  2716. return res;
  2717. }
  2718. if (this.length > num.length) return this.clone().iadd(num);
  2719. return num.clone().iadd(this);
  2720. };
  2721. // Subtract `num` from `this` in-place
  2722. BN.prototype.isub = function isub (num) {
  2723. // this - (-num) = this + num
  2724. if (num.negative !== 0) {
  2725. num.negative = 0;
  2726. var r = this.iadd(num);
  2727. num.negative = 1;
  2728. return r._normSign();
  2729. // -this - num = -(this + num)
  2730. } else if (this.negative !== 0) {
  2731. this.negative = 0;
  2732. this.iadd(num);
  2733. this.negative = 1;
  2734. return this._normSign();
  2735. }
  2736. // At this point both numbers are positive
  2737. var cmp = this.cmp(num);
  2738. // Optimization - zeroify
  2739. if (cmp === 0) {
  2740. this.negative = 0;
  2741. this.length = 1;
  2742. this.words[0] = 0;
  2743. return this;
  2744. }
  2745. // a > b
  2746. var a, b;
  2747. if (cmp > 0) {
  2748. a = this;
  2749. b = num;
  2750. } else {
  2751. a = num;
  2752. b = this;
  2753. }
  2754. var carry = 0;
  2755. for (var i = 0; i < b.length; i++) {
  2756. r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
  2757. carry = r >> 26;
  2758. this.words[i] = r & 0x3ffffff;
  2759. }
  2760. for (; carry !== 0 && i < a.length; i++) {
  2761. r = (a.words[i] | 0) + carry;
  2762. carry = r >> 26;
  2763. this.words[i] = r & 0x3ffffff;
  2764. }
  2765. // Copy rest of the words
  2766. if (carry === 0 && i < a.length && a !== this) {
  2767. for (; i < a.length; i++) {
  2768. this.words[i] = a.words[i];
  2769. }
  2770. }
  2771. this.length = Math.max(this.length, i);
  2772. if (a !== this) {
  2773. this.negative = 1;
  2774. }
  2775. return this.strip();
  2776. };
  2777. // Subtract `num` from `this`
  2778. BN.prototype.sub = function sub (num) {
  2779. return this.clone().isub(num);
  2780. };
  2781. function smallMulTo (self, num, out) {
  2782. out.negative = num.negative ^ self.negative;
  2783. var len = (self.length + num.length) | 0;
  2784. out.length = len;
  2785. len = (len - 1) | 0;
  2786. // Peel one iteration (compiler can't do it, because of code complexity)
  2787. var a = self.words[0] | 0;
  2788. var b = num.words[0] | 0;
  2789. var r = a * b;
  2790. var lo = r & 0x3ffffff;
  2791. var carry = (r / 0x4000000) | 0;
  2792. out.words[0] = lo;
  2793. for (var k = 1; k < len; k++) {
  2794. // Sum all words with the same `i + j = k` and accumulate `ncarry`,
  2795. // note that ncarry could be >= 0x3ffffff
  2796. var ncarry = carry >>> 26;
  2797. var rword = carry & 0x3ffffff;
  2798. var maxJ = Math.min(k, num.length - 1);
  2799. for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
  2800. var i = (k - j) | 0;
  2801. a = self.words[i] | 0;
  2802. b = num.words[j] | 0;
  2803. r = a * b + rword;
  2804. ncarry += (r / 0x4000000) | 0;
  2805. rword = r & 0x3ffffff;
  2806. }
  2807. out.words[k] = rword | 0;
  2808. carry = ncarry | 0;
  2809. }
  2810. if (carry !== 0) {
  2811. out.words[k] = carry | 0;
  2812. } else {
  2813. out.length--;
  2814. }
  2815. return out.strip();
  2816. }
  2817. // TODO(indutny): it may be reasonable to omit it for users who don't need
  2818. // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
  2819. // multiplication (like elliptic secp256k1).
  2820. var comb10MulTo = function comb10MulTo (self, num, out) {
  2821. var a = self.words;
  2822. var b = num.words;
  2823. var o = out.words;
  2824. var c = 0;
  2825. var lo;
  2826. var mid;
  2827. var hi;
  2828. var a0 = a[0] | 0;
  2829. var al0 = a0 & 0x1fff;
  2830. var ah0 = a0 >>> 13;
  2831. var a1 = a[1] | 0;
  2832. var al1 = a1 & 0x1fff;
  2833. var ah1 = a1 >>> 13;
  2834. var a2 = a[2] | 0;
  2835. var al2 = a2 & 0x1fff;
  2836. var ah2 = a2 >>> 13;
  2837. var a3 = a[3] | 0;
  2838. var al3 = a3 & 0x1fff;
  2839. var ah3 = a3 >>> 13;
  2840. var a4 = a[4] | 0;
  2841. var al4 = a4 & 0x1fff;
  2842. var ah4 = a4 >>> 13;
  2843. var a5 = a[5] | 0;
  2844. var al5 = a5 & 0x1fff;
  2845. var ah5 = a5 >>> 13;
  2846. var a6 = a[6] | 0;
  2847. var al6 = a6 & 0x1fff;
  2848. var ah6 = a6 >>> 13;
  2849. var a7 = a[7] | 0;
  2850. var al7 = a7 & 0x1fff;
  2851. var ah7 = a7 >>> 13;
  2852. var a8 = a[8] | 0;
  2853. var al8 = a8 & 0x1fff;
  2854. var ah8 = a8 >>> 13;
  2855. var a9 = a[9] | 0;
  2856. var al9 = a9 & 0x1fff;
  2857. var ah9 = a9 >>> 13;
  2858. var b0 = b[0] | 0;
  2859. var bl0 = b0 & 0x1fff;
  2860. var bh0 = b0 >>> 13;
  2861. var b1 = b[1] | 0;
  2862. var bl1 = b1 & 0x1fff;
  2863. var bh1 = b1 >>> 13;
  2864. var b2 = b[2] | 0;
  2865. var bl2 = b2 & 0x1fff;
  2866. var bh2 = b2 >>> 13;
  2867. var b3 = b[3] | 0;
  2868. var bl3 = b3 & 0x1fff;
  2869. var bh3 = b3 >>> 13;
  2870. var b4 = b[4] | 0;
  2871. var bl4 = b4 & 0x1fff;
  2872. var bh4 = b4 >>> 13;
  2873. var b5 = b[5] | 0;
  2874. var bl5 = b5 & 0x1fff;
  2875. var bh5 = b5 >>> 13;
  2876. var b6 = b[6] | 0;
  2877. var bl6 = b6 & 0x1fff;
  2878. var bh6 = b6 >>> 13;
  2879. var b7 = b[7] | 0;
  2880. var bl7 = b7 & 0x1fff;
  2881. var bh7 = b7 >>> 13;
  2882. var b8 = b[8] | 0;
  2883. var bl8 = b8 & 0x1fff;
  2884. var bh8 = b8 >>> 13;
  2885. var b9 = b[9] | 0;
  2886. var bl9 = b9 & 0x1fff;
  2887. var bh9 = b9 >>> 13;
  2888. out.negative = self.negative ^ num.negative;
  2889. out.length = 19;
  2890. /* k = 0 */
  2891. lo = Math.imul(al0, bl0);
  2892. mid = Math.imul(al0, bh0);
  2893. mid = (mid + Math.imul(ah0, bl0)) | 0;
  2894. hi = Math.imul(ah0, bh0);
  2895. var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  2896. c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
  2897. w0 &= 0x3ffffff;
  2898. /* k = 1 */
  2899. lo = Math.imul(al1, bl0);
  2900. mid = Math.imul(al1, bh0);
  2901. mid = (mid + Math.imul(ah1, bl0)) | 0;
  2902. hi = Math.imul(ah1, bh0);
  2903. lo = (lo + Math.imul(al0, bl1)) | 0;
  2904. mid = (mid + Math.imul(al0, bh1)) | 0;
  2905. mid = (mid + Math.imul(ah0, bl1)) | 0;
  2906. hi = (hi + Math.imul(ah0, bh1)) | 0;
  2907. var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  2908. c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
  2909. w1 &= 0x3ffffff;
  2910. /* k = 2 */
  2911. lo = Math.imul(al2, bl0);
  2912. mid = Math.imul(al2, bh0);
  2913. mid = (mid + Math.imul(ah2, bl0)) | 0;
  2914. hi = Math.imul(ah2, bh0);
  2915. lo = (lo + Math.imul(al1, bl1)) | 0;
  2916. mid = (mid + Math.imul(al1, bh1)) | 0;
  2917. mid = (mid + Math.imul(ah1, bl1)) | 0;
  2918. hi = (hi + Math.imul(ah1, bh1)) | 0;
  2919. lo = (lo + Math.imul(al0, bl2)) | 0;
  2920. mid = (mid + Math.imul(al0, bh2)) | 0;
  2921. mid = (mid + Math.imul(ah0, bl2)) | 0;
  2922. hi = (hi + Math.imul(ah0, bh2)) | 0;
  2923. var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  2924. c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
  2925. w2 &= 0x3ffffff;
  2926. /* k = 3 */
  2927. lo = Math.imul(al3, bl0);
  2928. mid = Math.imul(al3, bh0);
  2929. mid = (mid + Math.imul(ah3, bl0)) | 0;
  2930. hi = Math.imul(ah3, bh0);
  2931. lo = (lo + Math.imul(al2, bl1)) | 0;
  2932. mid = (mid + Math.imul(al2, bh1)) | 0;
  2933. mid = (mid + Math.imul(ah2, bl1)) | 0;
  2934. hi = (hi + Math.imul(ah2, bh1)) | 0;
  2935. lo = (lo + Math.imul(al1, bl2)) | 0;
  2936. mid = (mid + Math.imul(al1, bh2)) | 0;
  2937. mid = (mid + Math.imul(ah1, bl2)) | 0;
  2938. hi = (hi + Math.imul(ah1, bh2)) | 0;
  2939. lo = (lo + Math.imul(al0, bl3)) | 0;
  2940. mid = (mid + Math.imul(al0, bh3)) | 0;
  2941. mid = (mid + Math.imul(ah0, bl3)) | 0;
  2942. hi = (hi + Math.imul(ah0, bh3)) | 0;
  2943. var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  2944. c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
  2945. w3 &= 0x3ffffff;
  2946. /* k = 4 */
  2947. lo = Math.imul(al4, bl0);
  2948. mid = Math.imul(al4, bh0);
  2949. mid = (mid + Math.imul(ah4, bl0)) | 0;
  2950. hi = Math.imul(ah4, bh0);
  2951. lo = (lo + Math.imul(al3, bl1)) | 0;
  2952. mid = (mid + Math.imul(al3, bh1)) | 0;
  2953. mid = (mid + Math.imul(ah3, bl1)) | 0;
  2954. hi = (hi + Math.imul(ah3, bh1)) | 0;
  2955. lo = (lo + Math.imul(al2, bl2)) | 0;
  2956. mid = (mid + Math.imul(al2, bh2)) | 0;
  2957. mid = (mid + Math.imul(ah2, bl2)) | 0;
  2958. hi = (hi + Math.imul(ah2, bh2)) | 0;
  2959. lo = (lo + Math.imul(al1, bl3)) | 0;
  2960. mid = (mid + Math.imul(al1, bh3)) | 0;
  2961. mid = (mid + Math.imul(ah1, bl3)) | 0;
  2962. hi = (hi + Math.imul(ah1, bh3)) | 0;
  2963. lo = (lo + Math.imul(al0, bl4)) | 0;
  2964. mid = (mid + Math.imul(al0, bh4)) | 0;
  2965. mid = (mid + Math.imul(ah0, bl4)) | 0;
  2966. hi = (hi + Math.imul(ah0, bh4)) | 0;
  2967. var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  2968. c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
  2969. w4 &= 0x3ffffff;
  2970. /* k = 5 */
  2971. lo = Math.imul(al5, bl0);
  2972. mid = Math.imul(al5, bh0);
  2973. mid = (mid + Math.imul(ah5, bl0)) | 0;
  2974. hi = Math.imul(ah5, bh0);
  2975. lo = (lo + Math.imul(al4, bl1)) | 0;
  2976. mid = (mid + Math.imul(al4, bh1)) | 0;
  2977. mid = (mid + Math.imul(ah4, bl1)) | 0;
  2978. hi = (hi + Math.imul(ah4, bh1)) | 0;
  2979. lo = (lo + Math.imul(al3, bl2)) | 0;
  2980. mid = (mid + Math.imul(al3, bh2)) | 0;
  2981. mid = (mid + Math.imul(ah3, bl2)) | 0;
  2982. hi = (hi + Math.imul(ah3, bh2)) | 0;
  2983. lo = (lo + Math.imul(al2, bl3)) | 0;
  2984. mid = (mid + Math.imul(al2, bh3)) | 0;
  2985. mid = (mid + Math.imul(ah2, bl3)) | 0;
  2986. hi = (hi + Math.imul(ah2, bh3)) | 0;
  2987. lo = (lo + Math.imul(al1, bl4)) | 0;
  2988. mid = (mid + Math.imul(al1, bh4)) | 0;
  2989. mid = (mid + Math.imul(ah1, bl4)) | 0;
  2990. hi = (hi + Math.imul(ah1, bh4)) | 0;
  2991. lo = (lo + Math.imul(al0, bl5)) | 0;
  2992. mid = (mid + Math.imul(al0, bh5)) | 0;
  2993. mid = (mid + Math.imul(ah0, bl5)) | 0;
  2994. hi = (hi + Math.imul(ah0, bh5)) | 0;
  2995. var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  2996. c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
  2997. w5 &= 0x3ffffff;
  2998. /* k = 6 */
  2999. lo = Math.imul(al6, bl0);
  3000. mid = Math.imul(al6, bh0);
  3001. mid = (mid + Math.imul(ah6, bl0)) | 0;
  3002. hi = Math.imul(ah6, bh0);
  3003. lo = (lo + Math.imul(al5, bl1)) | 0;
  3004. mid = (mid + Math.imul(al5, bh1)) | 0;
  3005. mid = (mid + Math.imul(ah5, bl1)) | 0;
  3006. hi = (hi + Math.imul(ah5, bh1)) | 0;
  3007. lo = (lo + Math.imul(al4, bl2)) | 0;
  3008. mid = (mid + Math.imul(al4, bh2)) | 0;
  3009. mid = (mid + Math.imul(ah4, bl2)) | 0;
  3010. hi = (hi + Math.imul(ah4, bh2)) | 0;
  3011. lo = (lo + Math.imul(al3, bl3)) | 0;
  3012. mid = (mid + Math.imul(al3, bh3)) | 0;
  3013. mid = (mid + Math.imul(ah3, bl3)) | 0;
  3014. hi = (hi + Math.imul(ah3, bh3)) | 0;
  3015. lo = (lo + Math.imul(al2, bl4)) | 0;
  3016. mid = (mid + Math.imul(al2, bh4)) | 0;
  3017. mid = (mid + Math.imul(ah2, bl4)) | 0;
  3018. hi = (hi + Math.imul(ah2, bh4)) | 0;
  3019. lo = (lo + Math.imul(al1, bl5)) | 0;
  3020. mid = (mid + Math.imul(al1, bh5)) | 0;
  3021. mid = (mid + Math.imul(ah1, bl5)) | 0;
  3022. hi = (hi + Math.imul(ah1, bh5)) | 0;
  3023. lo = (lo + Math.imul(al0, bl6)) | 0;
  3024. mid = (mid + Math.imul(al0, bh6)) | 0;
  3025. mid = (mid + Math.imul(ah0, bl6)) | 0;
  3026. hi = (hi + Math.imul(ah0, bh6)) | 0;
  3027. var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  3028. c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
  3029. w6 &= 0x3ffffff;
  3030. /* k = 7 */
  3031. lo = Math.imul(al7, bl0);
  3032. mid = Math.imul(al7, bh0);
  3033. mid = (mid + Math.imul(ah7, bl0)) | 0;
  3034. hi = Math.imul(ah7, bh0);
  3035. lo = (lo + Math.imul(al6, bl1)) | 0;
  3036. mid = (mid + Math.imul(al6, bh1)) | 0;
  3037. mid = (mid + Math.imul(ah6, bl1)) | 0;
  3038. hi = (hi + Math.imul(ah6, bh1)) | 0;
  3039. lo = (lo + Math.imul(al5, bl2)) | 0;
  3040. mid = (mid + Math.imul(al5, bh2)) | 0;
  3041. mid = (mid + Math.imul(ah5, bl2)) | 0;
  3042. hi = (hi + Math.imul(ah5, bh2)) | 0;
  3043. lo = (lo + Math.imul(al4, bl3)) | 0;
  3044. mid = (mid + Math.imul(al4, bh3)) | 0;
  3045. mid = (mid + Math.imul(ah4, bl3)) | 0;
  3046. hi = (hi + Math.imul(ah4, bh3)) | 0;
  3047. lo = (lo + Math.imul(al3, bl4)) | 0;
  3048. mid = (mid + Math.imul(al3, bh4)) | 0;
  3049. mid = (mid + Math.imul(ah3, bl4)) | 0;
  3050. hi = (hi + Math.imul(ah3, bh4)) | 0;
  3051. lo = (lo + Math.imul(al2, bl5)) | 0;
  3052. mid = (mid + Math.imul(al2, bh5)) | 0;
  3053. mid = (mid + Math.imul(ah2, bl5)) | 0;
  3054. hi = (hi + Math.imul(ah2, bh5)) | 0;
  3055. lo = (lo + Math.imul(al1, bl6)) | 0;
  3056. mid = (mid + Math.imul(al1, bh6)) | 0;
  3057. mid = (mid + Math.imul(ah1, bl6)) | 0;
  3058. hi = (hi + Math.imul(ah1, bh6)) | 0;
  3059. lo = (lo + Math.imul(al0, bl7)) | 0;
  3060. mid = (mid + Math.imul(al0, bh7)) | 0;
  3061. mid = (mid + Math.imul(ah0, bl7)) | 0;
  3062. hi = (hi + Math.imul(ah0, bh7)) | 0;
  3063. var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  3064. c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
  3065. w7 &= 0x3ffffff;
  3066. /* k = 8 */
  3067. lo = Math.imul(al8, bl0);
  3068. mid = Math.imul(al8, bh0);
  3069. mid = (mid + Math.imul(ah8, bl0)) | 0;
  3070. hi = Math.imul(ah8, bh0);
  3071. lo = (lo + Math.imul(al7, bl1)) | 0;
  3072. mid = (mid + Math.imul(al7, bh1)) | 0;
  3073. mid = (mid + Math.imul(ah7, bl1)) | 0;
  3074. hi = (hi + Math.imul(ah7, bh1)) | 0;
  3075. lo = (lo + Math.imul(al6, bl2)) | 0;
  3076. mid = (mid + Math.imul(al6, bh2)) | 0;
  3077. mid = (mid + Math.imul(ah6, bl2)) | 0;
  3078. hi = (hi + Math.imul(ah6, bh2)) | 0;
  3079. lo = (lo + Math.imul(al5, bl3)) | 0;
  3080. mid = (mid + Math.imul(al5, bh3)) | 0;
  3081. mid = (mid + Math.imul(ah5, bl3)) | 0;
  3082. hi = (hi + Math.imul(ah5, bh3)) | 0;
  3083. lo = (lo + Math.imul(al4, bl4)) | 0;
  3084. mid = (mid + Math.imul(al4, bh4)) | 0;
  3085. mid = (mid + Math.imul(ah4, bl4)) | 0;
  3086. hi = (hi + Math.imul(ah4, bh4)) | 0;
  3087. lo = (lo + Math.imul(al3, bl5)) | 0;
  3088. mid = (mid + Math.imul(al3, bh5)) | 0;
  3089. mid = (mid + Math.imul(ah3, bl5)) | 0;
  3090. hi = (hi + Math.imul(ah3, bh5)) | 0;
  3091. lo = (lo + Math.imul(al2, bl6)) | 0;
  3092. mid = (mid + Math.imul(al2, bh6)) | 0;
  3093. mid = (mid + Math.imul(ah2, bl6)) | 0;
  3094. hi = (hi + Math.imul(ah2, bh6)) | 0;
  3095. lo = (lo + Math.imul(al1, bl7)) | 0;
  3096. mid = (mid + Math.imul(al1, bh7)) | 0;
  3097. mid = (mid + Math.imul(ah1, bl7)) | 0;
  3098. hi = (hi + Math.imul(ah1, bh7)) | 0;
  3099. lo = (lo + Math.imul(al0, bl8)) | 0;
  3100. mid = (mid + Math.imul(al0, bh8)) | 0;
  3101. mid = (mid + Math.imul(ah0, bl8)) | 0;
  3102. hi = (hi + Math.imul(ah0, bh8)) | 0;
  3103. var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  3104. c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
  3105. w8 &= 0x3ffffff;
  3106. /* k = 9 */
  3107. lo = Math.imul(al9, bl0);
  3108. mid = Math.imul(al9, bh0);
  3109. mid = (mid + Math.imul(ah9, bl0)) | 0;
  3110. hi = Math.imul(ah9, bh0);
  3111. lo = (lo + Math.imul(al8, bl1)) | 0;
  3112. mid = (mid + Math.imul(al8, bh1)) | 0;
  3113. mid = (mid + Math.imul(ah8, bl1)) | 0;
  3114. hi = (hi + Math.imul(ah8, bh1)) | 0;
  3115. lo = (lo + Math.imul(al7, bl2)) | 0;
  3116. mid = (mid + Math.imul(al7, bh2)) | 0;
  3117. mid = (mid + Math.imul(ah7, bl2)) | 0;
  3118. hi = (hi + Math.imul(ah7, bh2)) | 0;
  3119. lo = (lo + Math.imul(al6, bl3)) | 0;
  3120. mid = (mid + Math.imul(al6, bh3)) | 0;
  3121. mid = (mid + Math.imul(ah6, bl3)) | 0;
  3122. hi = (hi + Math.imul(ah6, bh3)) | 0;
  3123. lo = (lo + Math.imul(al5, bl4)) | 0;
  3124. mid = (mid + Math.imul(al5, bh4)) | 0;
  3125. mid = (mid + Math.imul(ah5, bl4)) | 0;
  3126. hi = (hi + Math.imul(ah5, bh4)) | 0;
  3127. lo = (lo + Math.imul(al4, bl5)) | 0;
  3128. mid = (mid + Math.imul(al4, bh5)) | 0;
  3129. mid = (mid + Math.imul(ah4, bl5)) | 0;
  3130. hi = (hi + Math.imul(ah4, bh5)) | 0;
  3131. lo = (lo + Math.imul(al3, bl6)) | 0;
  3132. mid = (mid + Math.imul(al3, bh6)) | 0;
  3133. mid = (mid + Math.imul(ah3, bl6)) | 0;
  3134. hi = (hi + Math.imul(ah3, bh6)) | 0;
  3135. lo = (lo + Math.imul(al2, bl7)) | 0;
  3136. mid = (mid + Math.imul(al2, bh7)) | 0;
  3137. mid = (mid + Math.imul(ah2, bl7)) | 0;
  3138. hi = (hi + Math.imul(ah2, bh7)) | 0;
  3139. lo = (lo + Math.imul(al1, bl8)) | 0;
  3140. mid = (mid + Math.imul(al1, bh8)) | 0;
  3141. mid = (mid + Math.imul(ah1, bl8)) | 0;
  3142. hi = (hi + Math.imul(ah1, bh8)) | 0;
  3143. lo = (lo + Math.imul(al0, bl9)) | 0;
  3144. mid = (mid + Math.imul(al0, bh9)) | 0;
  3145. mid = (mid + Math.imul(ah0, bl9)) | 0;
  3146. hi = (hi + Math.imul(ah0, bh9)) | 0;
  3147. var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  3148. c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
  3149. w9 &= 0x3ffffff;
  3150. /* k = 10 */
  3151. lo = Math.imul(al9, bl1);
  3152. mid = Math.imul(al9, bh1);
  3153. mid = (mid + Math.imul(ah9, bl1)) | 0;
  3154. hi = Math.imul(ah9, bh1);
  3155. lo = (lo + Math.imul(al8, bl2)) | 0;
  3156. mid = (mid + Math.imul(al8, bh2)) | 0;
  3157. mid = (mid + Math.imul(ah8, bl2)) | 0;
  3158. hi = (hi + Math.imul(ah8, bh2)) | 0;
  3159. lo = (lo + Math.imul(al7, bl3)) | 0;
  3160. mid = (mid + Math.imul(al7, bh3)) | 0;
  3161. mid = (mid + Math.imul(ah7, bl3)) | 0;
  3162. hi = (hi + Math.imul(ah7, bh3)) | 0;
  3163. lo = (lo + Math.imul(al6, bl4)) | 0;
  3164. mid = (mid + Math.imul(al6, bh4)) | 0;
  3165. mid = (mid + Math.imul(ah6, bl4)) | 0;
  3166. hi = (hi + Math.imul(ah6, bh4)) | 0;
  3167. lo = (lo + Math.imul(al5, bl5)) | 0;
  3168. mid = (mid + Math.imul(al5, bh5)) | 0;
  3169. mid = (mid + Math.imul(ah5, bl5)) | 0;
  3170. hi = (hi + Math.imul(ah5, bh5)) | 0;
  3171. lo = (lo + Math.imul(al4, bl6)) | 0;
  3172. mid = (mid + Math.imul(al4, bh6)) | 0;
  3173. mid = (mid + Math.imul(ah4, bl6)) | 0;
  3174. hi = (hi + Math.imul(ah4, bh6)) | 0;
  3175. lo = (lo + Math.imul(al3, bl7)) | 0;
  3176. mid = (mid + Math.imul(al3, bh7)) | 0;
  3177. mid = (mid + Math.imul(ah3, bl7)) | 0;
  3178. hi = (hi + Math.imul(ah3, bh7)) | 0;
  3179. lo = (lo + Math.imul(al2, bl8)) | 0;
  3180. mid = (mid + Math.imul(al2, bh8)) | 0;
  3181. mid = (mid + Math.imul(ah2, bl8)) | 0;
  3182. hi = (hi + Math.imul(ah2, bh8)) | 0;
  3183. lo = (lo + Math.imul(al1, bl9)) | 0;
  3184. mid = (mid + Math.imul(al1, bh9)) | 0;
  3185. mid = (mid + Math.imul(ah1, bl9)) | 0;
  3186. hi = (hi + Math.imul(ah1, bh9)) | 0;
  3187. var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  3188. c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
  3189. w10 &= 0x3ffffff;
  3190. /* k = 11 */
  3191. lo = Math.imul(al9, bl2);
  3192. mid = Math.imul(al9, bh2);
  3193. mid = (mid + Math.imul(ah9, bl2)) | 0;
  3194. hi = Math.imul(ah9, bh2);
  3195. lo = (lo + Math.imul(al8, bl3)) | 0;
  3196. mid = (mid + Math.imul(al8, bh3)) | 0;
  3197. mid = (mid + Math.imul(ah8, bl3)) | 0;
  3198. hi = (hi + Math.imul(ah8, bh3)) | 0;
  3199. lo = (lo + Math.imul(al7, bl4)) | 0;
  3200. mid = (mid + Math.imul(al7, bh4)) | 0;
  3201. mid = (mid + Math.imul(ah7, bl4)) | 0;
  3202. hi = (hi + Math.imul(ah7, bh4)) | 0;
  3203. lo = (lo + Math.imul(al6, bl5)) | 0;
  3204. mid = (mid + Math.imul(al6, bh5)) | 0;
  3205. mid = (mid + Math.imul(ah6, bl5)) | 0;
  3206. hi = (hi + Math.imul(ah6, bh5)) | 0;
  3207. lo = (lo + Math.imul(al5, bl6)) | 0;
  3208. mid = (mid + Math.imul(al5, bh6)) | 0;
  3209. mid = (mid + Math.imul(ah5, bl6)) | 0;
  3210. hi = (hi + Math.imul(ah5, bh6)) | 0;
  3211. lo = (lo + Math.imul(al4, bl7)) | 0;
  3212. mid = (mid + Math.imul(al4, bh7)) | 0;
  3213. mid = (mid + Math.imul(ah4, bl7)) | 0;
  3214. hi = (hi + Math.imul(ah4, bh7)) | 0;
  3215. lo = (lo + Math.imul(al3, bl8)) | 0;
  3216. mid = (mid + Math.imul(al3, bh8)) | 0;
  3217. mid = (mid + Math.imul(ah3, bl8)) | 0;
  3218. hi = (hi + Math.imul(ah3, bh8)) | 0;
  3219. lo = (lo + Math.imul(al2, bl9)) | 0;
  3220. mid = (mid + Math.imul(al2, bh9)) | 0;
  3221. mid = (mid + Math.imul(ah2, bl9)) | 0;
  3222. hi = (hi + Math.imul(ah2, bh9)) | 0;
  3223. var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  3224. c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
  3225. w11 &= 0x3ffffff;
  3226. /* k = 12 */
  3227. lo = Math.imul(al9, bl3);
  3228. mid = Math.imul(al9, bh3);
  3229. mid = (mid + Math.imul(ah9, bl3)) | 0;
  3230. hi = Math.imul(ah9, bh3);
  3231. lo = (lo + Math.imul(al8, bl4)) | 0;
  3232. mid = (mid + Math.imul(al8, bh4)) | 0;
  3233. mid = (mid + Math.imul(ah8, bl4)) | 0;
  3234. hi = (hi + Math.imul(ah8, bh4)) | 0;
  3235. lo = (lo + Math.imul(al7, bl5)) | 0;
  3236. mid = (mid + Math.imul(al7, bh5)) | 0;
  3237. mid = (mid + Math.imul(ah7, bl5)) | 0;
  3238. hi = (hi + Math.imul(ah7, bh5)) | 0;
  3239. lo = (lo + Math.imul(al6, bl6)) | 0;
  3240. mid = (mid + Math.imul(al6, bh6)) | 0;
  3241. mid = (mid + Math.imul(ah6, bl6)) | 0;
  3242. hi = (hi + Math.imul(ah6, bh6)) | 0;
  3243. lo = (lo + Math.imul(al5, bl7)) | 0;
  3244. mid = (mid + Math.imul(al5, bh7)) | 0;
  3245. mid = (mid + Math.imul(ah5, bl7)) | 0;
  3246. hi = (hi + Math.imul(ah5, bh7)) | 0;
  3247. lo = (lo + Math.imul(al4, bl8)) | 0;
  3248. mid = (mid + Math.imul(al4, bh8)) | 0;
  3249. mid = (mid + Math.imul(ah4, bl8)) | 0;
  3250. hi = (hi + Math.imul(ah4, bh8)) | 0;
  3251. lo = (lo + Math.imul(al3, bl9)) | 0;
  3252. mid = (mid + Math.imul(al3, bh9)) | 0;
  3253. mid = (mid + Math.imul(ah3, bl9)) | 0;
  3254. hi = (hi + Math.imul(ah3, bh9)) | 0;
  3255. var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  3256. c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
  3257. w12 &= 0x3ffffff;
  3258. /* k = 13 */
  3259. lo = Math.imul(al9, bl4);
  3260. mid = Math.imul(al9, bh4);
  3261. mid = (mid + Math.imul(ah9, bl4)) | 0;
  3262. hi = Math.imul(ah9, bh4);
  3263. lo = (lo + Math.imul(al8, bl5)) | 0;
  3264. mid = (mid + Math.imul(al8, bh5)) | 0;
  3265. mid = (mid + Math.imul(ah8, bl5)) | 0;
  3266. hi = (hi + Math.imul(ah8, bh5)) | 0;
  3267. lo = (lo + Math.imul(al7, bl6)) | 0;
  3268. mid = (mid + Math.imul(al7, bh6)) | 0;
  3269. mid = (mid + Math.imul(ah7, bl6)) | 0;
  3270. hi = (hi + Math.imul(ah7, bh6)) | 0;
  3271. lo = (lo + Math.imul(al6, bl7)) | 0;
  3272. mid = (mid + Math.imul(al6, bh7)) | 0;
  3273. mid = (mid + Math.imul(ah6, bl7)) | 0;
  3274. hi = (hi + Math.imul(ah6, bh7)) | 0;
  3275. lo = (lo + Math.imul(al5, bl8)) | 0;
  3276. mid = (mid + Math.imul(al5, bh8)) | 0;
  3277. mid = (mid + Math.imul(ah5, bl8)) | 0;
  3278. hi = (hi + Math.imul(ah5, bh8)) | 0;
  3279. lo = (lo + Math.imul(al4, bl9)) | 0;
  3280. mid = (mid + Math.imul(al4, bh9)) | 0;
  3281. mid = (mid + Math.imul(ah4, bl9)) | 0;
  3282. hi = (hi + Math.imul(ah4, bh9)) | 0;
  3283. var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  3284. c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
  3285. w13 &= 0x3ffffff;
  3286. /* k = 14 */
  3287. lo = Math.imul(al9, bl5);
  3288. mid = Math.imul(al9, bh5);
  3289. mid = (mid + Math.imul(ah9, bl5)) | 0;
  3290. hi = Math.imul(ah9, bh5);
  3291. lo = (lo + Math.imul(al8, bl6)) | 0;
  3292. mid = (mid + Math.imul(al8, bh6)) | 0;
  3293. mid = (mid + Math.imul(ah8, bl6)) | 0;
  3294. hi = (hi + Math.imul(ah8, bh6)) | 0;
  3295. lo = (lo + Math.imul(al7, bl7)) | 0;
  3296. mid = (mid + Math.imul(al7, bh7)) | 0;
  3297. mid = (mid + Math.imul(ah7, bl7)) | 0;
  3298. hi = (hi + Math.imul(ah7, bh7)) | 0;
  3299. lo = (lo + Math.imul(al6, bl8)) | 0;
  3300. mid = (mid + Math.imul(al6, bh8)) | 0;
  3301. mid = (mid + Math.imul(ah6, bl8)) | 0;
  3302. hi = (hi + Math.imul(ah6, bh8)) | 0;
  3303. lo = (lo + Math.imul(al5, bl9)) | 0;
  3304. mid = (mid + Math.imul(al5, bh9)) | 0;
  3305. mid = (mid + Math.imul(ah5, bl9)) | 0;
  3306. hi = (hi + Math.imul(ah5, bh9)) | 0;
  3307. var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  3308. c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
  3309. w14 &= 0x3ffffff;
  3310. /* k = 15 */
  3311. lo = Math.imul(al9, bl6);
  3312. mid = Math.imul(al9, bh6);
  3313. mid = (mid + Math.imul(ah9, bl6)) | 0;
  3314. hi = Math.imul(ah9, bh6);
  3315. lo = (lo + Math.imul(al8, bl7)) | 0;
  3316. mid = (mid + Math.imul(al8, bh7)) | 0;
  3317. mid = (mid + Math.imul(ah8, bl7)) | 0;
  3318. hi = (hi + Math.imul(ah8, bh7)) | 0;
  3319. lo = (lo + Math.imul(al7, bl8)) | 0;
  3320. mid = (mid + Math.imul(al7, bh8)) | 0;
  3321. mid = (mid + Math.imul(ah7, bl8)) | 0;
  3322. hi = (hi + Math.imul(ah7, bh8)) | 0;
  3323. lo = (lo + Math.imul(al6, bl9)) | 0;
  3324. mid = (mid + Math.imul(al6, bh9)) | 0;
  3325. mid = (mid + Math.imul(ah6, bl9)) | 0;
  3326. hi = (hi + Math.imul(ah6, bh9)) | 0;
  3327. var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  3328. c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
  3329. w15 &= 0x3ffffff;
  3330. /* k = 16 */
  3331. lo = Math.imul(al9, bl7);
  3332. mid = Math.imul(al9, bh7);
  3333. mid = (mid + Math.imul(ah9, bl7)) | 0;
  3334. hi = Math.imul(ah9, bh7);
  3335. lo = (lo + Math.imul(al8, bl8)) | 0;
  3336. mid = (mid + Math.imul(al8, bh8)) | 0;
  3337. mid = (mid + Math.imul(ah8, bl8)) | 0;
  3338. hi = (hi + Math.imul(ah8, bh8)) | 0;
  3339. lo = (lo + Math.imul(al7, bl9)) | 0;
  3340. mid = (mid + Math.imul(al7, bh9)) | 0;
  3341. mid = (mid + Math.imul(ah7, bl9)) | 0;
  3342. hi = (hi + Math.imul(ah7, bh9)) | 0;
  3343. var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  3344. c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
  3345. w16 &= 0x3ffffff;
  3346. /* k = 17 */
  3347. lo = Math.imul(al9, bl8);
  3348. mid = Math.imul(al9, bh8);
  3349. mid = (mid + Math.imul(ah9, bl8)) | 0;
  3350. hi = Math.imul(ah9, bh8);
  3351. lo = (lo + Math.imul(al8, bl9)) | 0;
  3352. mid = (mid + Math.imul(al8, bh9)) | 0;
  3353. mid = (mid + Math.imul(ah8, bl9)) | 0;
  3354. hi = (hi + Math.imul(ah8, bh9)) | 0;
  3355. var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  3356. c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
  3357. w17 &= 0x3ffffff;
  3358. /* k = 18 */
  3359. lo = Math.imul(al9, bl9);
  3360. mid = Math.imul(al9, bh9);
  3361. mid = (mid + Math.imul(ah9, bl9)) | 0;
  3362. hi = Math.imul(ah9, bh9);
  3363. var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  3364. c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
  3365. w18 &= 0x3ffffff;
  3366. o[0] = w0;
  3367. o[1] = w1;
  3368. o[2] = w2;
  3369. o[3] = w3;
  3370. o[4] = w4;
  3371. o[5] = w5;
  3372. o[6] = w6;
  3373. o[7] = w7;
  3374. o[8] = w8;
  3375. o[9] = w9;
  3376. o[10] = w10;
  3377. o[11] = w11;
  3378. o[12] = w12;
  3379. o[13] = w13;
  3380. o[14] = w14;
  3381. o[15] = w15;
  3382. o[16] = w16;
  3383. o[17] = w17;
  3384. o[18] = w18;
  3385. if (c !== 0) {
  3386. o[19] = c;
  3387. out.length++;
  3388. }
  3389. return out;
  3390. };
  3391. // Polyfill comb
  3392. if (!Math.imul) {
  3393. comb10MulTo = smallMulTo;
  3394. }
  3395. function bigMulTo (self, num, out) {
  3396. out.negative = num.negative ^ self.negative;
  3397. out.length = self.length + num.length;
  3398. var carry = 0;
  3399. var hncarry = 0;
  3400. for (var k = 0; k < out.length - 1; k++) {
  3401. // Sum all words with the same `i + j = k` and accumulate `ncarry`,
  3402. // note that ncarry could be >= 0x3ffffff
  3403. var ncarry = hncarry;
  3404. hncarry = 0;
  3405. var rword = carry & 0x3ffffff;
  3406. var maxJ = Math.min(k, num.length - 1);
  3407. for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
  3408. var i = k - j;
  3409. var a = self.words[i] | 0;
  3410. var b = num.words[j] | 0;
  3411. var r = a * b;
  3412. var lo = r & 0x3ffffff;
  3413. ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
  3414. lo = (lo + rword) | 0;
  3415. rword = lo & 0x3ffffff;
  3416. ncarry = (ncarry + (lo >>> 26)) | 0;
  3417. hncarry += ncarry >>> 26;
  3418. ncarry &= 0x3ffffff;
  3419. }
  3420. out.words[k] = rword;
  3421. carry = ncarry;
  3422. ncarry = hncarry;
  3423. }
  3424. if (carry !== 0) {
  3425. out.words[k] = carry;
  3426. } else {
  3427. out.length--;
  3428. }
  3429. return out.strip();
  3430. }
  3431. function jumboMulTo (self, num, out) {
  3432. var fftm = new FFTM();
  3433. return fftm.mulp(self, num, out);
  3434. }
  3435. BN.prototype.mulTo = function mulTo (num, out) {
  3436. var res;
  3437. var len = this.length + num.length;
  3438. if (this.length === 10 && num.length === 10) {
  3439. res = comb10MulTo(this, num, out);
  3440. } else if (len < 63) {
  3441. res = smallMulTo(this, num, out);
  3442. } else if (len < 1024) {
  3443. res = bigMulTo(this, num, out);
  3444. } else {
  3445. res = jumboMulTo(this, num, out);
  3446. }
  3447. return res;
  3448. };
  3449. // Cooley-Tukey algorithm for FFT
  3450. // slightly revisited to rely on looping instead of recursion
  3451. function FFTM (x, y) {
  3452. this.x = x;
  3453. this.y = y;
  3454. }
  3455. FFTM.prototype.makeRBT = function makeRBT (N) {
  3456. var t = new Array(N);
  3457. var l = BN.prototype._countBits(N) - 1;
  3458. for (var i = 0; i < N; i++) {
  3459. t[i] = this.revBin(i, l, N);
  3460. }
  3461. return t;
  3462. };
  3463. // Returns binary-reversed representation of `x`
  3464. FFTM.prototype.revBin = function revBin (x, l, N) {
  3465. if (x === 0 || x === N - 1) return x;
  3466. var rb = 0;
  3467. for (var i = 0; i < l; i++) {
  3468. rb |= (x & 1) << (l - i - 1);
  3469. x >>= 1;
  3470. }
  3471. return rb;
  3472. };
  3473. // Performs "tweedling" phase, therefore 'emulating'
  3474. // behaviour of the recursive algorithm
  3475. FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
  3476. for (var i = 0; i < N; i++) {
  3477. rtws[i] = rws[rbt[i]];
  3478. itws[i] = iws[rbt[i]];
  3479. }
  3480. };
  3481. FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
  3482. this.permute(rbt, rws, iws, rtws, itws, N);
  3483. for (var s = 1; s < N; s <<= 1) {
  3484. var l = s << 1;
  3485. var rtwdf = Math.cos(2 * Math.PI / l);
  3486. var itwdf = Math.sin(2 * Math.PI / l);
  3487. for (var p = 0; p < N; p += l) {
  3488. var rtwdf_ = rtwdf;
  3489. var itwdf_ = itwdf;
  3490. for (var j = 0; j < s; j++) {
  3491. var re = rtws[p + j];
  3492. var ie = itws[p + j];
  3493. var ro = rtws[p + j + s];
  3494. var io = itws[p + j + s];
  3495. var rx = rtwdf_ * ro - itwdf_ * io;
  3496. io = rtwdf_ * io + itwdf_ * ro;
  3497. ro = rx;
  3498. rtws[p + j] = re + ro;
  3499. itws[p + j] = ie + io;
  3500. rtws[p + j + s] = re - ro;
  3501. itws[p + j + s] = ie - io;
  3502. /* jshint maxdepth : false */
  3503. if (j !== l) {
  3504. rx = rtwdf * rtwdf_ - itwdf * itwdf_;
  3505. itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
  3506. rtwdf_ = rx;
  3507. }
  3508. }
  3509. }
  3510. }
  3511. };
  3512. FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
  3513. var N = Math.max(m, n) | 1;
  3514. var odd = N & 1;
  3515. var i = 0;
  3516. for (N = N / 2 | 0; N; N = N >>> 1) {
  3517. i++;
  3518. }
  3519. return 1 << i + 1 + odd;
  3520. };
  3521. FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
  3522. if (N <= 1) return;
  3523. for (var i = 0; i < N / 2; i++) {
  3524. var t = rws[i];
  3525. rws[i] = rws[N - i - 1];
  3526. rws[N - i - 1] = t;
  3527. t = iws[i];
  3528. iws[i] = -iws[N - i - 1];
  3529. iws[N - i - 1] = -t;
  3530. }
  3531. };
  3532. FFTM.prototype.normalize13b = function normalize13b (ws, N) {
  3533. var carry = 0;
  3534. for (var i = 0; i < N / 2; i++) {
  3535. var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
  3536. Math.round(ws[2 * i] / N) +
  3537. carry;
  3538. ws[i] = w & 0x3ffffff;
  3539. if (w < 0x4000000) {
  3540. carry = 0;
  3541. } else {
  3542. carry = w / 0x4000000 | 0;
  3543. }
  3544. }
  3545. return ws;
  3546. };
  3547. FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
  3548. var carry = 0;
  3549. for (var i = 0; i < len; i++) {
  3550. carry = carry + (ws[i] | 0);
  3551. rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
  3552. rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
  3553. }
  3554. // Pad with zeroes
  3555. for (i = 2 * len; i < N; ++i) {
  3556. rws[i] = 0;
  3557. }
  3558. assert(carry === 0);
  3559. assert((carry & ~0x1fff) === 0);
  3560. };
  3561. FFTM.prototype.stub = function stub (N) {
  3562. var ph = new Array(N);
  3563. for (var i = 0; i < N; i++) {
  3564. ph[i] = 0;
  3565. }
  3566. return ph;
  3567. };
  3568. FFTM.prototype.mulp = function mulp (x, y, out) {
  3569. var N = 2 * this.guessLen13b(x.length, y.length);
  3570. var rbt = this.makeRBT(N);
  3571. var _ = this.stub(N);
  3572. var rws = new Array(N);
  3573. var rwst = new Array(N);
  3574. var iwst = new Array(N);
  3575. var nrws = new Array(N);
  3576. var nrwst = new Array(N);
  3577. var niwst = new Array(N);
  3578. var rmws = out.words;
  3579. rmws.length = N;
  3580. this.convert13b(x.words, x.length, rws, N);
  3581. this.convert13b(y.words, y.length, nrws, N);
  3582. this.transform(rws, _, rwst, iwst, N, rbt);
  3583. this.transform(nrws, _, nrwst, niwst, N, rbt);
  3584. for (var i = 0; i < N; i++) {
  3585. var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
  3586. iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
  3587. rwst[i] = rx;
  3588. }
  3589. this.conjugate(rwst, iwst, N);
  3590. this.transform(rwst, iwst, rmws, _, N, rbt);
  3591. this.conjugate(rmws, _, N);
  3592. this.normalize13b(rmws, N);
  3593. out.negative = x.negative ^ y.negative;
  3594. out.length = x.length + y.length;
  3595. return out.strip();
  3596. };
  3597. // Multiply `this` by `num`
  3598. BN.prototype.mul = function mul (num) {
  3599. var out = new BN(null);
  3600. out.words = new Array(this.length + num.length);
  3601. return this.mulTo(num, out);
  3602. };
  3603. // Multiply employing FFT
  3604. BN.prototype.mulf = function mulf (num) {
  3605. var out = new BN(null);
  3606. out.words = new Array(this.length + num.length);
  3607. return jumboMulTo(this, num, out);
  3608. };
  3609. // In-place Multiplication
  3610. BN.prototype.imul = function imul (num) {
  3611. return this.clone().mulTo(num, this);
  3612. };
  3613. BN.prototype.imuln = function imuln (num) {
  3614. assert(typeof num === 'number');
  3615. assert(num < 0x4000000);
  3616. // Carry
  3617. var carry = 0;
  3618. for (var i = 0; i < this.length; i++) {
  3619. var w = (this.words[i] | 0) * num;
  3620. var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
  3621. carry >>= 26;
  3622. carry += (w / 0x4000000) | 0;
  3623. // NOTE: lo is 27bit maximum
  3624. carry += lo >>> 26;
  3625. this.words[i] = lo & 0x3ffffff;
  3626. }
  3627. if (carry !== 0) {
  3628. this.words[i] = carry;
  3629. this.length++;
  3630. }
  3631. return this;
  3632. };
  3633. BN.prototype.muln = function muln (num) {
  3634. return this.clone().imuln(num);
  3635. };
  3636. // `this` * `this`
  3637. BN.prototype.sqr = function sqr () {
  3638. return this.mul(this);
  3639. };
  3640. // `this` * `this` in-place
  3641. BN.prototype.isqr = function isqr () {
  3642. return this.imul(this.clone());
  3643. };
  3644. // Math.pow(`this`, `num`)
  3645. BN.prototype.pow = function pow (num) {
  3646. var w = toBitArray(num);
  3647. if (w.length === 0) return new BN(1);
  3648. // Skip leading zeroes
  3649. var res = this;
  3650. for (var i = 0; i < w.length; i++, res = res.sqr()) {
  3651. if (w[i] !== 0) break;
  3652. }
  3653. if (++i < w.length) {
  3654. for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
  3655. if (w[i] === 0) continue;
  3656. res = res.mul(q);
  3657. }
  3658. }
  3659. return res;
  3660. };
  3661. // Shift-left in-place
  3662. BN.prototype.iushln = function iushln (bits) {
  3663. assert(typeof bits === 'number' && bits >= 0);
  3664. var r = bits % 26;
  3665. var s = (bits - r) / 26;
  3666. var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
  3667. var i;
  3668. if (r !== 0) {
  3669. var carry = 0;
  3670. for (i = 0; i < this.length; i++) {
  3671. var newCarry = this.words[i] & carryMask;
  3672. var c = ((this.words[i] | 0) - newCarry) << r;
  3673. this.words[i] = c | carry;
  3674. carry = newCarry >>> (26 - r);
  3675. }
  3676. if (carry) {
  3677. this.words[i] = carry;
  3678. this.length++;
  3679. }
  3680. }
  3681. if (s !== 0) {
  3682. for (i = this.length - 1; i >= 0; i--) {
  3683. this.words[i + s] = this.words[i];
  3684. }
  3685. for (i = 0; i < s; i++) {
  3686. this.words[i] = 0;
  3687. }
  3688. this.length += s;
  3689. }
  3690. return this.strip();
  3691. };
  3692. BN.prototype.ishln = function ishln (bits) {
  3693. // TODO(indutny): implement me
  3694. assert(this.negative === 0);
  3695. return this.iushln(bits);
  3696. };
  3697. // Shift-right in-place
  3698. // NOTE: `hint` is a lowest bit before trailing zeroes
  3699. // NOTE: if `extended` is present - it will be filled with destroyed bits
  3700. BN.prototype.iushrn = function iushrn (bits, hint, extended) {
  3701. assert(typeof bits === 'number' && bits >= 0);
  3702. var h;
  3703. if (hint) {
  3704. h = (hint - (hint % 26)) / 26;
  3705. } else {
  3706. h = 0;
  3707. }
  3708. var r = bits % 26;
  3709. var s = Math.min((bits - r) / 26, this.length);
  3710. var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
  3711. var maskedWords = extended;
  3712. h -= s;
  3713. h = Math.max(0, h);
  3714. // Extended mode, copy masked part
  3715. if (maskedWords) {
  3716. for (var i = 0; i < s; i++) {
  3717. maskedWords.words[i] = this.words[i];
  3718. }
  3719. maskedWords.length = s;
  3720. }
  3721. if (s === 0) {
  3722. // No-op, we should not move anything at all
  3723. } else if (this.length > s) {
  3724. this.length -= s;
  3725. for (i = 0; i < this.length; i++) {
  3726. this.words[i] = this.words[i + s];
  3727. }
  3728. } else {
  3729. this.words[0] = 0;
  3730. this.length = 1;
  3731. }
  3732. var carry = 0;
  3733. for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
  3734. var word = this.words[i] | 0;
  3735. this.words[i] = (carry << (26 - r)) | (word >>> r);
  3736. carry = word & mask;
  3737. }
  3738. // Push carried bits as a mask
  3739. if (maskedWords && carry !== 0) {
  3740. maskedWords.words[maskedWords.length++] = carry;
  3741. }
  3742. if (this.length === 0) {
  3743. this.words[0] = 0;
  3744. this.length = 1;
  3745. }
  3746. return this.strip();
  3747. };
  3748. BN.prototype.ishrn = function ishrn (bits, hint, extended) {
  3749. // TODO(indutny): implement me
  3750. assert(this.negative === 0);
  3751. return this.iushrn(bits, hint, extended);
  3752. };
  3753. // Shift-left
  3754. BN.prototype.shln = function shln (bits) {
  3755. return this.clone().ishln(bits);
  3756. };
  3757. BN.prototype.ushln = function ushln (bits) {
  3758. return this.clone().iushln(bits);
  3759. };
  3760. // Shift-right
  3761. BN.prototype.shrn = function shrn (bits) {
  3762. return this.clone().ishrn(bits);
  3763. };
  3764. BN.prototype.ushrn = function ushrn (bits) {
  3765. return this.clone().iushrn(bits);
  3766. };
  3767. // Test if n bit is set
  3768. BN.prototype.testn = function testn (bit) {
  3769. assert(typeof bit === 'number' && bit >= 0);
  3770. var r = bit % 26;
  3771. var s = (bit - r) / 26;
  3772. var q = 1 << r;
  3773. // Fast case: bit is much higher than all existing words
  3774. if (this.length <= s) return false;
  3775. // Check bit and return
  3776. var w = this.words[s];
  3777. return !!(w & q);
  3778. };
  3779. // Return only lowers bits of number (in-place)
  3780. BN.prototype.imaskn = function imaskn (bits) {
  3781. assert(typeof bits === 'number' && bits >= 0);
  3782. var r = bits % 26;
  3783. var s = (bits - r) / 26;
  3784. assert(this.negative === 0, 'imaskn works only with positive numbers');
  3785. if (this.length <= s) {
  3786. return this;
  3787. }
  3788. if (r !== 0) {
  3789. s++;
  3790. }
  3791. this.length = Math.min(s, this.length);
  3792. if (r !== 0) {
  3793. var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
  3794. this.words[this.length - 1] &= mask;
  3795. }
  3796. return this.strip();
  3797. };
  3798. // Return only lowers bits of number
  3799. BN.prototype.maskn = function maskn (bits) {
  3800. return this.clone().imaskn(bits);
  3801. };
  3802. // Add plain number `num` to `this`
  3803. BN.prototype.iaddn = function iaddn (num) {
  3804. assert(typeof num === 'number');
  3805. assert(num < 0x4000000);
  3806. if (num < 0) return this.isubn(-num);
  3807. // Possible sign change
  3808. if (this.negative !== 0) {
  3809. if (this.length === 1 && (this.words[0] | 0) < num) {
  3810. this.words[0] = num - (this.words[0] | 0);
  3811. this.negative = 0;
  3812. return this;
  3813. }
  3814. this.negative = 0;
  3815. this.isubn(num);
  3816. this.negative = 1;
  3817. return this;
  3818. }
  3819. // Add without checks
  3820. return this._iaddn(num);
  3821. };
  3822. BN.prototype._iaddn = function _iaddn (num) {
  3823. this.words[0] += num;
  3824. // Carry
  3825. for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
  3826. this.words[i] -= 0x4000000;
  3827. if (i === this.length - 1) {
  3828. this.words[i + 1] = 1;
  3829. } else {
  3830. this.words[i + 1]++;
  3831. }
  3832. }
  3833. this.length = Math.max(this.length, i + 1);
  3834. return this;
  3835. };
  3836. // Subtract plain number `num` from `this`
  3837. BN.prototype.isubn = function isubn (num) {
  3838. assert(typeof num === 'number');
  3839. assert(num < 0x4000000);
  3840. if (num < 0) return this.iaddn(-num);
  3841. if (this.negative !== 0) {
  3842. this.negative = 0;
  3843. this.iaddn(num);
  3844. this.negative = 1;
  3845. return this;
  3846. }
  3847. this.words[0] -= num;
  3848. if (this.length === 1 && this.words[0] < 0) {
  3849. this.words[0] = -this.words[0];
  3850. this.negative = 1;
  3851. } else {
  3852. // Carry
  3853. for (var i = 0; i < this.length && this.words[i] < 0; i++) {
  3854. this.words[i] += 0x4000000;
  3855. this.words[i + 1] -= 1;
  3856. }
  3857. }
  3858. return this.strip();
  3859. };
  3860. BN.prototype.addn = function addn (num) {
  3861. return this.clone().iaddn(num);
  3862. };
  3863. BN.prototype.subn = function subn (num) {
  3864. return this.clone().isubn(num);
  3865. };
  3866. BN.prototype.iabs = function iabs () {
  3867. this.negative = 0;
  3868. return this;
  3869. };
  3870. BN.prototype.abs = function abs () {
  3871. return this.clone().iabs();
  3872. };
  3873. BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
  3874. var len = num.length + shift;
  3875. var i;
  3876. this._expand(len);
  3877. var w;
  3878. var carry = 0;
  3879. for (i = 0; i < num.length; i++) {
  3880. w = (this.words[i + shift] | 0) + carry;
  3881. var right = (num.words[i] | 0) * mul;
  3882. w -= right & 0x3ffffff;
  3883. carry = (w >> 26) - ((right / 0x4000000) | 0);
  3884. this.words[i + shift] = w & 0x3ffffff;
  3885. }
  3886. for (; i < this.length - shift; i++) {
  3887. w = (this.words[i + shift] | 0) + carry;
  3888. carry = w >> 26;
  3889. this.words[i + shift] = w & 0x3ffffff;
  3890. }
  3891. if (carry === 0) return this.strip();
  3892. // Subtraction overflow
  3893. assert(carry === -1);
  3894. carry = 0;
  3895. for (i = 0; i < this.length; i++) {
  3896. w = -(this.words[i] | 0) + carry;
  3897. carry = w >> 26;
  3898. this.words[i] = w & 0x3ffffff;
  3899. }
  3900. this.negative = 1;
  3901. return this.strip();
  3902. };
  3903. BN.prototype._wordDiv = function _wordDiv (num, mode) {
  3904. var shift = this.length - num.length;
  3905. var a = this.clone();
  3906. var b = num;
  3907. // Normalize
  3908. var bhi = b.words[b.length - 1] | 0;
  3909. var bhiBits = this._countBits(bhi);
  3910. shift = 26 - bhiBits;
  3911. if (shift !== 0) {
  3912. b = b.ushln(shift);
  3913. a.iushln(shift);
  3914. bhi = b.words[b.length - 1] | 0;
  3915. }
  3916. // Initialize quotient
  3917. var m = a.length - b.length;
  3918. var q;
  3919. if (mode !== 'mod') {
  3920. q = new BN(null);
  3921. q.length = m + 1;
  3922. q.words = new Array(q.length);
  3923. for (var i = 0; i < q.length; i++) {
  3924. q.words[i] = 0;
  3925. }
  3926. }
  3927. var diff = a.clone()._ishlnsubmul(b, 1, m);
  3928. if (diff.negative === 0) {
  3929. a = diff;
  3930. if (q) {
  3931. q.words[m] = 1;
  3932. }
  3933. }
  3934. for (var j = m - 1; j >= 0; j--) {
  3935. var qj = (a.words[b.length + j] | 0) * 0x4000000 +
  3936. (a.words[b.length + j - 1] | 0);
  3937. // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
  3938. // (0x7ffffff)
  3939. qj = Math.min((qj / bhi) | 0, 0x3ffffff);
  3940. a._ishlnsubmul(b, qj, j);
  3941. while (a.negative !== 0) {
  3942. qj--;
  3943. a.negative = 0;
  3944. a._ishlnsubmul(b, 1, j);
  3945. if (!a.isZero()) {
  3946. a.negative ^= 1;
  3947. }
  3948. }
  3949. if (q) {
  3950. q.words[j] = qj;
  3951. }
  3952. }
  3953. if (q) {
  3954. q.strip();
  3955. }
  3956. a.strip();
  3957. // Denormalize
  3958. if (mode !== 'div' && shift !== 0) {
  3959. a.iushrn(shift);
  3960. }
  3961. return {
  3962. div: q || null,
  3963. mod: a
  3964. };
  3965. };
  3966. // NOTE: 1) `mode` can be set to `mod` to request mod only,
  3967. // to `div` to request div only, or be absent to
  3968. // request both div & mod
  3969. // 2) `positive` is true if unsigned mod is requested
  3970. BN.prototype.divmod = function divmod (num, mode, positive) {
  3971. assert(!num.isZero());
  3972. if (this.isZero()) {
  3973. return {
  3974. div: new BN(0),
  3975. mod: new BN(0)
  3976. };
  3977. }
  3978. var div, mod, res;
  3979. if (this.negative !== 0 && num.negative === 0) {
  3980. res = this.neg().divmod(num, mode);
  3981. if (mode !== 'mod') {
  3982. div = res.div.neg();
  3983. }
  3984. if (mode !== 'div') {
  3985. mod = res.mod.neg();
  3986. if (positive && mod.negative !== 0) {
  3987. mod.iadd(num);
  3988. }
  3989. }
  3990. return {
  3991. div: div,
  3992. mod: mod
  3993. };
  3994. }
  3995. if (this.negative === 0 && num.negative !== 0) {
  3996. res = this.divmod(num.neg(), mode);
  3997. if (mode !== 'mod') {
  3998. div = res.div.neg();
  3999. }
  4000. return {
  4001. div: div,
  4002. mod: res.mod
  4003. };
  4004. }
  4005. if ((this.negative & num.negative) !== 0) {
  4006. res = this.neg().divmod(num.neg(), mode);
  4007. if (mode !== 'div') {
  4008. mod = res.mod.neg();
  4009. if (positive && mod.negative !== 0) {
  4010. mod.isub(num);
  4011. }
  4012. }
  4013. return {
  4014. div: res.div,
  4015. mod: mod
  4016. };
  4017. }
  4018. // Both numbers are positive at this point
  4019. // Strip both numbers to approximate shift value
  4020. if (num.length > this.length || this.cmp(num) < 0) {
  4021. return {
  4022. div: new BN(0),
  4023. mod: this
  4024. };
  4025. }
  4026. // Very short reduction
  4027. if (num.length === 1) {
  4028. if (mode === 'div') {
  4029. return {
  4030. div: this.divn(num.words[0]),
  4031. mod: null
  4032. };
  4033. }
  4034. if (mode === 'mod') {
  4035. return {
  4036. div: null,
  4037. mod: new BN(this.modn(num.words[0]))
  4038. };
  4039. }
  4040. return {
  4041. div: this.divn(num.words[0]),
  4042. mod: new BN(this.modn(num.words[0]))
  4043. };
  4044. }
  4045. return this._wordDiv(num, mode);
  4046. };
  4047. // Find `this` / `num`
  4048. BN.prototype.div = function div (num) {
  4049. return this.divmod(num, 'div', false).div;
  4050. };
  4051. // Find `this` % `num`
  4052. BN.prototype.mod = function mod (num) {
  4053. return this.divmod(num, 'mod', false).mod;
  4054. };
  4055. BN.prototype.umod = function umod (num) {
  4056. return this.divmod(num, 'mod', true).mod;
  4057. };
  4058. // Find Round(`this` / `num`)
  4059. BN.prototype.divRound = function divRound (num) {
  4060. var dm = this.divmod(num);
  4061. // Fast case - exact division
  4062. if (dm.mod.isZero()) return dm.div;
  4063. var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
  4064. var half = num.ushrn(1);
  4065. var r2 = num.andln(1);
  4066. var cmp = mod.cmp(half);
  4067. // Round down
  4068. if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
  4069. // Round up
  4070. return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
  4071. };
  4072. BN.prototype.modn = function modn (num) {
  4073. assert(num <= 0x3ffffff);
  4074. var p = (1 << 26) % num;
  4075. var acc = 0;
  4076. for (var i = this.length - 1; i >= 0; i--) {
  4077. acc = (p * acc + (this.words[i] | 0)) % num;
  4078. }
  4079. return acc;
  4080. };
  4081. // In-place division by number
  4082. BN.prototype.idivn = function idivn (num) {
  4083. assert(num <= 0x3ffffff);
  4084. var carry = 0;
  4085. for (var i = this.length - 1; i >= 0; i--) {
  4086. var w = (this.words[i] | 0) + carry * 0x4000000;
  4087. this.words[i] = (w / num) | 0;
  4088. carry = w % num;
  4089. }
  4090. return this.strip();
  4091. };
  4092. BN.prototype.divn = function divn (num) {
  4093. return this.clone().idivn(num);
  4094. };
  4095. BN.prototype.egcd = function egcd (p) {
  4096. assert(p.negative === 0);
  4097. assert(!p.isZero());
  4098. var x = this;
  4099. var y = p.clone();
  4100. if (x.negative !== 0) {
  4101. x = x.umod(p);
  4102. } else {
  4103. x = x.clone();
  4104. }
  4105. // A * x + B * y = x
  4106. var A = new BN(1);
  4107. var B = new BN(0);
  4108. // C * x + D * y = y
  4109. var C = new BN(0);
  4110. var D = new BN(1);
  4111. var g = 0;
  4112. while (x.isEven() && y.isEven()) {
  4113. x.iushrn(1);
  4114. y.iushrn(1);
  4115. ++g;
  4116. }
  4117. var yp = y.clone();
  4118. var xp = x.clone();
  4119. while (!x.isZero()) {
  4120. for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
  4121. if (i > 0) {
  4122. x.iushrn(i);
  4123. while (i-- > 0) {
  4124. if (A.isOdd() || B.isOdd()) {
  4125. A.iadd(yp);
  4126. B.isub(xp);
  4127. }
  4128. A.iushrn(1);
  4129. B.iushrn(1);
  4130. }
  4131. }
  4132. for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
  4133. if (j > 0) {
  4134. y.iushrn(j);
  4135. while (j-- > 0) {
  4136. if (C.isOdd() || D.isOdd()) {
  4137. C.iadd(yp);
  4138. D.isub(xp);
  4139. }
  4140. C.iushrn(1);
  4141. D.iushrn(1);
  4142. }
  4143. }
  4144. if (x.cmp(y) >= 0) {
  4145. x.isub(y);
  4146. A.isub(C);
  4147. B.isub(D);
  4148. } else {
  4149. y.isub(x);
  4150. C.isub(A);
  4151. D.isub(B);
  4152. }
  4153. }
  4154. return {
  4155. a: C,
  4156. b: D,
  4157. gcd: y.iushln(g)
  4158. };
  4159. };
  4160. // This is reduced incarnation of the binary EEA
  4161. // above, designated to invert members of the
  4162. // _prime_ fields F(p) at a maximal speed
  4163. BN.prototype._invmp = function _invmp (p) {
  4164. assert(p.negative === 0);
  4165. assert(!p.isZero());
  4166. var a = this;
  4167. var b = p.clone();
  4168. if (a.negative !== 0) {
  4169. a = a.umod(p);
  4170. } else {
  4171. a = a.clone();
  4172. }
  4173. var x1 = new BN(1);
  4174. var x2 = new BN(0);
  4175. var delta = b.clone();
  4176. while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
  4177. for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
  4178. if (i > 0) {
  4179. a.iushrn(i);
  4180. while (i-- > 0) {
  4181. if (x1.isOdd()) {
  4182. x1.iadd(delta);
  4183. }
  4184. x1.iushrn(1);
  4185. }
  4186. }
  4187. for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
  4188. if (j > 0) {
  4189. b.iushrn(j);
  4190. while (j-- > 0) {
  4191. if (x2.isOdd()) {
  4192. x2.iadd(delta);
  4193. }
  4194. x2.iushrn(1);
  4195. }
  4196. }
  4197. if (a.cmp(b) >= 0) {
  4198. a.isub(b);
  4199. x1.isub(x2);
  4200. } else {
  4201. b.isub(a);
  4202. x2.isub(x1);
  4203. }
  4204. }
  4205. var res;
  4206. if (a.cmpn(1) === 0) {
  4207. res = x1;
  4208. } else {
  4209. res = x2;
  4210. }
  4211. if (res.cmpn(0) < 0) {
  4212. res.iadd(p);
  4213. }
  4214. return res;
  4215. };
  4216. BN.prototype.gcd = function gcd (num) {
  4217. if (this.isZero()) return num.abs();
  4218. if (num.isZero()) return this.abs();
  4219. var a = this.clone();
  4220. var b = num.clone();
  4221. a.negative = 0;
  4222. b.negative = 0;
  4223. // Remove common factor of two
  4224. for (var shift = 0; a.isEven() && b.isEven(); shift++) {
  4225. a.iushrn(1);
  4226. b.iushrn(1);
  4227. }
  4228. do {
  4229. while (a.isEven()) {
  4230. a.iushrn(1);
  4231. }
  4232. while (b.isEven()) {
  4233. b.iushrn(1);
  4234. }
  4235. var r = a.cmp(b);
  4236. if (r < 0) {
  4237. // Swap `a` and `b` to make `a` always bigger than `b`
  4238. var t = a;
  4239. a = b;
  4240. b = t;
  4241. } else if (r === 0 || b.cmpn(1) === 0) {
  4242. break;
  4243. }
  4244. a.isub(b);
  4245. } while (true);
  4246. return b.iushln(shift);
  4247. };
  4248. // Invert number in the field F(num)
  4249. BN.prototype.invm = function invm (num) {
  4250. return this.egcd(num).a.umod(num);
  4251. };
  4252. BN.prototype.isEven = function isEven () {
  4253. return (this.words[0] & 1) === 0;
  4254. };
  4255. BN.prototype.isOdd = function isOdd () {
  4256. return (this.words[0] & 1) === 1;
  4257. };
  4258. // And first word and num
  4259. BN.prototype.andln = function andln (num) {
  4260. return this.words[0] & num;
  4261. };
  4262. // Increment at the bit position in-line
  4263. BN.prototype.bincn = function bincn (bit) {
  4264. assert(typeof bit === 'number');
  4265. var r = bit % 26;
  4266. var s = (bit - r) / 26;
  4267. var q = 1 << r;
  4268. // Fast case: bit is much higher than all existing words
  4269. if (this.length <= s) {
  4270. this._expand(s + 1);
  4271. this.words[s] |= q;
  4272. return this;
  4273. }
  4274. // Add bit and propagate, if needed
  4275. var carry = q;
  4276. for (var i = s; carry !== 0 && i < this.length; i++) {
  4277. var w = this.words[i] | 0;
  4278. w += carry;
  4279. carry = w >>> 26;
  4280. w &= 0x3ffffff;
  4281. this.words[i] = w;
  4282. }
  4283. if (carry !== 0) {
  4284. this.words[i] = carry;
  4285. this.length++;
  4286. }
  4287. return this;
  4288. };
  4289. BN.prototype.isZero = function isZero () {
  4290. return this.length === 1 && this.words[0] === 0;
  4291. };
  4292. BN.prototype.cmpn = function cmpn (num) {
  4293. var negative = num < 0;
  4294. if (this.negative !== 0 && !negative) return -1;
  4295. if (this.negative === 0 && negative) return 1;
  4296. this.strip();
  4297. var res;
  4298. if (this.length > 1) {
  4299. res = 1;
  4300. } else {
  4301. if (negative) {
  4302. num = -num;
  4303. }
  4304. assert(num <= 0x3ffffff, 'Number is too big');
  4305. var w = this.words[0] | 0;
  4306. res = w === num ? 0 : w < num ? -1 : 1;
  4307. }
  4308. if (this.negative !== 0) return -res | 0;
  4309. return res;
  4310. };
  4311. // Compare two numbers and return:
  4312. // 1 - if `this` > `num`
  4313. // 0 - if `this` == `num`
  4314. // -1 - if `this` < `num`
  4315. BN.prototype.cmp = function cmp (num) {
  4316. if (this.negative !== 0 && num.negative === 0) return -1;
  4317. if (this.negative === 0 && num.negative !== 0) return 1;
  4318. var res = this.ucmp(num);
  4319. if (this.negative !== 0) return -res | 0;
  4320. return res;
  4321. };
  4322. // Unsigned comparison
  4323. BN.prototype.ucmp = function ucmp (num) {
  4324. // At this point both numbers have the same sign
  4325. if (this.length > num.length) return 1;
  4326. if (this.length < num.length) return -1;
  4327. var res = 0;
  4328. for (var i = this.length - 1; i >= 0; i--) {
  4329. var a = this.words[i] | 0;
  4330. var b = num.words[i] | 0;
  4331. if (a === b) continue;
  4332. if (a < b) {
  4333. res = -1;
  4334. } else if (a > b) {
  4335. res = 1;
  4336. }
  4337. break;
  4338. }
  4339. return res;
  4340. };
  4341. BN.prototype.gtn = function gtn (num) {
  4342. return this.cmpn(num) === 1;
  4343. };
  4344. BN.prototype.gt = function gt (num) {
  4345. return this.cmp(num) === 1;
  4346. };
  4347. BN.prototype.gten = function gten (num) {
  4348. return this.cmpn(num) >= 0;
  4349. };
  4350. BN.prototype.gte = function gte (num) {
  4351. return this.cmp(num) >= 0;
  4352. };
  4353. BN.prototype.ltn = function ltn (num) {
  4354. return this.cmpn(num) === -1;
  4355. };
  4356. BN.prototype.lt = function lt (num) {
  4357. return this.cmp(num) === -1;
  4358. };
  4359. BN.prototype.lten = function lten (num) {
  4360. return this.cmpn(num) <= 0;
  4361. };
  4362. BN.prototype.lte = function lte (num) {
  4363. return this.cmp(num) <= 0;
  4364. };
  4365. BN.prototype.eqn = function eqn (num) {
  4366. return this.cmpn(num) === 0;
  4367. };
  4368. BN.prototype.eq = function eq (num) {
  4369. return this.cmp(num) === 0;
  4370. };
  4371. //
  4372. // A reduce context, could be using montgomery or something better, depending
  4373. // on the `m` itself.
  4374. //
  4375. BN.red = function red (num) {
  4376. return new Red(num);
  4377. };
  4378. BN.prototype.toRed = function toRed (ctx) {
  4379. assert(!this.red, 'Already a number in reduction context');
  4380. assert(this.negative === 0, 'red works only with positives');
  4381. return ctx.convertTo(this)._forceRed(ctx);
  4382. };
  4383. BN.prototype.fromRed = function fromRed () {
  4384. assert(this.red, 'fromRed works only with numbers in reduction context');
  4385. return this.red.convertFrom(this);
  4386. };
  4387. BN.prototype._forceRed = function _forceRed (ctx) {
  4388. this.red = ctx;
  4389. return this;
  4390. };
  4391. BN.prototype.forceRed = function forceRed (ctx) {
  4392. assert(!this.red, 'Already a number in reduction context');
  4393. return this._forceRed(ctx);
  4394. };
  4395. BN.prototype.redAdd = function redAdd (num) {
  4396. assert(this.red, 'redAdd works only with red numbers');
  4397. return this.red.add(this, num);
  4398. };
  4399. BN.prototype.redIAdd = function redIAdd (num) {
  4400. assert(this.red, 'redIAdd works only with red numbers');
  4401. return this.red.iadd(this, num);
  4402. };
  4403. BN.prototype.redSub = function redSub (num) {
  4404. assert(this.red, 'redSub works only with red numbers');
  4405. return this.red.sub(this, num);
  4406. };
  4407. BN.prototype.redISub = function redISub (num) {
  4408. assert(this.red, 'redISub works only with red numbers');
  4409. return this.red.isub(this, num);
  4410. };
  4411. BN.prototype.redShl = function redShl (num) {
  4412. assert(this.red, 'redShl works only with red numbers');
  4413. return this.red.shl(this, num);
  4414. };
  4415. BN.prototype.redMul = function redMul (num) {
  4416. assert(this.red, 'redMul works only with red numbers');
  4417. this.red._verify2(this, num);
  4418. return this.red.mul(this, num);
  4419. };
  4420. BN.prototype.redIMul = function redIMul (num) {
  4421. assert(this.red, 'redMul works only with red numbers');
  4422. this.red._verify2(this, num);
  4423. return this.red.imul(this, num);
  4424. };
  4425. BN.prototype.redSqr = function redSqr () {
  4426. assert(this.red, 'redSqr works only with red numbers');
  4427. this.red._verify1(this);
  4428. return this.red.sqr(this);
  4429. };
  4430. BN.prototype.redISqr = function redISqr () {
  4431. assert(this.red, 'redISqr works only with red numbers');
  4432. this.red._verify1(this);
  4433. return this.red.isqr(this);
  4434. };
  4435. // Square root over p
  4436. BN.prototype.redSqrt = function redSqrt () {
  4437. assert(this.red, 'redSqrt works only with red numbers');
  4438. this.red._verify1(this);
  4439. return this.red.sqrt(this);
  4440. };
  4441. BN.prototype.redInvm = function redInvm () {
  4442. assert(this.red, 'redInvm works only with red numbers');
  4443. this.red._verify1(this);
  4444. return this.red.invm(this);
  4445. };
  4446. // Return negative clone of `this` % `red modulo`
  4447. BN.prototype.redNeg = function redNeg () {
  4448. assert(this.red, 'redNeg works only with red numbers');
  4449. this.red._verify1(this);
  4450. return this.red.neg(this);
  4451. };
  4452. BN.prototype.redPow = function redPow (num) {
  4453. assert(this.red && !num.red, 'redPow(normalNum)');
  4454. this.red._verify1(this);
  4455. return this.red.pow(this, num);
  4456. };
  4457. // Prime numbers with efficient reduction
  4458. var primes = {
  4459. k256: null,
  4460. p224: null,
  4461. p192: null,
  4462. p25519: null
  4463. };
  4464. // Pseudo-Mersenne prime
  4465. function MPrime (name, p) {
  4466. // P = 2 ^ N - K
  4467. this.name = name;
  4468. this.p = new BN(p, 16);
  4469. this.n = this.p.bitLength();
  4470. this.k = new BN(1).iushln(this.n).isub(this.p);
  4471. this.tmp = this._tmp();
  4472. }
  4473. MPrime.prototype._tmp = function _tmp () {
  4474. var tmp = new BN(null);
  4475. tmp.words = new Array(Math.ceil(this.n / 13));
  4476. return tmp;
  4477. };
  4478. MPrime.prototype.ireduce = function ireduce (num) {
  4479. // Assumes that `num` is less than `P^2`
  4480. // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
  4481. var r = num;
  4482. var rlen;
  4483. do {
  4484. this.split(r, this.tmp);
  4485. r = this.imulK(r);
  4486. r = r.iadd(this.tmp);
  4487. rlen = r.bitLength();
  4488. } while (rlen > this.n);
  4489. var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
  4490. if (cmp === 0) {
  4491. r.words[0] = 0;
  4492. r.length = 1;
  4493. } else if (cmp > 0) {
  4494. r.isub(this.p);
  4495. } else {
  4496. r.strip();
  4497. }
  4498. return r;
  4499. };
  4500. MPrime.prototype.split = function split (input, out) {
  4501. input.iushrn(this.n, 0, out);
  4502. };
  4503. MPrime.prototype.imulK = function imulK (num) {
  4504. return num.imul(this.k);
  4505. };
  4506. function K256 () {
  4507. MPrime.call(
  4508. this,
  4509. 'k256',
  4510. 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
  4511. }
  4512. inherits(K256, MPrime);
  4513. K256.prototype.split = function split (input, output) {
  4514. // 256 = 9 * 26 + 22
  4515. var mask = 0x3fffff;
  4516. var outLen = Math.min(input.length, 9);
  4517. for (var i = 0; i < outLen; i++) {
  4518. output.words[i] = input.words[i];
  4519. }
  4520. output.length = outLen;
  4521. if (input.length <= 9) {
  4522. input.words[0] = 0;
  4523. input.length = 1;
  4524. return;
  4525. }
  4526. // Shift by 9 limbs
  4527. var prev = input.words[9];
  4528. output.words[output.length++] = prev & mask;
  4529. for (i = 10; i < input.length; i++) {
  4530. var next = input.words[i] | 0;
  4531. input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
  4532. prev = next;
  4533. }
  4534. prev >>>= 22;
  4535. input.words[i - 10] = prev;
  4536. if (prev === 0 && input.length > 10) {
  4537. input.length -= 10;
  4538. } else {
  4539. input.length -= 9;
  4540. }
  4541. };
  4542. K256.prototype.imulK = function imulK (num) {
  4543. // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
  4544. num.words[num.length] = 0;
  4545. num.words[num.length + 1] = 0;
  4546. num.length += 2;
  4547. // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
  4548. var lo = 0;
  4549. for (var i = 0; i < num.length; i++) {
  4550. var w = num.words[i] | 0;
  4551. lo += w * 0x3d1;
  4552. num.words[i] = lo & 0x3ffffff;
  4553. lo = w * 0x40 + ((lo / 0x4000000) | 0);
  4554. }
  4555. // Fast length reduction
  4556. if (num.words[num.length - 1] === 0) {
  4557. num.length--;
  4558. if (num.words[num.length - 1] === 0) {
  4559. num.length--;
  4560. }
  4561. }
  4562. return num;
  4563. };
  4564. function P224 () {
  4565. MPrime.call(
  4566. this,
  4567. 'p224',
  4568. 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
  4569. }
  4570. inherits(P224, MPrime);
  4571. function P192 () {
  4572. MPrime.call(
  4573. this,
  4574. 'p192',
  4575. 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
  4576. }
  4577. inherits(P192, MPrime);
  4578. function P25519 () {
  4579. // 2 ^ 255 - 19
  4580. MPrime.call(
  4581. this,
  4582. '25519',
  4583. '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
  4584. }
  4585. inherits(P25519, MPrime);
  4586. P25519.prototype.imulK = function imulK (num) {
  4587. // K = 0x13
  4588. var carry = 0;
  4589. for (var i = 0; i < num.length; i++) {
  4590. var hi = (num.words[i] | 0) * 0x13 + carry;
  4591. var lo = hi & 0x3ffffff;
  4592. hi >>>= 26;
  4593. num.words[i] = lo;
  4594. carry = hi;
  4595. }
  4596. if (carry !== 0) {
  4597. num.words[num.length++] = carry;
  4598. }
  4599. return num;
  4600. };
  4601. // Exported mostly for testing purposes, use plain name instead
  4602. BN._prime = function prime (name) {
  4603. // Cached version of prime
  4604. if (primes[name]) return primes[name];
  4605. var prime;
  4606. if (name === 'k256') {
  4607. prime = new K256();
  4608. } else if (name === 'p224') {
  4609. prime = new P224();
  4610. } else if (name === 'p192') {
  4611. prime = new P192();
  4612. } else if (name === 'p25519') {
  4613. prime = new P25519();
  4614. } else {
  4615. throw new Error('Unknown prime ' + name);
  4616. }
  4617. primes[name] = prime;
  4618. return prime;
  4619. };
  4620. //
  4621. // Base reduction engine
  4622. //
  4623. function Red (m) {
  4624. if (typeof m === 'string') {
  4625. var prime = BN._prime(m);
  4626. this.m = prime.p;
  4627. this.prime = prime;
  4628. } else {
  4629. assert(m.gtn(1), 'modulus must be greater than 1');
  4630. this.m = m;
  4631. this.prime = null;
  4632. }
  4633. }
  4634. Red.prototype._verify1 = function _verify1 (a) {
  4635. assert(a.negative === 0, 'red works only with positives');
  4636. assert(a.red, 'red works only with red numbers');
  4637. };
  4638. Red.prototype._verify2 = function _verify2 (a, b) {
  4639. assert((a.negative | b.negative) === 0, 'red works only with positives');
  4640. assert(a.red && a.red === b.red,
  4641. 'red works only with red numbers');
  4642. };
  4643. Red.prototype.imod = function imod (a) {
  4644. if (this.prime) return this.prime.ireduce(a)._forceRed(this);
  4645. return a.umod(this.m)._forceRed(this);
  4646. };
  4647. Red.prototype.neg = function neg (a) {
  4648. if (a.isZero()) {
  4649. return a.clone();
  4650. }
  4651. return this.m.sub(a)._forceRed(this);
  4652. };
  4653. Red.prototype.add = function add (a, b) {
  4654. this._verify2(a, b);
  4655. var res = a.add(b);
  4656. if (res.cmp(this.m) >= 0) {
  4657. res.isub(this.m);
  4658. }
  4659. return res._forceRed(this);
  4660. };
  4661. Red.prototype.iadd = function iadd (a, b) {
  4662. this._verify2(a, b);
  4663. var res = a.iadd(b);
  4664. if (res.cmp(this.m) >= 0) {
  4665. res.isub(this.m);
  4666. }
  4667. return res;
  4668. };
  4669. Red.prototype.sub = function sub (a, b) {
  4670. this._verify2(a, b);
  4671. var res = a.sub(b);
  4672. if (res.cmpn(0) < 0) {
  4673. res.iadd(this.m);
  4674. }
  4675. return res._forceRed(this);
  4676. };
  4677. Red.prototype.isub = function isub (a, b) {
  4678. this._verify2(a, b);
  4679. var res = a.isub(b);
  4680. if (res.cmpn(0) < 0) {
  4681. res.iadd(this.m);
  4682. }
  4683. return res;
  4684. };
  4685. Red.prototype.shl = function shl (a, num) {
  4686. this._verify1(a);
  4687. return this.imod(a.ushln(num));
  4688. };
  4689. Red.prototype.imul = function imul (a, b) {
  4690. this._verify2(a, b);
  4691. return this.imod(a.imul(b));
  4692. };
  4693. Red.prototype.mul = function mul (a, b) {
  4694. this._verify2(a, b);
  4695. return this.imod(a.mul(b));
  4696. };
  4697. Red.prototype.isqr = function isqr (a) {
  4698. return this.imul(a, a.clone());
  4699. };
  4700. Red.prototype.sqr = function sqr (a) {
  4701. return this.mul(a, a);
  4702. };
  4703. Red.prototype.sqrt = function sqrt (a) {
  4704. if (a.isZero()) return a.clone();
  4705. var mod3 = this.m.andln(3);
  4706. assert(mod3 % 2 === 1);
  4707. // Fast case
  4708. if (mod3 === 3) {
  4709. var pow = this.m.add(new BN(1)).iushrn(2);
  4710. return this.pow(a, pow);
  4711. }
  4712. // Tonelli-Shanks algorithm (Totally unoptimized and slow)
  4713. //
  4714. // Find Q and S, that Q * 2 ^ S = (P - 1)
  4715. var q = this.m.subn(1);
  4716. var s = 0;
  4717. while (!q.isZero() && q.andln(1) === 0) {
  4718. s++;
  4719. q.iushrn(1);
  4720. }
  4721. assert(!q.isZero());
  4722. var one = new BN(1).toRed(this);
  4723. var nOne = one.redNeg();
  4724. // Find quadratic non-residue
  4725. // NOTE: Max is such because of generalized Riemann hypothesis.
  4726. var lpow = this.m.subn(1).iushrn(1);
  4727. var z = this.m.bitLength();
  4728. z = new BN(2 * z * z).toRed(this);
  4729. while (this.pow(z, lpow).cmp(nOne) !== 0) {
  4730. z.redIAdd(nOne);
  4731. }
  4732. var c = this.pow(z, q);
  4733. var r = this.pow(a, q.addn(1).iushrn(1));
  4734. var t = this.pow(a, q);
  4735. var m = s;
  4736. while (t.cmp(one) !== 0) {
  4737. var tmp = t;
  4738. for (var i = 0; tmp.cmp(one) !== 0; i++) {
  4739. tmp = tmp.redSqr();
  4740. }
  4741. assert(i < m);
  4742. var b = this.pow(c, new BN(1).iushln(m - i - 1));
  4743. r = r.redMul(b);
  4744. c = b.redSqr();
  4745. t = t.redMul(c);
  4746. m = i;
  4747. }
  4748. return r;
  4749. };
  4750. Red.prototype.invm = function invm (a) {
  4751. var inv = a._invmp(this.m);
  4752. if (inv.negative !== 0) {
  4753. inv.negative = 0;
  4754. return this.imod(inv).redNeg();
  4755. } else {
  4756. return this.imod(inv);
  4757. }
  4758. };
  4759. Red.prototype.pow = function pow (a, num) {
  4760. if (num.isZero()) return new BN(1).toRed(this);
  4761. if (num.cmpn(1) === 0) return a.clone();
  4762. var windowSize = 4;
  4763. var wnd = new Array(1 << windowSize);
  4764. wnd[0] = new BN(1).toRed(this);
  4765. wnd[1] = a;
  4766. for (var i = 2; i < wnd.length; i++) {
  4767. wnd[i] = this.mul(wnd[i - 1], a);
  4768. }
  4769. var res = wnd[0];
  4770. var current = 0;
  4771. var currentLen = 0;
  4772. var start = num.bitLength() % 26;
  4773. if (start === 0) {
  4774. start = 26;
  4775. }
  4776. for (i = num.length - 1; i >= 0; i--) {
  4777. var word = num.words[i];
  4778. for (var j = start - 1; j >= 0; j--) {
  4779. var bit = (word >> j) & 1;
  4780. if (res !== wnd[0]) {
  4781. res = this.sqr(res);
  4782. }
  4783. if (bit === 0 && current === 0) {
  4784. currentLen = 0;
  4785. continue;
  4786. }
  4787. current <<= 1;
  4788. current |= bit;
  4789. currentLen++;
  4790. if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
  4791. res = this.mul(res, wnd[current]);
  4792. currentLen = 0;
  4793. current = 0;
  4794. }
  4795. start = 26;
  4796. }
  4797. return res;
  4798. };
  4799. Red.prototype.convertTo = function convertTo (num) {
  4800. var r = num.umod(this.m);
  4801. return r === num ? r.clone() : r;
  4802. };
  4803. Red.prototype.convertFrom = function convertFrom (num) {
  4804. var res = num.clone();
  4805. res.red = null;
  4806. return res;
  4807. };
  4808. //
  4809. // Montgomery method engine
  4810. //
  4811. BN.mont = function mont (num) {
  4812. return new Mont(num);
  4813. };
  4814. function Mont (m) {
  4815. Red.call(this, m);
  4816. this.shift = this.m.bitLength();
  4817. if (this.shift % 26 !== 0) {
  4818. this.shift += 26 - (this.shift % 26);
  4819. }
  4820. this.r = new BN(1).iushln(this.shift);
  4821. this.r2 = this.imod(this.r.sqr());
  4822. this.rinv = this.r._invmp(this.m);
  4823. this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
  4824. this.minv = this.minv.umod(this.r);
  4825. this.minv = this.r.sub(this.minv);
  4826. }
  4827. inherits(Mont, Red);
  4828. Mont.prototype.convertTo = function convertTo (num) {
  4829. return this.imod(num.ushln(this.shift));
  4830. };
  4831. Mont.prototype.convertFrom = function convertFrom (num) {
  4832. var r = this.imod(num.mul(this.rinv));
  4833. r.red = null;
  4834. return r;
  4835. };
  4836. Mont.prototype.imul = function imul (a, b) {
  4837. if (a.isZero() || b.isZero()) {
  4838. a.words[0] = 0;
  4839. a.length = 1;
  4840. return a;
  4841. }
  4842. var t = a.imul(b);
  4843. var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
  4844. var u = t.isub(c).iushrn(this.shift);
  4845. var res = u;
  4846. if (u.cmp(this.m) >= 0) {
  4847. res = u.isub(this.m);
  4848. } else if (u.cmpn(0) < 0) {
  4849. res = u.iadd(this.m);
  4850. }
  4851. return res._forceRed(this);
  4852. };
  4853. Mont.prototype.mul = function mul (a, b) {
  4854. if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
  4855. var t = a.mul(b);
  4856. var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
  4857. var u = t.isub(c).iushrn(this.shift);
  4858. var res = u;
  4859. if (u.cmp(this.m) >= 0) {
  4860. res = u.isub(this.m);
  4861. } else if (u.cmpn(0) < 0) {
  4862. res = u.iadd(this.m);
  4863. }
  4864. return res._forceRed(this);
  4865. };
  4866. Mont.prototype.invm = function invm (a) {
  4867. // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
  4868. var res = this.imod(a._invmp(this.m).mul(this.r2));
  4869. return res._forceRed(this);
  4870. };
  4871. })(typeof module === 'undefined' || module, this);
  4872. },{"buffer":19}],18:[function(require,module,exports){
  4873. var r;
  4874. module.exports = function rand(len) {
  4875. if (!r)
  4876. r = new Rand(null);
  4877. return r.generate(len);
  4878. };
  4879. function Rand(rand) {
  4880. this.rand = rand;
  4881. }
  4882. module.exports.Rand = Rand;
  4883. Rand.prototype.generate = function generate(len) {
  4884. return this._rand(len);
  4885. };
  4886. // Emulate crypto API using randy
  4887. Rand.prototype._rand = function _rand(n) {
  4888. if (this.rand.getBytes)
  4889. return this.rand.getBytes(n);
  4890. var res = new Uint8Array(n);
  4891. for (var i = 0; i < res.length; i++)
  4892. res[i] = this.rand.getByte();
  4893. return res;
  4894. };
  4895. if (typeof self === 'object') {
  4896. if (self.crypto && self.crypto.getRandomValues) {
  4897. // Modern browsers
  4898. Rand.prototype._rand = function _rand(n) {
  4899. var arr = new Uint8Array(n);
  4900. self.crypto.getRandomValues(arr);
  4901. return arr;
  4902. };
  4903. } else if (self.msCrypto && self.msCrypto.getRandomValues) {
  4904. // IE
  4905. Rand.prototype._rand = function _rand(n) {
  4906. var arr = new Uint8Array(n);
  4907. self.msCrypto.getRandomValues(arr);
  4908. return arr;
  4909. };
  4910. // Safari's WebWorkers do not have `crypto`
  4911. } else if (typeof window === 'object') {
  4912. // Old junk
  4913. Rand.prototype._rand = function() {
  4914. throw new Error('Not implemented yet');
  4915. };
  4916. }
  4917. } else {
  4918. // Node.js or Web worker with no crypto support
  4919. try {
  4920. var crypto = require('crypto');
  4921. if (typeof crypto.randomBytes !== 'function')
  4922. throw new Error('Not supported');
  4923. Rand.prototype._rand = function _rand(n) {
  4924. return crypto.randomBytes(n);
  4925. };
  4926. } catch (e) {
  4927. }
  4928. }
  4929. },{"crypto":19}],19:[function(require,module,exports){
  4930. },{}],20:[function(require,module,exports){
  4931. // based on the aes implimentation in triple sec
  4932. // https://github.com/keybase/triplesec
  4933. // which is in turn based on the one from crypto-js
  4934. // https://code.google.com/p/crypto-js/
  4935. var Buffer = require('safe-buffer').Buffer
  4936. function asUInt32Array (buf) {
  4937. if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
  4938. var len = (buf.length / 4) | 0
  4939. var out = new Array(len)
  4940. for (var i = 0; i < len; i++) {
  4941. out[i] = buf.readUInt32BE(i * 4)
  4942. }
  4943. return out
  4944. }
  4945. function scrubVec (v) {
  4946. for (var i = 0; i < v.length; v++) {
  4947. v[i] = 0
  4948. }
  4949. }
  4950. function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) {
  4951. var SUB_MIX0 = SUB_MIX[0]
  4952. var SUB_MIX1 = SUB_MIX[1]
  4953. var SUB_MIX2 = SUB_MIX[2]
  4954. var SUB_MIX3 = SUB_MIX[3]
  4955. var s0 = M[0] ^ keySchedule[0]
  4956. var s1 = M[1] ^ keySchedule[1]
  4957. var s2 = M[2] ^ keySchedule[2]
  4958. var s3 = M[3] ^ keySchedule[3]
  4959. var t0, t1, t2, t3
  4960. var ksRow = 4
  4961. for (var round = 1; round < nRounds; round++) {
  4962. t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++]
  4963. t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++]
  4964. t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++]
  4965. t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++]
  4966. s0 = t0
  4967. s1 = t1
  4968. s2 = t2
  4969. s3 = t3
  4970. }
  4971. t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]
  4972. t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]
  4973. t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]
  4974. t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]
  4975. t0 = t0 >>> 0
  4976. t1 = t1 >>> 0
  4977. t2 = t2 >>> 0
  4978. t3 = t3 >>> 0
  4979. return [t0, t1, t2, t3]
  4980. }
  4981. // AES constants
  4982. var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
  4983. var G = (function () {
  4984. // Compute double table
  4985. var d = new Array(256)
  4986. for (var j = 0; j < 256; j++) {
  4987. if (j < 128) {
  4988. d[j] = j << 1
  4989. } else {
  4990. d[j] = (j << 1) ^ 0x11b
  4991. }
  4992. }
  4993. var SBOX = []
  4994. var INV_SBOX = []
  4995. var SUB_MIX = [[], [], [], []]
  4996. var INV_SUB_MIX = [[], [], [], []]
  4997. // Walk GF(2^8)
  4998. var x = 0
  4999. var xi = 0
  5000. for (var i = 0; i < 256; ++i) {
  5001. // Compute sbox
  5002. var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
  5003. sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
  5004. SBOX[x] = sx
  5005. INV_SBOX[sx] = x
  5006. // Compute multiplication
  5007. var x2 = d[x]
  5008. var x4 = d[x2]
  5009. var x8 = d[x4]
  5010. // Compute sub bytes, mix columns tables
  5011. var t = (d[sx] * 0x101) ^ (sx * 0x1010100)
  5012. SUB_MIX[0][x] = (t << 24) | (t >>> 8)
  5013. SUB_MIX[1][x] = (t << 16) | (t >>> 16)
  5014. SUB_MIX[2][x] = (t << 8) | (t >>> 24)
  5015. SUB_MIX[3][x] = t
  5016. // Compute inv sub bytes, inv mix columns tables
  5017. t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
  5018. INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
  5019. INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
  5020. INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
  5021. INV_SUB_MIX[3][sx] = t
  5022. if (x === 0) {
  5023. x = xi = 1
  5024. } else {
  5025. x = x2 ^ d[d[d[x8 ^ x2]]]
  5026. xi ^= d[d[xi]]
  5027. }
  5028. }
  5029. return {
  5030. SBOX: SBOX,
  5031. INV_SBOX: INV_SBOX,
  5032. SUB_MIX: SUB_MIX,
  5033. INV_SUB_MIX: INV_SUB_MIX
  5034. }
  5035. })()
  5036. function AES (key) {
  5037. this._key = asUInt32Array(key)
  5038. this._reset()
  5039. }
  5040. AES.blockSize = 4 * 4
  5041. AES.keySize = 256 / 8
  5042. AES.prototype.blockSize = AES.blockSize
  5043. AES.prototype.keySize = AES.keySize
  5044. AES.prototype._reset = function () {
  5045. var keyWords = this._key
  5046. var keySize = keyWords.length
  5047. var nRounds = keySize + 6
  5048. var ksRows = (nRounds + 1) * 4
  5049. var keySchedule = []
  5050. for (var k = 0; k < keySize; k++) {
  5051. keySchedule[k] = keyWords[k]
  5052. }
  5053. for (k = keySize; k < ksRows; k++) {
  5054. var t = keySchedule[k - 1]
  5055. if (k % keySize === 0) {
  5056. t = (t << 8) | (t >>> 24)
  5057. t =
  5058. (G.SBOX[t >>> 24] << 24) |
  5059. (G.SBOX[(t >>> 16) & 0xff] << 16) |
  5060. (G.SBOX[(t >>> 8) & 0xff] << 8) |
  5061. (G.SBOX[t & 0xff])
  5062. t ^= RCON[(k / keySize) | 0] << 24
  5063. } else if (keySize > 6 && k % keySize === 4) {
  5064. t =
  5065. (G.SBOX[t >>> 24] << 24) |
  5066. (G.SBOX[(t >>> 16) & 0xff] << 16) |
  5067. (G.SBOX[(t >>> 8) & 0xff] << 8) |
  5068. (G.SBOX[t & 0xff])
  5069. }
  5070. keySchedule[k] = keySchedule[k - keySize] ^ t
  5071. }
  5072. var invKeySchedule = []
  5073. for (var ik = 0; ik < ksRows; ik++) {
  5074. var ksR = ksRows - ik
  5075. var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)]
  5076. if (ik < 4 || ksR <= 4) {
  5077. invKeySchedule[ik] = tt
  5078. } else {
  5079. invKeySchedule[ik] =
  5080. G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^
  5081. G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^
  5082. G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^
  5083. G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]]
  5084. }
  5085. }
  5086. this._nRounds = nRounds
  5087. this._keySchedule = keySchedule
  5088. this._invKeySchedule = invKeySchedule
  5089. }
  5090. AES.prototype.encryptBlockRaw = function (M) {
  5091. M = asUInt32Array(M)
  5092. return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds)
  5093. }
  5094. AES.prototype.encryptBlock = function (M) {
  5095. var out = this.encryptBlockRaw(M)
  5096. var buf = Buffer.allocUnsafe(16)
  5097. buf.writeUInt32BE(out[0], 0)
  5098. buf.writeUInt32BE(out[1], 4)
  5099. buf.writeUInt32BE(out[2], 8)
  5100. buf.writeUInt32BE(out[3], 12)
  5101. return buf
  5102. }
  5103. AES.prototype.decryptBlock = function (M) {
  5104. M = asUInt32Array(M)
  5105. // swap
  5106. var m1 = M[1]
  5107. M[1] = M[3]
  5108. M[3] = m1
  5109. var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds)
  5110. var buf = Buffer.allocUnsafe(16)
  5111. buf.writeUInt32BE(out[0], 0)
  5112. buf.writeUInt32BE(out[3], 4)
  5113. buf.writeUInt32BE(out[2], 8)
  5114. buf.writeUInt32BE(out[1], 12)
  5115. return buf
  5116. }
  5117. AES.prototype.scrub = function () {
  5118. scrubVec(this._keySchedule)
  5119. scrubVec(this._invKeySchedule)
  5120. scrubVec(this._key)
  5121. }
  5122. module.exports.AES = AES
  5123. },{"safe-buffer":157}],21:[function(require,module,exports){
  5124. var aes = require('./aes')
  5125. var Buffer = require('safe-buffer').Buffer
  5126. var Transform = require('cipher-base')
  5127. var inherits = require('inherits')
  5128. var GHASH = require('./ghash')
  5129. var xor = require('buffer-xor')
  5130. var incr32 = require('./incr32')
  5131. function xorTest (a, b) {
  5132. var out = 0
  5133. if (a.length !== b.length) out++
  5134. var len = Math.min(a.length, b.length)
  5135. for (var i = 0; i < len; ++i) {
  5136. out += (a[i] ^ b[i])
  5137. }
  5138. return out
  5139. }
  5140. function calcIv (self, iv, ck) {
  5141. if (iv.length === 12) {
  5142. self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])])
  5143. return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])])
  5144. }
  5145. var ghash = new GHASH(ck)
  5146. var len = iv.length
  5147. var toPad = len % 16
  5148. ghash.update(iv)
  5149. if (toPad) {
  5150. toPad = 16 - toPad
  5151. ghash.update(Buffer.alloc(toPad, 0))
  5152. }
  5153. ghash.update(Buffer.alloc(8, 0))
  5154. var ivBits = len * 8
  5155. var tail = Buffer.alloc(8)
  5156. tail.writeUIntBE(ivBits, 0, 8)
  5157. ghash.update(tail)
  5158. self._finID = ghash.state
  5159. var out = Buffer.from(self._finID)
  5160. incr32(out)
  5161. return out
  5162. }
  5163. function StreamCipher (mode, key, iv, decrypt) {
  5164. Transform.call(this)
  5165. var h = Buffer.alloc(4, 0)
  5166. this._cipher = new aes.AES(key)
  5167. var ck = this._cipher.encryptBlock(h)
  5168. this._ghash = new GHASH(ck)
  5169. iv = calcIv(this, iv, ck)
  5170. this._prev = Buffer.from(iv)
  5171. this._cache = Buffer.allocUnsafe(0)
  5172. this._secCache = Buffer.allocUnsafe(0)
  5173. this._decrypt = decrypt
  5174. this._alen = 0
  5175. this._len = 0
  5176. this._mode = mode
  5177. this._authTag = null
  5178. this._called = false
  5179. }
  5180. inherits(StreamCipher, Transform)
  5181. StreamCipher.prototype._update = function (chunk) {
  5182. if (!this._called && this._alen) {
  5183. var rump = 16 - (this._alen % 16)
  5184. if (rump < 16) {
  5185. rump = Buffer.alloc(rump, 0)
  5186. this._ghash.update(rump)
  5187. }
  5188. }
  5189. this._called = true
  5190. var out = this._mode.encrypt(this, chunk)
  5191. if (this._decrypt) {
  5192. this._ghash.update(chunk)
  5193. } else {
  5194. this._ghash.update(out)
  5195. }
  5196. this._len += chunk.length
  5197. return out
  5198. }
  5199. StreamCipher.prototype._final = function () {
  5200. if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data')
  5201. var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID))
  5202. if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data')
  5203. this._authTag = tag
  5204. this._cipher.scrub()
  5205. }
  5206. StreamCipher.prototype.getAuthTag = function getAuthTag () {
  5207. if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state')
  5208. return this._authTag
  5209. }
  5210. StreamCipher.prototype.setAuthTag = function setAuthTag (tag) {
  5211. if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state')
  5212. this._authTag = tag
  5213. }
  5214. StreamCipher.prototype.setAAD = function setAAD (buf) {
  5215. if (this._called) throw new Error('Attempting to set AAD in unsupported state')
  5216. this._ghash.update(buf)
  5217. this._alen += buf.length
  5218. }
  5219. module.exports = StreamCipher
  5220. },{"./aes":20,"./ghash":25,"./incr32":26,"buffer-xor":49,"cipher-base":51,"inherits":104,"safe-buffer":157}],22:[function(require,module,exports){
  5221. var ciphers = require('./encrypter')
  5222. var deciphers = require('./decrypter')
  5223. var modes = require('./modes/list.json')
  5224. function getCiphers () {
  5225. return Object.keys(modes)
  5226. }
  5227. exports.createCipher = exports.Cipher = ciphers.createCipher
  5228. exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv
  5229. exports.createDecipher = exports.Decipher = deciphers.createDecipher
  5230. exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv
  5231. exports.listCiphers = exports.getCiphers = getCiphers
  5232. },{"./decrypter":23,"./encrypter":24,"./modes/list.json":34}],23:[function(require,module,exports){
  5233. var AuthCipher = require('./authCipher')
  5234. var Buffer = require('safe-buffer').Buffer
  5235. var MODES = require('./modes')
  5236. var StreamCipher = require('./streamCipher')
  5237. var Transform = require('cipher-base')
  5238. var aes = require('./aes')
  5239. var ebtk = require('evp_bytestokey')
  5240. var inherits = require('inherits')
  5241. function Decipher (mode, key, iv) {
  5242. Transform.call(this)
  5243. this._cache = new Splitter()
  5244. this._last = void 0
  5245. this._cipher = new aes.AES(key)
  5246. this._prev = Buffer.from(iv)
  5247. this._mode = mode
  5248. this._autopadding = true
  5249. }
  5250. inherits(Decipher, Transform)
  5251. Decipher.prototype._update = function (data) {
  5252. this._cache.add(data)
  5253. var chunk
  5254. var thing
  5255. var out = []
  5256. while ((chunk = this._cache.get(this._autopadding))) {
  5257. thing = this._mode.decrypt(this, chunk)
  5258. out.push(thing)
  5259. }
  5260. return Buffer.concat(out)
  5261. }
  5262. Decipher.prototype._final = function () {
  5263. var chunk = this._cache.flush()
  5264. if (this._autopadding) {
  5265. return unpad(this._mode.decrypt(this, chunk))
  5266. } else if (chunk) {
  5267. throw new Error('data not multiple of block length')
  5268. }
  5269. }
  5270. Decipher.prototype.setAutoPadding = function (setTo) {
  5271. this._autopadding = !!setTo
  5272. return this
  5273. }
  5274. function Splitter () {
  5275. this.cache = Buffer.allocUnsafe(0)
  5276. }
  5277. Splitter.prototype.add = function (data) {
  5278. this.cache = Buffer.concat([this.cache, data])
  5279. }
  5280. Splitter.prototype.get = function (autoPadding) {
  5281. var out
  5282. if (autoPadding) {
  5283. if (this.cache.length > 16) {
  5284. out = this.cache.slice(0, 16)
  5285. this.cache = this.cache.slice(16)
  5286. return out
  5287. }
  5288. } else {
  5289. if (this.cache.length >= 16) {
  5290. out = this.cache.slice(0, 16)
  5291. this.cache = this.cache.slice(16)
  5292. return out
  5293. }
  5294. }
  5295. return null
  5296. }
  5297. Splitter.prototype.flush = function () {
  5298. if (this.cache.length) return this.cache
  5299. }
  5300. function unpad (last) {
  5301. var padded = last[15]
  5302. var i = -1
  5303. while (++i < padded) {
  5304. if (last[(i + (16 - padded))] !== padded) {
  5305. throw new Error('unable to decrypt data')
  5306. }
  5307. }
  5308. if (padded === 16) return
  5309. return last.slice(0, 16 - padded)
  5310. }
  5311. function createDecipheriv (suite, password, iv) {
  5312. var config = MODES[suite.toLowerCase()]
  5313. if (!config) throw new TypeError('invalid suite type')
  5314. if (typeof iv === 'string') iv = Buffer.from(iv)
  5315. if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
  5316. if (typeof password === 'string') password = Buffer.from(password)
  5317. if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
  5318. if (config.type === 'stream') {
  5319. return new StreamCipher(config.module, password, iv, true)
  5320. } else if (config.type === 'auth') {
  5321. return new AuthCipher(config.module, password, iv, true)
  5322. }
  5323. return new Decipher(config.module, password, iv)
  5324. }
  5325. function createDecipher (suite, password) {
  5326. var config = MODES[suite.toLowerCase()]
  5327. if (!config) throw new TypeError('invalid suite type')
  5328. var keys = ebtk(password, false, config.key, config.iv)
  5329. return createDecipheriv(suite, keys.key, keys.iv)
  5330. }
  5331. exports.createDecipher = createDecipher
  5332. exports.createDecipheriv = createDecipheriv
  5333. },{"./aes":20,"./authCipher":21,"./modes":33,"./streamCipher":36,"cipher-base":51,"evp_bytestokey":87,"inherits":104,"safe-buffer":157}],24:[function(require,module,exports){
  5334. var MODES = require('./modes')
  5335. var AuthCipher = require('./authCipher')
  5336. var Buffer = require('safe-buffer').Buffer
  5337. var StreamCipher = require('./streamCipher')
  5338. var Transform = require('cipher-base')
  5339. var aes = require('./aes')
  5340. var ebtk = require('evp_bytestokey')
  5341. var inherits = require('inherits')
  5342. function Cipher (mode, key, iv) {
  5343. Transform.call(this)
  5344. this._cache = new Splitter()
  5345. this._cipher = new aes.AES(key)
  5346. this._prev = Buffer.from(iv)
  5347. this._mode = mode
  5348. this._autopadding = true
  5349. }
  5350. inherits(Cipher, Transform)
  5351. Cipher.prototype._update = function (data) {
  5352. this._cache.add(data)
  5353. var chunk
  5354. var thing
  5355. var out = []
  5356. while ((chunk = this._cache.get())) {
  5357. thing = this._mode.encrypt(this, chunk)
  5358. out.push(thing)
  5359. }
  5360. return Buffer.concat(out)
  5361. }
  5362. var PADDING = Buffer.alloc(16, 0x10)
  5363. Cipher.prototype._final = function () {
  5364. var chunk = this._cache.flush()
  5365. if (this._autopadding) {
  5366. chunk = this._mode.encrypt(this, chunk)
  5367. this._cipher.scrub()
  5368. return chunk
  5369. }
  5370. if (!chunk.equals(PADDING)) {
  5371. this._cipher.scrub()
  5372. throw new Error('data not multiple of block length')
  5373. }
  5374. }
  5375. Cipher.prototype.setAutoPadding = function (setTo) {
  5376. this._autopadding = !!setTo
  5377. return this
  5378. }
  5379. function Splitter () {
  5380. this.cache = Buffer.allocUnsafe(0)
  5381. }
  5382. Splitter.prototype.add = function (data) {
  5383. this.cache = Buffer.concat([this.cache, data])
  5384. }
  5385. Splitter.prototype.get = function () {
  5386. if (this.cache.length > 15) {
  5387. var out = this.cache.slice(0, 16)
  5388. this.cache = this.cache.slice(16)
  5389. return out
  5390. }
  5391. return null
  5392. }
  5393. Splitter.prototype.flush = function () {
  5394. var len = 16 - this.cache.length
  5395. var padBuff = Buffer.allocUnsafe(len)
  5396. var i = -1
  5397. while (++i < len) {
  5398. padBuff.writeUInt8(len, i)
  5399. }
  5400. return Buffer.concat([this.cache, padBuff])
  5401. }
  5402. function createCipheriv (suite, password, iv) {
  5403. var config = MODES[suite.toLowerCase()]
  5404. if (!config) throw new TypeError('invalid suite type')
  5405. if (typeof password === 'string') password = Buffer.from(password)
  5406. if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
  5407. if (typeof iv === 'string') iv = Buffer.from(iv)
  5408. if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
  5409. if (config.type === 'stream') {
  5410. return new StreamCipher(config.module, password, iv)
  5411. } else if (config.type === 'auth') {
  5412. return new AuthCipher(config.module, password, iv)
  5413. }
  5414. return new Cipher(config.module, password, iv)
  5415. }
  5416. function createCipher (suite, password) {
  5417. var config = MODES[suite.toLowerCase()]
  5418. if (!config) throw new TypeError('invalid suite type')
  5419. var keys = ebtk(password, false, config.key, config.iv)
  5420. return createCipheriv(suite, keys.key, keys.iv)
  5421. }
  5422. exports.createCipheriv = createCipheriv
  5423. exports.createCipher = createCipher
  5424. },{"./aes":20,"./authCipher":21,"./modes":33,"./streamCipher":36,"cipher-base":51,"evp_bytestokey":87,"inherits":104,"safe-buffer":157}],25:[function(require,module,exports){
  5425. var Buffer = require('safe-buffer').Buffer
  5426. var ZEROES = Buffer.alloc(16, 0)
  5427. function toArray (buf) {
  5428. return [
  5429. buf.readUInt32BE(0),
  5430. buf.readUInt32BE(4),
  5431. buf.readUInt32BE(8),
  5432. buf.readUInt32BE(12)
  5433. ]
  5434. }
  5435. function fromArray (out) {
  5436. var buf = Buffer.allocUnsafe(16)
  5437. buf.writeUInt32BE(out[0] >>> 0, 0)
  5438. buf.writeUInt32BE(out[1] >>> 0, 4)
  5439. buf.writeUInt32BE(out[2] >>> 0, 8)
  5440. buf.writeUInt32BE(out[3] >>> 0, 12)
  5441. return buf
  5442. }
  5443. function GHASH (key) {
  5444. this.h = key
  5445. this.state = Buffer.alloc(16, 0)
  5446. this.cache = Buffer.allocUnsafe(0)
  5447. }
  5448. // from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
  5449. // by Juho Vähä-Herttua
  5450. GHASH.prototype.ghash = function (block) {
  5451. var i = -1
  5452. while (++i < block.length) {
  5453. this.state[i] ^= block[i]
  5454. }
  5455. this._multiply()
  5456. }
  5457. GHASH.prototype._multiply = function () {
  5458. var Vi = toArray(this.h)
  5459. var Zi = [0, 0, 0, 0]
  5460. var j, xi, lsbVi
  5461. var i = -1
  5462. while (++i < 128) {
  5463. xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0
  5464. if (xi) {
  5465. // Z_i+1 = Z_i ^ V_i
  5466. Zi[0] ^= Vi[0]
  5467. Zi[1] ^= Vi[1]
  5468. Zi[2] ^= Vi[2]
  5469. Zi[3] ^= Vi[3]
  5470. }
  5471. // Store the value of LSB(V_i)
  5472. lsbVi = (Vi[3] & 1) !== 0
  5473. // V_i+1 = V_i >> 1
  5474. for (j = 3; j > 0; j--) {
  5475. Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31)
  5476. }
  5477. Vi[0] = Vi[0] >>> 1
  5478. // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
  5479. if (lsbVi) {
  5480. Vi[0] = Vi[0] ^ (0xe1 << 24)
  5481. }
  5482. }
  5483. this.state = fromArray(Zi)
  5484. }
  5485. GHASH.prototype.update = function (buf) {
  5486. this.cache = Buffer.concat([this.cache, buf])
  5487. var chunk
  5488. while (this.cache.length >= 16) {
  5489. chunk = this.cache.slice(0, 16)
  5490. this.cache = this.cache.slice(16)
  5491. this.ghash(chunk)
  5492. }
  5493. }
  5494. GHASH.prototype.final = function (abl, bl) {
  5495. if (this.cache.length) {
  5496. this.ghash(Buffer.concat([this.cache, ZEROES], 16))
  5497. }
  5498. this.ghash(fromArray([0, abl, 0, bl]))
  5499. return this.state
  5500. }
  5501. module.exports = GHASH
  5502. },{"safe-buffer":157}],26:[function(require,module,exports){
  5503. function incr32 (iv) {
  5504. var len = iv.length
  5505. var item
  5506. while (len--) {
  5507. item = iv.readUInt8(len)
  5508. if (item === 255) {
  5509. iv.writeUInt8(0, len)
  5510. } else {
  5511. item++
  5512. iv.writeUInt8(item, len)
  5513. break
  5514. }
  5515. }
  5516. }
  5517. module.exports = incr32
  5518. },{}],27:[function(require,module,exports){
  5519. var xor = require('buffer-xor')
  5520. exports.encrypt = function (self, block) {
  5521. var data = xor(block, self._prev)
  5522. self._prev = self._cipher.encryptBlock(data)
  5523. return self._prev
  5524. }
  5525. exports.decrypt = function (self, block) {
  5526. var pad = self._prev
  5527. self._prev = block
  5528. var out = self._cipher.decryptBlock(block)
  5529. return xor(out, pad)
  5530. }
  5531. },{"buffer-xor":49}],28:[function(require,module,exports){
  5532. var Buffer = require('safe-buffer').Buffer
  5533. var xor = require('buffer-xor')
  5534. function encryptStart (self, data, decrypt) {
  5535. var len = data.length
  5536. var out = xor(data, self._cache)
  5537. self._cache = self._cache.slice(len)
  5538. self._prev = Buffer.concat([self._prev, decrypt ? data : out])
  5539. return out
  5540. }
  5541. exports.encrypt = function (self, data, decrypt) {
  5542. var out = Buffer.allocUnsafe(0)
  5543. var len
  5544. while (data.length) {
  5545. if (self._cache.length === 0) {
  5546. self._cache = self._cipher.encryptBlock(self._prev)
  5547. self._prev = Buffer.allocUnsafe(0)
  5548. }
  5549. if (self._cache.length <= data.length) {
  5550. len = self._cache.length
  5551. out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)])
  5552. data = data.slice(len)
  5553. } else {
  5554. out = Buffer.concat([out, encryptStart(self, data, decrypt)])
  5555. break
  5556. }
  5557. }
  5558. return out
  5559. }
  5560. },{"buffer-xor":49,"safe-buffer":157}],29:[function(require,module,exports){
  5561. var Buffer = require('safe-buffer').Buffer
  5562. function encryptByte (self, byteParam, decrypt) {
  5563. var pad
  5564. var i = -1
  5565. var len = 8
  5566. var out = 0
  5567. var bit, value
  5568. while (++i < len) {
  5569. pad = self._cipher.encryptBlock(self._prev)
  5570. bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0
  5571. value = pad[0] ^ bit
  5572. out += ((value & 0x80) >> (i % 8))
  5573. self._prev = shiftIn(self._prev, decrypt ? bit : value)
  5574. }
  5575. return out
  5576. }
  5577. function shiftIn (buffer, value) {
  5578. var len = buffer.length
  5579. var i = -1
  5580. var out = Buffer.allocUnsafe(buffer.length)
  5581. buffer = Buffer.concat([buffer, Buffer.from([value])])
  5582. while (++i < len) {
  5583. out[i] = buffer[i] << 1 | buffer[i + 1] >> (7)
  5584. }
  5585. return out
  5586. }
  5587. exports.encrypt = function (self, chunk, decrypt) {
  5588. var len = chunk.length
  5589. var out = Buffer.allocUnsafe(len)
  5590. var i = -1
  5591. while (++i < len) {
  5592. out[i] = encryptByte(self, chunk[i], decrypt)
  5593. }
  5594. return out
  5595. }
  5596. },{"safe-buffer":157}],30:[function(require,module,exports){
  5597. var Buffer = require('safe-buffer').Buffer
  5598. function encryptByte (self, byteParam, decrypt) {
  5599. var pad = self._cipher.encryptBlock(self._prev)
  5600. var out = pad[0] ^ byteParam
  5601. self._prev = Buffer.concat([
  5602. self._prev.slice(1),
  5603. Buffer.from([decrypt ? byteParam : out])
  5604. ])
  5605. return out
  5606. }
  5607. exports.encrypt = function (self, chunk, decrypt) {
  5608. var len = chunk.length
  5609. var out = Buffer.allocUnsafe(len)
  5610. var i = -1
  5611. while (++i < len) {
  5612. out[i] = encryptByte(self, chunk[i], decrypt)
  5613. }
  5614. return out
  5615. }
  5616. },{"safe-buffer":157}],31:[function(require,module,exports){
  5617. var xor = require('buffer-xor')
  5618. var Buffer = require('safe-buffer').Buffer
  5619. var incr32 = require('../incr32')
  5620. function getBlock (self) {
  5621. var out = self._cipher.encryptBlockRaw(self._prev)
  5622. incr32(self._prev)
  5623. return out
  5624. }
  5625. var blockSize = 16
  5626. exports.encrypt = function (self, chunk) {
  5627. var chunkNum = Math.ceil(chunk.length / blockSize)
  5628. var start = self._cache.length
  5629. self._cache = Buffer.concat([
  5630. self._cache,
  5631. Buffer.allocUnsafe(chunkNum * blockSize)
  5632. ])
  5633. for (var i = 0; i < chunkNum; i++) {
  5634. var out = getBlock(self)
  5635. var offset = start + i * blockSize
  5636. self._cache.writeUInt32BE(out[0], offset + 0)
  5637. self._cache.writeUInt32BE(out[1], offset + 4)
  5638. self._cache.writeUInt32BE(out[2], offset + 8)
  5639. self._cache.writeUInt32BE(out[3], offset + 12)
  5640. }
  5641. var pad = self._cache.slice(0, chunk.length)
  5642. self._cache = self._cache.slice(chunk.length)
  5643. return xor(chunk, pad)
  5644. }
  5645. },{"../incr32":26,"buffer-xor":49,"safe-buffer":157}],32:[function(require,module,exports){
  5646. exports.encrypt = function (self, block) {
  5647. return self._cipher.encryptBlock(block)
  5648. }
  5649. exports.decrypt = function (self, block) {
  5650. return self._cipher.decryptBlock(block)
  5651. }
  5652. },{}],33:[function(require,module,exports){
  5653. var modeModules = {
  5654. ECB: require('./ecb'),
  5655. CBC: require('./cbc'),
  5656. CFB: require('./cfb'),
  5657. CFB8: require('./cfb8'),
  5658. CFB1: require('./cfb1'),
  5659. OFB: require('./ofb'),
  5660. CTR: require('./ctr'),
  5661. GCM: require('./ctr')
  5662. }
  5663. var modes = require('./list.json')
  5664. for (var key in modes) {
  5665. modes[key].module = modeModules[modes[key].mode]
  5666. }
  5667. module.exports = modes
  5668. },{"./cbc":27,"./cfb":28,"./cfb1":29,"./cfb8":30,"./ctr":31,"./ecb":32,"./list.json":34,"./ofb":35}],34:[function(require,module,exports){
  5669. module.exports={
  5670. "aes-128-ecb": {
  5671. "cipher": "AES",
  5672. "key": 128,
  5673. "iv": 0,
  5674. "mode": "ECB",
  5675. "type": "block"
  5676. },
  5677. "aes-192-ecb": {
  5678. "cipher": "AES",
  5679. "key": 192,
  5680. "iv": 0,
  5681. "mode": "ECB",
  5682. "type": "block"
  5683. },
  5684. "aes-256-ecb": {
  5685. "cipher": "AES",
  5686. "key": 256,
  5687. "iv": 0,
  5688. "mode": "ECB",
  5689. "type": "block"
  5690. },
  5691. "aes-128-cbc": {
  5692. "cipher": "AES",
  5693. "key": 128,
  5694. "iv": 16,
  5695. "mode": "CBC",
  5696. "type": "block"
  5697. },
  5698. "aes-192-cbc": {
  5699. "cipher": "AES",
  5700. "key": 192,
  5701. "iv": 16,
  5702. "mode": "CBC",
  5703. "type": "block"
  5704. },
  5705. "aes-256-cbc": {
  5706. "cipher": "AES",
  5707. "key": 256,
  5708. "iv": 16,
  5709. "mode": "CBC",
  5710. "type": "block"
  5711. },
  5712. "aes128": {
  5713. "cipher": "AES",
  5714. "key": 128,
  5715. "iv": 16,
  5716. "mode": "CBC",
  5717. "type": "block"
  5718. },
  5719. "aes192": {
  5720. "cipher": "AES",
  5721. "key": 192,
  5722. "iv": 16,
  5723. "mode": "CBC",
  5724. "type": "block"
  5725. },
  5726. "aes256": {
  5727. "cipher": "AES",
  5728. "key": 256,
  5729. "iv": 16,
  5730. "mode": "CBC",
  5731. "type": "block"
  5732. },
  5733. "aes-128-cfb": {
  5734. "cipher": "AES",
  5735. "key": 128,
  5736. "iv": 16,
  5737. "mode": "CFB",
  5738. "type": "stream"
  5739. },
  5740. "aes-192-cfb": {
  5741. "cipher": "AES",
  5742. "key": 192,
  5743. "iv": 16,
  5744. "mode": "CFB",
  5745. "type": "stream"
  5746. },
  5747. "aes-256-cfb": {
  5748. "cipher": "AES",
  5749. "key": 256,
  5750. "iv": 16,
  5751. "mode": "CFB",
  5752. "type": "stream"
  5753. },
  5754. "aes-128-cfb8": {
  5755. "cipher": "AES",
  5756. "key": 128,
  5757. "iv": 16,
  5758. "mode": "CFB8",
  5759. "type": "stream"
  5760. },
  5761. "aes-192-cfb8": {
  5762. "cipher": "AES",
  5763. "key": 192,
  5764. "iv": 16,
  5765. "mode": "CFB8",
  5766. "type": "stream"
  5767. },
  5768. "aes-256-cfb8": {
  5769. "cipher": "AES",
  5770. "key": 256,
  5771. "iv": 16,
  5772. "mode": "CFB8",
  5773. "type": "stream"
  5774. },
  5775. "aes-128-cfb1": {
  5776. "cipher": "AES",
  5777. "key": 128,
  5778. "iv": 16,
  5779. "mode": "CFB1",
  5780. "type": "stream"
  5781. },
  5782. "aes-192-cfb1": {
  5783. "cipher": "AES",
  5784. "key": 192,
  5785. "iv": 16,
  5786. "mode": "CFB1",
  5787. "type": "stream"
  5788. },
  5789. "aes-256-cfb1": {
  5790. "cipher": "AES",
  5791. "key": 256,
  5792. "iv": 16,
  5793. "mode": "CFB1",
  5794. "type": "stream"
  5795. },
  5796. "aes-128-ofb": {
  5797. "cipher": "AES",
  5798. "key": 128,
  5799. "iv": 16,
  5800. "mode": "OFB",
  5801. "type": "stream"
  5802. },
  5803. "aes-192-ofb": {
  5804. "cipher": "AES",
  5805. "key": 192,
  5806. "iv": 16,
  5807. "mode": "OFB",
  5808. "type": "stream"
  5809. },
  5810. "aes-256-ofb": {
  5811. "cipher": "AES",
  5812. "key": 256,
  5813. "iv": 16,
  5814. "mode": "OFB",
  5815. "type": "stream"
  5816. },
  5817. "aes-128-ctr": {
  5818. "cipher": "AES",
  5819. "key": 128,
  5820. "iv": 16,
  5821. "mode": "CTR",
  5822. "type": "stream"
  5823. },
  5824. "aes-192-ctr": {
  5825. "cipher": "AES",
  5826. "key": 192,
  5827. "iv": 16,
  5828. "mode": "CTR",
  5829. "type": "stream"
  5830. },
  5831. "aes-256-ctr": {
  5832. "cipher": "AES",
  5833. "key": 256,
  5834. "iv": 16,
  5835. "mode": "CTR",
  5836. "type": "stream"
  5837. },
  5838. "aes-128-gcm": {
  5839. "cipher": "AES",
  5840. "key": 128,
  5841. "iv": 12,
  5842. "mode": "GCM",
  5843. "type": "auth"
  5844. },
  5845. "aes-192-gcm": {
  5846. "cipher": "AES",
  5847. "key": 192,
  5848. "iv": 12,
  5849. "mode": "GCM",
  5850. "type": "auth"
  5851. },
  5852. "aes-256-gcm": {
  5853. "cipher": "AES",
  5854. "key": 256,
  5855. "iv": 12,
  5856. "mode": "GCM",
  5857. "type": "auth"
  5858. }
  5859. }
  5860. },{}],35:[function(require,module,exports){
  5861. (function (Buffer){
  5862. var xor = require('buffer-xor')
  5863. function getBlock (self) {
  5864. self._prev = self._cipher.encryptBlock(self._prev)
  5865. return self._prev
  5866. }
  5867. exports.encrypt = function (self, chunk) {
  5868. while (self._cache.length < chunk.length) {
  5869. self._cache = Buffer.concat([self._cache, getBlock(self)])
  5870. }
  5871. var pad = self._cache.slice(0, chunk.length)
  5872. self._cache = self._cache.slice(chunk.length)
  5873. return xor(chunk, pad)
  5874. }
  5875. }).call(this,require("buffer").Buffer)
  5876. },{"buffer":50,"buffer-xor":49}],36:[function(require,module,exports){
  5877. var aes = require('./aes')
  5878. var Buffer = require('safe-buffer').Buffer
  5879. var Transform = require('cipher-base')
  5880. var inherits = require('inherits')
  5881. function StreamCipher (mode, key, iv, decrypt) {
  5882. Transform.call(this)
  5883. this._cipher = new aes.AES(key)
  5884. this._prev = Buffer.from(iv)
  5885. this._cache = Buffer.allocUnsafe(0)
  5886. this._secCache = Buffer.allocUnsafe(0)
  5887. this._decrypt = decrypt
  5888. this._mode = mode
  5889. }
  5890. inherits(StreamCipher, Transform)
  5891. StreamCipher.prototype._update = function (chunk) {
  5892. return this._mode.encrypt(this, chunk, this._decrypt)
  5893. }
  5894. StreamCipher.prototype._final = function () {
  5895. this._cipher.scrub()
  5896. }
  5897. module.exports = StreamCipher
  5898. },{"./aes":20,"cipher-base":51,"inherits":104,"safe-buffer":157}],37:[function(require,module,exports){
  5899. var ebtk = require('evp_bytestokey')
  5900. var aes = require('browserify-aes/browser')
  5901. var DES = require('browserify-des')
  5902. var desModes = require('browserify-des/modes')
  5903. var aesModes = require('browserify-aes/modes')
  5904. function createCipher (suite, password) {
  5905. var keyLen, ivLen
  5906. suite = suite.toLowerCase()
  5907. if (aesModes[suite]) {
  5908. keyLen = aesModes[suite].key
  5909. ivLen = aesModes[suite].iv
  5910. } else if (desModes[suite]) {
  5911. keyLen = desModes[suite].key * 8
  5912. ivLen = desModes[suite].iv
  5913. } else {
  5914. throw new TypeError('invalid suite type')
  5915. }
  5916. var keys = ebtk(password, false, keyLen, ivLen)
  5917. return createCipheriv(suite, keys.key, keys.iv)
  5918. }
  5919. function createDecipher (suite, password) {
  5920. var keyLen, ivLen
  5921. suite = suite.toLowerCase()
  5922. if (aesModes[suite]) {
  5923. keyLen = aesModes[suite].key
  5924. ivLen = aesModes[suite].iv
  5925. } else if (desModes[suite]) {
  5926. keyLen = desModes[suite].key * 8
  5927. ivLen = desModes[suite].iv
  5928. } else {
  5929. throw new TypeError('invalid suite type')
  5930. }
  5931. var keys = ebtk(password, false, keyLen, ivLen)
  5932. return createDecipheriv(suite, keys.key, keys.iv)
  5933. }
  5934. function createCipheriv (suite, key, iv) {
  5935. suite = suite.toLowerCase()
  5936. if (aesModes[suite]) {
  5937. return aes.createCipheriv(suite, key, iv)
  5938. } else if (desModes[suite]) {
  5939. return new DES({
  5940. key: key,
  5941. iv: iv,
  5942. mode: suite
  5943. })
  5944. } else {
  5945. throw new TypeError('invalid suite type')
  5946. }
  5947. }
  5948. function createDecipheriv (suite, key, iv) {
  5949. suite = suite.toLowerCase()
  5950. if (aesModes[suite]) {
  5951. return aes.createDecipheriv(suite, key, iv)
  5952. } else if (desModes[suite]) {
  5953. return new DES({
  5954. key: key,
  5955. iv: iv,
  5956. mode: suite,
  5957. decrypt: true
  5958. })
  5959. } else {
  5960. throw new TypeError('invalid suite type')
  5961. }
  5962. }
  5963. exports.createCipher = exports.Cipher = createCipher
  5964. exports.createCipheriv = exports.Cipheriv = createCipheriv
  5965. exports.createDecipher = exports.Decipher = createDecipher
  5966. exports.createDecipheriv = exports.Decipheriv = createDecipheriv
  5967. function getCiphers () {
  5968. return Object.keys(desModes).concat(aes.getCiphers())
  5969. }
  5970. exports.listCiphers = exports.getCiphers = getCiphers
  5971. },{"browserify-aes/browser":22,"browserify-aes/modes":33,"browserify-des":38,"browserify-des/modes":39,"evp_bytestokey":87}],38:[function(require,module,exports){
  5972. (function (Buffer){
  5973. var CipherBase = require('cipher-base')
  5974. var des = require('des.js')
  5975. var inherits = require('inherits')
  5976. var modes = {
  5977. 'des-ede3-cbc': des.CBC.instantiate(des.EDE),
  5978. 'des-ede3': des.EDE,
  5979. 'des-ede-cbc': des.CBC.instantiate(des.EDE),
  5980. 'des-ede': des.EDE,
  5981. 'des-cbc': des.CBC.instantiate(des.DES),
  5982. 'des-ecb': des.DES
  5983. }
  5984. modes.des = modes['des-cbc']
  5985. modes.des3 = modes['des-ede3-cbc']
  5986. module.exports = DES
  5987. inherits(DES, CipherBase)
  5988. function DES (opts) {
  5989. CipherBase.call(this)
  5990. var modeName = opts.mode.toLowerCase()
  5991. var mode = modes[modeName]
  5992. var type
  5993. if (opts.decrypt) {
  5994. type = 'decrypt'
  5995. } else {
  5996. type = 'encrypt'
  5997. }
  5998. var key = opts.key
  5999. if (modeName === 'des-ede' || modeName === 'des-ede-cbc') {
  6000. key = Buffer.concat([key, key.slice(0, 8)])
  6001. }
  6002. var iv = opts.iv
  6003. this._des = mode.create({
  6004. key: key,
  6005. iv: iv,
  6006. type: type
  6007. })
  6008. }
  6009. DES.prototype._update = function (data) {
  6010. return new Buffer(this._des.update(data))
  6011. }
  6012. DES.prototype._final = function () {
  6013. return new Buffer(this._des.final())
  6014. }
  6015. }).call(this,require("buffer").Buffer)
  6016. },{"buffer":50,"cipher-base":51,"des.js":60,"inherits":104}],39:[function(require,module,exports){
  6017. exports['des-ecb'] = {
  6018. key: 8,
  6019. iv: 0
  6020. }
  6021. exports['des-cbc'] = exports.des = {
  6022. key: 8,
  6023. iv: 8
  6024. }
  6025. exports['des-ede3-cbc'] = exports.des3 = {
  6026. key: 24,
  6027. iv: 8
  6028. }
  6029. exports['des-ede3'] = {
  6030. key: 24,
  6031. iv: 0
  6032. }
  6033. exports['des-ede-cbc'] = {
  6034. key: 16,
  6035. iv: 8
  6036. }
  6037. exports['des-ede'] = {
  6038. key: 16,
  6039. iv: 0
  6040. }
  6041. },{}],40:[function(require,module,exports){
  6042. (function (Buffer){
  6043. var bn = require('bn.js');
  6044. var randomBytes = require('randombytes');
  6045. module.exports = crt;
  6046. function blind(priv) {
  6047. var r = getr(priv);
  6048. var blinder = r.toRed(bn.mont(priv.modulus))
  6049. .redPow(new bn(priv.publicExponent)).fromRed();
  6050. return {
  6051. blinder: blinder,
  6052. unblinder:r.invm(priv.modulus)
  6053. };
  6054. }
  6055. function crt(msg, priv) {
  6056. var blinds = blind(priv);
  6057. var len = priv.modulus.byteLength();
  6058. var mod = bn.mont(priv.modulus);
  6059. var blinded = new bn(msg).mul(blinds.blinder).umod(priv.modulus);
  6060. var c1 = blinded.toRed(bn.mont(priv.prime1));
  6061. var c2 = blinded.toRed(bn.mont(priv.prime2));
  6062. var qinv = priv.coefficient;
  6063. var p = priv.prime1;
  6064. var q = priv.prime2;
  6065. var m1 = c1.redPow(priv.exponent1);
  6066. var m2 = c2.redPow(priv.exponent2);
  6067. m1 = m1.fromRed();
  6068. m2 = m2.fromRed();
  6069. var h = m1.isub(m2).imul(qinv).umod(p);
  6070. h.imul(q);
  6071. m2.iadd(h);
  6072. return new Buffer(m2.imul(blinds.unblinder).umod(priv.modulus).toArray(false, len));
  6073. }
  6074. crt.getr = getr;
  6075. function getr(priv) {
  6076. var len = priv.modulus.byteLength();
  6077. var r = new bn(randomBytes(len));
  6078. while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)) {
  6079. r = new bn(randomBytes(len));
  6080. }
  6081. return r;
  6082. }
  6083. }).call(this,require("buffer").Buffer)
  6084. },{"bn.js":17,"buffer":50,"randombytes":141}],41:[function(require,module,exports){
  6085. module.exports = require('./browser/algorithms.json')
  6086. },{"./browser/algorithms.json":42}],42:[function(require,module,exports){
  6087. module.exports={
  6088. "sha224WithRSAEncryption": {
  6089. "sign": "rsa",
  6090. "hash": "sha224",
  6091. "id": "302d300d06096086480165030402040500041c"
  6092. },
  6093. "RSA-SHA224": {
  6094. "sign": "ecdsa/rsa",
  6095. "hash": "sha224",
  6096. "id": "302d300d06096086480165030402040500041c"
  6097. },
  6098. "sha256WithRSAEncryption": {
  6099. "sign": "rsa",
  6100. "hash": "sha256",
  6101. "id": "3031300d060960864801650304020105000420"
  6102. },
  6103. "RSA-SHA256": {
  6104. "sign": "ecdsa/rsa",
  6105. "hash": "sha256",
  6106. "id": "3031300d060960864801650304020105000420"
  6107. },
  6108. "sha384WithRSAEncryption": {
  6109. "sign": "rsa",
  6110. "hash": "sha384",
  6111. "id": "3041300d060960864801650304020205000430"
  6112. },
  6113. "RSA-SHA384": {
  6114. "sign": "ecdsa/rsa",
  6115. "hash": "sha384",
  6116. "id": "3041300d060960864801650304020205000430"
  6117. },
  6118. "sha512WithRSAEncryption": {
  6119. "sign": "rsa",
  6120. "hash": "sha512",
  6121. "id": "3051300d060960864801650304020305000440"
  6122. },
  6123. "RSA-SHA512": {
  6124. "sign": "ecdsa/rsa",
  6125. "hash": "sha512",
  6126. "id": "3051300d060960864801650304020305000440"
  6127. },
  6128. "RSA-SHA1": {
  6129. "sign": "rsa",
  6130. "hash": "sha1",
  6131. "id": "3021300906052b0e03021a05000414"
  6132. },
  6133. "ecdsa-with-SHA1": {
  6134. "sign": "ecdsa",
  6135. "hash": "sha1",
  6136. "id": ""
  6137. },
  6138. "sha256": {
  6139. "sign": "ecdsa",
  6140. "hash": "sha256",
  6141. "id": ""
  6142. },
  6143. "sha224": {
  6144. "sign": "ecdsa",
  6145. "hash": "sha224",
  6146. "id": ""
  6147. },
  6148. "sha384": {
  6149. "sign": "ecdsa",
  6150. "hash": "sha384",
  6151. "id": ""
  6152. },
  6153. "sha512": {
  6154. "sign": "ecdsa",
  6155. "hash": "sha512",
  6156. "id": ""
  6157. },
  6158. "DSA-SHA": {
  6159. "sign": "dsa",
  6160. "hash": "sha1",
  6161. "id": ""
  6162. },
  6163. "DSA-SHA1": {
  6164. "sign": "dsa",
  6165. "hash": "sha1",
  6166. "id": ""
  6167. },
  6168. "DSA": {
  6169. "sign": "dsa",
  6170. "hash": "sha1",
  6171. "id": ""
  6172. },
  6173. "DSA-WITH-SHA224": {
  6174. "sign": "dsa",
  6175. "hash": "sha224",
  6176. "id": ""
  6177. },
  6178. "DSA-SHA224": {
  6179. "sign": "dsa",
  6180. "hash": "sha224",
  6181. "id": ""
  6182. },
  6183. "DSA-WITH-SHA256": {
  6184. "sign": "dsa",
  6185. "hash": "sha256",
  6186. "id": ""
  6187. },
  6188. "DSA-SHA256": {
  6189. "sign": "dsa",
  6190. "hash": "sha256",
  6191. "id": ""
  6192. },
  6193. "DSA-WITH-SHA384": {
  6194. "sign": "dsa",
  6195. "hash": "sha384",
  6196. "id": ""
  6197. },
  6198. "DSA-SHA384": {
  6199. "sign": "dsa",
  6200. "hash": "sha384",
  6201. "id": ""
  6202. },
  6203. "DSA-WITH-SHA512": {
  6204. "sign": "dsa",
  6205. "hash": "sha512",
  6206. "id": ""
  6207. },
  6208. "DSA-SHA512": {
  6209. "sign": "dsa",
  6210. "hash": "sha512",
  6211. "id": ""
  6212. },
  6213. "DSA-RIPEMD160": {
  6214. "sign": "dsa",
  6215. "hash": "rmd160",
  6216. "id": ""
  6217. },
  6218. "ripemd160WithRSA": {
  6219. "sign": "rsa",
  6220. "hash": "rmd160",
  6221. "id": "3021300906052b2403020105000414"
  6222. },
  6223. "RSA-RIPEMD160": {
  6224. "sign": "rsa",
  6225. "hash": "rmd160",
  6226. "id": "3021300906052b2403020105000414"
  6227. },
  6228. "md5WithRSAEncryption": {
  6229. "sign": "rsa",
  6230. "hash": "md5",
  6231. "id": "3020300c06082a864886f70d020505000410"
  6232. },
  6233. "RSA-MD5": {
  6234. "sign": "rsa",
  6235. "hash": "md5",
  6236. "id": "3020300c06082a864886f70d020505000410"
  6237. }
  6238. }
  6239. },{}],43:[function(require,module,exports){
  6240. module.exports={
  6241. "1.3.132.0.10": "secp256k1",
  6242. "1.3.132.0.33": "p224",
  6243. "1.2.840.10045.3.1.1": "p192",
  6244. "1.2.840.10045.3.1.7": "p256",
  6245. "1.3.132.0.34": "p384",
  6246. "1.3.132.0.35": "p521"
  6247. }
  6248. },{}],44:[function(require,module,exports){
  6249. (function (Buffer){
  6250. var createHash = require('create-hash')
  6251. var stream = require('stream')
  6252. var inherits = require('inherits')
  6253. var sign = require('./sign')
  6254. var verify = require('./verify')
  6255. var algorithms = require('./algorithms.json')
  6256. Object.keys(algorithms).forEach(function (key) {
  6257. algorithms[key].id = new Buffer(algorithms[key].id, 'hex')
  6258. algorithms[key.toLowerCase()] = algorithms[key]
  6259. })
  6260. function Sign (algorithm) {
  6261. stream.Writable.call(this)
  6262. var data = algorithms[algorithm]
  6263. if (!data) throw new Error('Unknown message digest')
  6264. this._hashType = data.hash
  6265. this._hash = createHash(data.hash)
  6266. this._tag = data.id
  6267. this._signType = data.sign
  6268. }
  6269. inherits(Sign, stream.Writable)
  6270. Sign.prototype._write = function _write (data, _, done) {
  6271. this._hash.update(data)
  6272. done()
  6273. }
  6274. Sign.prototype.update = function update (data, enc) {
  6275. if (typeof data === 'string') data = new Buffer(data, enc)
  6276. this._hash.update(data)
  6277. return this
  6278. }
  6279. Sign.prototype.sign = function signMethod (key, enc) {
  6280. this.end()
  6281. var hash = this._hash.digest()
  6282. var sig = sign(hash, key, this._hashType, this._signType, this._tag)
  6283. return enc ? sig.toString(enc) : sig
  6284. }
  6285. function Verify (algorithm) {
  6286. stream.Writable.call(this)
  6287. var data = algorithms[algorithm]
  6288. if (!data) throw new Error('Unknown message digest')
  6289. this._hash = createHash(data.hash)
  6290. this._tag = data.id
  6291. this._signType = data.sign
  6292. }
  6293. inherits(Verify, stream.Writable)
  6294. Verify.prototype._write = function _write (data, _, done) {
  6295. this._hash.update(data)
  6296. done()
  6297. }
  6298. Verify.prototype.update = function update (data, enc) {
  6299. if (typeof data === 'string') data = new Buffer(data, enc)
  6300. this._hash.update(data)
  6301. return this
  6302. }
  6303. Verify.prototype.verify = function verifyMethod (key, sig, enc) {
  6304. if (typeof sig === 'string') sig = new Buffer(sig, enc)
  6305. this.end()
  6306. var hash = this._hash.digest()
  6307. return verify(sig, hash, key, this._signType, this._tag)
  6308. }
  6309. function createSign (algorithm) {
  6310. return new Sign(algorithm)
  6311. }
  6312. function createVerify (algorithm) {
  6313. return new Verify(algorithm)
  6314. }
  6315. module.exports = {
  6316. Sign: createSign,
  6317. Verify: createVerify,
  6318. createSign: createSign,
  6319. createVerify: createVerify
  6320. }
  6321. }).call(this,require("buffer").Buffer)
  6322. },{"./algorithms.json":42,"./sign":45,"./verify":46,"buffer":50,"create-hash":54,"inherits":104,"stream":166}],45:[function(require,module,exports){
  6323. (function (Buffer){
  6324. // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
  6325. var createHmac = require('create-hmac')
  6326. var crt = require('browserify-rsa')
  6327. var EC = require('elliptic').ec
  6328. var BN = require('bn.js')
  6329. var parseKeys = require('parse-asn1')
  6330. var curves = require('./curves.json')
  6331. function sign (hash, key, hashType, signType, tag) {
  6332. var priv = parseKeys(key)
  6333. if (priv.curve) {
  6334. // rsa keys can be interpreted as ecdsa ones in openssl
  6335. if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
  6336. return ecSign(hash, priv)
  6337. } else if (priv.type === 'dsa') {
  6338. if (signType !== 'dsa') throw new Error('wrong private key type')
  6339. return dsaSign(hash, priv, hashType)
  6340. } else {
  6341. if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
  6342. }
  6343. hash = Buffer.concat([tag, hash])
  6344. var len = priv.modulus.byteLength()
  6345. var pad = [ 0, 1 ]
  6346. while (hash.length + pad.length + 1 < len) pad.push(0xff)
  6347. pad.push(0x00)
  6348. var i = -1
  6349. while (++i < hash.length) pad.push(hash[i])
  6350. var out = crt(pad, priv)
  6351. return out
  6352. }
  6353. function ecSign (hash, priv) {
  6354. var curveId = curves[priv.curve.join('.')]
  6355. if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.'))
  6356. var curve = new EC(curveId)
  6357. var key = curve.keyFromPrivate(priv.privateKey)
  6358. var out = key.sign(hash)
  6359. return new Buffer(out.toDER())
  6360. }
  6361. function dsaSign (hash, priv, algo) {
  6362. var x = priv.params.priv_key
  6363. var p = priv.params.p
  6364. var q = priv.params.q
  6365. var g = priv.params.g
  6366. var r = new BN(0)
  6367. var k
  6368. var H = bits2int(hash, q).mod(q)
  6369. var s = false
  6370. var kv = getKey(x, q, hash, algo)
  6371. while (s === false) {
  6372. k = makeKey(q, kv, algo)
  6373. r = makeR(g, k, p, q)
  6374. s = k.invm(q).imul(H.add(x.mul(r))).mod(q)
  6375. if (s.cmpn(0) === 0) {
  6376. s = false
  6377. r = new BN(0)
  6378. }
  6379. }
  6380. return toDER(r, s)
  6381. }
  6382. function toDER (r, s) {
  6383. r = r.toArray()
  6384. s = s.toArray()
  6385. // Pad values
  6386. if (r[0] & 0x80) r = [ 0 ].concat(r)
  6387. if (s[0] & 0x80) s = [ 0 ].concat(s)
  6388. var total = r.length + s.length + 4
  6389. var res = [ 0x30, total, 0x02, r.length ]
  6390. res = res.concat(r, [ 0x02, s.length ], s)
  6391. return new Buffer(res)
  6392. }
  6393. function getKey (x, q, hash, algo) {
  6394. x = new Buffer(x.toArray())
  6395. if (x.length < q.byteLength()) {
  6396. var zeros = new Buffer(q.byteLength() - x.length)
  6397. zeros.fill(0)
  6398. x = Buffer.concat([ zeros, x ])
  6399. }
  6400. var hlen = hash.length
  6401. var hbits = bits2octets(hash, q)
  6402. var v = new Buffer(hlen)
  6403. v.fill(1)
  6404. var k = new Buffer(hlen)
  6405. k.fill(0)
  6406. k = createHmac(algo, k).update(v).update(new Buffer([ 0 ])).update(x).update(hbits).digest()
  6407. v = createHmac(algo, k).update(v).digest()
  6408. k = createHmac(algo, k).update(v).update(new Buffer([ 1 ])).update(x).update(hbits).digest()
  6409. v = createHmac(algo, k).update(v).digest()
  6410. return { k: k, v: v }
  6411. }
  6412. function bits2int (obits, q) {
  6413. var bits = new BN(obits)
  6414. var shift = (obits.length << 3) - q.bitLength()
  6415. if (shift > 0) bits.ishrn(shift)
  6416. return bits
  6417. }
  6418. function bits2octets (bits, q) {
  6419. bits = bits2int(bits, q)
  6420. bits = bits.mod(q)
  6421. var out = new Buffer(bits.toArray())
  6422. if (out.length < q.byteLength()) {
  6423. var zeros = new Buffer(q.byteLength() - out.length)
  6424. zeros.fill(0)
  6425. out = Buffer.concat([ zeros, out ])
  6426. }
  6427. return out
  6428. }
  6429. function makeKey (q, kv, algo) {
  6430. var t
  6431. var k
  6432. do {
  6433. t = new Buffer(0)
  6434. while (t.length * 8 < q.bitLength()) {
  6435. kv.v = createHmac(algo, kv.k).update(kv.v).digest()
  6436. t = Buffer.concat([ t, kv.v ])
  6437. }
  6438. k = bits2int(t, q)
  6439. kv.k = createHmac(algo, kv.k).update(kv.v).update(new Buffer([ 0 ])).digest()
  6440. kv.v = createHmac(algo, kv.k).update(kv.v).digest()
  6441. } while (k.cmp(q) !== -1)
  6442. return k
  6443. }
  6444. function makeR (g, k, p, q) {
  6445. return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q)
  6446. }
  6447. module.exports = sign
  6448. module.exports.getKey = getKey
  6449. module.exports.makeKey = makeKey
  6450. }).call(this,require("buffer").Buffer)
  6451. },{"./curves.json":43,"bn.js":17,"browserify-rsa":40,"buffer":50,"create-hmac":57,"elliptic":70,"parse-asn1":127}],46:[function(require,module,exports){
  6452. (function (Buffer){
  6453. // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
  6454. var BN = require('bn.js')
  6455. var EC = require('elliptic').ec
  6456. var parseKeys = require('parse-asn1')
  6457. var curves = require('./curves.json')
  6458. function verify (sig, hash, key, signType, tag) {
  6459. var pub = parseKeys(key)
  6460. if (pub.type === 'ec') {
  6461. // rsa keys can be interpreted as ecdsa ones in openssl
  6462. if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
  6463. return ecVerify(sig, hash, pub)
  6464. } else if (pub.type === 'dsa') {
  6465. if (signType !== 'dsa') throw new Error('wrong public key type')
  6466. return dsaVerify(sig, hash, pub)
  6467. } else {
  6468. if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
  6469. }
  6470. hash = Buffer.concat([tag, hash])
  6471. var len = pub.modulus.byteLength()
  6472. var pad = [ 1 ]
  6473. var padNum = 0
  6474. while (hash.length + pad.length + 2 < len) {
  6475. pad.push(0xff)
  6476. padNum++
  6477. }
  6478. pad.push(0x00)
  6479. var i = -1
  6480. while (++i < hash.length) {
  6481. pad.push(hash[i])
  6482. }
  6483. pad = new Buffer(pad)
  6484. var red = BN.mont(pub.modulus)
  6485. sig = new BN(sig).toRed(red)
  6486. sig = sig.redPow(new BN(pub.publicExponent))
  6487. sig = new Buffer(sig.fromRed().toArray())
  6488. var out = padNum < 8 ? 1 : 0
  6489. len = Math.min(sig.length, pad.length)
  6490. if (sig.length !== pad.length) out = 1
  6491. i = -1
  6492. while (++i < len) out |= sig[i] ^ pad[i]
  6493. return out === 0
  6494. }
  6495. function ecVerify (sig, hash, pub) {
  6496. var curveId = curves[pub.data.algorithm.curve.join('.')]
  6497. if (!curveId) throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.'))
  6498. var curve = new EC(curveId)
  6499. var pubkey = pub.data.subjectPrivateKey.data
  6500. return curve.verify(hash, sig, pubkey)
  6501. }
  6502. function dsaVerify (sig, hash, pub) {
  6503. var p = pub.data.p
  6504. var q = pub.data.q
  6505. var g = pub.data.g
  6506. var y = pub.data.pub_key
  6507. var unpacked = parseKeys.signature.decode(sig, 'der')
  6508. var s = unpacked.s
  6509. var r = unpacked.r
  6510. checkValue(s, q)
  6511. checkValue(r, q)
  6512. var montp = BN.mont(p)
  6513. var w = s.invm(q)
  6514. var v = g.toRed(montp)
  6515. .redPow(new BN(hash).mul(w).mod(q))
  6516. .fromRed()
  6517. .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed())
  6518. .mod(p)
  6519. .mod(q)
  6520. return v.cmp(r) === 0
  6521. }
  6522. function checkValue (b, q) {
  6523. if (b.cmpn(0) <= 0) throw new Error('invalid sig')
  6524. if (b.cmp(q) >= q) throw new Error('invalid sig')
  6525. }
  6526. module.exports = verify
  6527. }).call(this,require("buffer").Buffer)
  6528. },{"./curves.json":43,"bn.js":17,"buffer":50,"elliptic":70,"parse-asn1":127}],47:[function(require,module,exports){
  6529. (function (process,Buffer){
  6530. 'use strict';
  6531. /* eslint camelcase: "off" */
  6532. var assert = require('assert');
  6533. var Zstream = require('pako/lib/zlib/zstream');
  6534. var zlib_deflate = require('pako/lib/zlib/deflate.js');
  6535. var zlib_inflate = require('pako/lib/zlib/inflate.js');
  6536. var constants = require('pako/lib/zlib/constants');
  6537. for (var key in constants) {
  6538. exports[key] = constants[key];
  6539. }
  6540. // zlib modes
  6541. exports.NONE = 0;
  6542. exports.DEFLATE = 1;
  6543. exports.INFLATE = 2;
  6544. exports.GZIP = 3;
  6545. exports.GUNZIP = 4;
  6546. exports.DEFLATERAW = 5;
  6547. exports.INFLATERAW = 6;
  6548. exports.UNZIP = 7;
  6549. var GZIP_HEADER_ID1 = 0x1f;
  6550. var GZIP_HEADER_ID2 = 0x8b;
  6551. /**
  6552. * Emulate Node's zlib C++ layer for use by the JS layer in index.js
  6553. */
  6554. function Zlib(mode) {
  6555. if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) {
  6556. throw new TypeError('Bad argument');
  6557. }
  6558. this.dictionary = null;
  6559. this.err = 0;
  6560. this.flush = 0;
  6561. this.init_done = false;
  6562. this.level = 0;
  6563. this.memLevel = 0;
  6564. this.mode = mode;
  6565. this.strategy = 0;
  6566. this.windowBits = 0;
  6567. this.write_in_progress = false;
  6568. this.pending_close = false;
  6569. this.gzip_id_bytes_read = 0;
  6570. }
  6571. Zlib.prototype.close = function () {
  6572. if (this.write_in_progress) {
  6573. this.pending_close = true;
  6574. return;
  6575. }
  6576. this.pending_close = false;
  6577. assert(this.init_done, 'close before init');
  6578. assert(this.mode <= exports.UNZIP);
  6579. if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) {
  6580. zlib_deflate.deflateEnd(this.strm);
  6581. } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) {
  6582. zlib_inflate.inflateEnd(this.strm);
  6583. }
  6584. this.mode = exports.NONE;
  6585. this.dictionary = null;
  6586. };
  6587. Zlib.prototype.write = function (flush, input, in_off, in_len, out, out_off, out_len) {
  6588. return this._write(true, flush, input, in_off, in_len, out, out_off, out_len);
  6589. };
  6590. Zlib.prototype.writeSync = function (flush, input, in_off, in_len, out, out_off, out_len) {
  6591. return this._write(false, flush, input, in_off, in_len, out, out_off, out_len);
  6592. };
  6593. Zlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) {
  6594. assert.equal(arguments.length, 8);
  6595. assert(this.init_done, 'write before init');
  6596. assert(this.mode !== exports.NONE, 'already finalized');
  6597. assert.equal(false, this.write_in_progress, 'write already in progress');
  6598. assert.equal(false, this.pending_close, 'close is pending');
  6599. this.write_in_progress = true;
  6600. assert.equal(false, flush === undefined, 'must provide flush value');
  6601. this.write_in_progress = true;
  6602. if (flush !== exports.Z_NO_FLUSH && flush !== exports.Z_PARTIAL_FLUSH && flush !== exports.Z_SYNC_FLUSH && flush !== exports.Z_FULL_FLUSH && flush !== exports.Z_FINISH && flush !== exports.Z_BLOCK) {
  6603. throw new Error('Invalid flush value');
  6604. }
  6605. if (input == null) {
  6606. input = Buffer.alloc(0);
  6607. in_len = 0;
  6608. in_off = 0;
  6609. }
  6610. this.strm.avail_in = in_len;
  6611. this.strm.input = input;
  6612. this.strm.next_in = in_off;
  6613. this.strm.avail_out = out_len;
  6614. this.strm.output = out;
  6615. this.strm.next_out = out_off;
  6616. this.flush = flush;
  6617. if (!async) {
  6618. // sync version
  6619. this._process();
  6620. if (this._checkError()) {
  6621. return this._afterSync();
  6622. }
  6623. return;
  6624. }
  6625. // async version
  6626. var self = this;
  6627. process.nextTick(function () {
  6628. self._process();
  6629. self._after();
  6630. });
  6631. return this;
  6632. };
  6633. Zlib.prototype._afterSync = function () {
  6634. var avail_out = this.strm.avail_out;
  6635. var avail_in = this.strm.avail_in;
  6636. this.write_in_progress = false;
  6637. return [avail_in, avail_out];
  6638. };
  6639. Zlib.prototype._process = function () {
  6640. var next_expected_header_byte = null;
  6641. // If the avail_out is left at 0, then it means that it ran out
  6642. // of room. If there was avail_out left over, then it means
  6643. // that all of the input was consumed.
  6644. switch (this.mode) {
  6645. case exports.DEFLATE:
  6646. case exports.GZIP:
  6647. case exports.DEFLATERAW:
  6648. this.err = zlib_deflate.deflate(this.strm, this.flush);
  6649. break;
  6650. case exports.UNZIP:
  6651. if (this.strm.avail_in > 0) {
  6652. next_expected_header_byte = this.strm.next_in;
  6653. }
  6654. switch (this.gzip_id_bytes_read) {
  6655. case 0:
  6656. if (next_expected_header_byte === null) {
  6657. break;
  6658. }
  6659. if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) {
  6660. this.gzip_id_bytes_read = 1;
  6661. next_expected_header_byte++;
  6662. if (this.strm.avail_in === 1) {
  6663. // The only available byte was already read.
  6664. break;
  6665. }
  6666. } else {
  6667. this.mode = exports.INFLATE;
  6668. break;
  6669. }
  6670. // fallthrough
  6671. case 1:
  6672. if (next_expected_header_byte === null) {
  6673. break;
  6674. }
  6675. if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) {
  6676. this.gzip_id_bytes_read = 2;
  6677. this.mode = exports.GUNZIP;
  6678. } else {
  6679. // There is no actual difference between INFLATE and INFLATERAW
  6680. // (after initialization).
  6681. this.mode = exports.INFLATE;
  6682. }
  6683. break;
  6684. default:
  6685. throw new Error('invalid number of gzip magic number bytes read');
  6686. }
  6687. // fallthrough
  6688. case exports.INFLATE:
  6689. case exports.GUNZIP:
  6690. case exports.INFLATERAW:
  6691. this.err = zlib_inflate.inflate(this.strm, this.flush
  6692. // If data was encoded with dictionary
  6693. );if (this.err === exports.Z_NEED_DICT && this.dictionary) {
  6694. // Load it
  6695. this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary);
  6696. if (this.err === exports.Z_OK) {
  6697. // And try to decode again
  6698. this.err = zlib_inflate.inflate(this.strm, this.flush);
  6699. } else if (this.err === exports.Z_DATA_ERROR) {
  6700. // Both inflateSetDictionary() and inflate() return Z_DATA_ERROR.
  6701. // Make it possible for After() to tell a bad dictionary from bad
  6702. // input.
  6703. this.err = exports.Z_NEED_DICT;
  6704. }
  6705. }
  6706. while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0x00) {
  6707. // Bytes remain in input buffer. Perhaps this is another compressed
  6708. // member in the same archive, or just trailing garbage.
  6709. // Trailing zero bytes are okay, though, since they are frequently
  6710. // used for padding.
  6711. this.reset();
  6712. this.err = zlib_inflate.inflate(this.strm, this.flush);
  6713. }
  6714. break;
  6715. default:
  6716. throw new Error('Unknown mode ' + this.mode);
  6717. }
  6718. };
  6719. Zlib.prototype._checkError = function () {
  6720. // Acceptable error states depend on the type of zlib stream.
  6721. switch (this.err) {
  6722. case exports.Z_OK:
  6723. case exports.Z_BUF_ERROR:
  6724. if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) {
  6725. this._error('unexpected end of file');
  6726. return false;
  6727. }
  6728. break;
  6729. case exports.Z_STREAM_END:
  6730. // normal statuses, not fatal
  6731. break;
  6732. case exports.Z_NEED_DICT:
  6733. if (this.dictionary == null) {
  6734. this._error('Missing dictionary');
  6735. } else {
  6736. this._error('Bad dictionary');
  6737. }
  6738. return false;
  6739. default:
  6740. // something else.
  6741. this._error('Zlib error');
  6742. return false;
  6743. }
  6744. return true;
  6745. };
  6746. Zlib.prototype._after = function () {
  6747. if (!this._checkError()) {
  6748. return;
  6749. }
  6750. var avail_out = this.strm.avail_out;
  6751. var avail_in = this.strm.avail_in;
  6752. this.write_in_progress = false;
  6753. // call the write() cb
  6754. this.callback(avail_in, avail_out);
  6755. if (this.pending_close) {
  6756. this.close();
  6757. }
  6758. };
  6759. Zlib.prototype._error = function (message) {
  6760. if (this.strm.msg) {
  6761. message = this.strm.msg;
  6762. }
  6763. this.onerror(message, this.err
  6764. // no hope of rescue.
  6765. );this.write_in_progress = false;
  6766. if (this.pending_close) {
  6767. this.close();
  6768. }
  6769. };
  6770. Zlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) {
  6771. assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])');
  6772. assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits');
  6773. assert(level >= -1 && level <= 9, 'invalid compression level');
  6774. assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel');
  6775. assert(strategy === exports.Z_FILTERED || strategy === exports.Z_HUFFMAN_ONLY || strategy === exports.Z_RLE || strategy === exports.Z_FIXED || strategy === exports.Z_DEFAULT_STRATEGY, 'invalid strategy');
  6776. this._init(level, windowBits, memLevel, strategy, dictionary);
  6777. this._setDictionary();
  6778. };
  6779. Zlib.prototype.params = function () {
  6780. throw new Error('deflateParams Not supported');
  6781. };
  6782. Zlib.prototype.reset = function () {
  6783. this._reset();
  6784. this._setDictionary();
  6785. };
  6786. Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) {
  6787. this.level = level;
  6788. this.windowBits = windowBits;
  6789. this.memLevel = memLevel;
  6790. this.strategy = strategy;
  6791. this.flush = exports.Z_NO_FLUSH;
  6792. this.err = exports.Z_OK;
  6793. if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) {
  6794. this.windowBits += 16;
  6795. }
  6796. if (this.mode === exports.UNZIP) {
  6797. this.windowBits += 32;
  6798. }
  6799. if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) {
  6800. this.windowBits = -1 * this.windowBits;
  6801. }
  6802. this.strm = new Zstream();
  6803. switch (this.mode) {
  6804. case exports.DEFLATE:
  6805. case exports.GZIP:
  6806. case exports.DEFLATERAW:
  6807. this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy);
  6808. break;
  6809. case exports.INFLATE:
  6810. case exports.GUNZIP:
  6811. case exports.INFLATERAW:
  6812. case exports.UNZIP:
  6813. this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits);
  6814. break;
  6815. default:
  6816. throw new Error('Unknown mode ' + this.mode);
  6817. }
  6818. if (this.err !== exports.Z_OK) {
  6819. this._error('Init error');
  6820. }
  6821. this.dictionary = dictionary;
  6822. this.write_in_progress = false;
  6823. this.init_done = true;
  6824. };
  6825. Zlib.prototype._setDictionary = function () {
  6826. if (this.dictionary == null) {
  6827. return;
  6828. }
  6829. this.err = exports.Z_OK;
  6830. switch (this.mode) {
  6831. case exports.DEFLATE:
  6832. case exports.DEFLATERAW:
  6833. this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary);
  6834. break;
  6835. default:
  6836. break;
  6837. }
  6838. if (this.err !== exports.Z_OK) {
  6839. this._error('Failed to set dictionary');
  6840. }
  6841. };
  6842. Zlib.prototype._reset = function () {
  6843. this.err = exports.Z_OK;
  6844. switch (this.mode) {
  6845. case exports.DEFLATE:
  6846. case exports.DEFLATERAW:
  6847. case exports.GZIP:
  6848. this.err = zlib_deflate.deflateReset(this.strm);
  6849. break;
  6850. case exports.INFLATE:
  6851. case exports.INFLATERAW:
  6852. case exports.GUNZIP:
  6853. this.err = zlib_inflate.inflateReset(this.strm);
  6854. break;
  6855. default:
  6856. break;
  6857. }
  6858. if (this.err !== exports.Z_OK) {
  6859. this._error('Failed to reset stream');
  6860. }
  6861. };
  6862. exports.Zlib = Zlib;
  6863. }).call(this,require('_process'),require("buffer").Buffer)
  6864. },{"_process":134,"assert":15,"buffer":50,"pako/lib/zlib/constants":114,"pako/lib/zlib/deflate.js":116,"pako/lib/zlib/inflate.js":118,"pako/lib/zlib/zstream":122}],48:[function(require,module,exports){
  6865. (function (process){
  6866. 'use strict';
  6867. var Buffer = require('buffer').Buffer;
  6868. var Transform = require('stream').Transform;
  6869. var binding = require('./binding');
  6870. var util = require('util');
  6871. var assert = require('assert').ok;
  6872. var kMaxLength = require('buffer').kMaxLength;
  6873. var kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' + 'than 0x' + kMaxLength.toString(16) + ' bytes';
  6874. // zlib doesn't provide these, so kludge them in following the same
  6875. // const naming scheme zlib uses.
  6876. binding.Z_MIN_WINDOWBITS = 8;
  6877. binding.Z_MAX_WINDOWBITS = 15;
  6878. binding.Z_DEFAULT_WINDOWBITS = 15;
  6879. // fewer than 64 bytes per chunk is stupid.
  6880. // technically it could work with as few as 8, but even 64 bytes
  6881. // is absurdly low. Usually a MB or more is best.
  6882. binding.Z_MIN_CHUNK = 64;
  6883. binding.Z_MAX_CHUNK = Infinity;
  6884. binding.Z_DEFAULT_CHUNK = 16 * 1024;
  6885. binding.Z_MIN_MEMLEVEL = 1;
  6886. binding.Z_MAX_MEMLEVEL = 9;
  6887. binding.Z_DEFAULT_MEMLEVEL = 8;
  6888. binding.Z_MIN_LEVEL = -1;
  6889. binding.Z_MAX_LEVEL = 9;
  6890. binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
  6891. // expose all the zlib constants
  6892. var bkeys = Object.keys(binding);
  6893. for (var bk = 0; bk < bkeys.length; bk++) {
  6894. var bkey = bkeys[bk];
  6895. if (bkey.match(/^Z/)) {
  6896. Object.defineProperty(exports, bkey, {
  6897. enumerable: true, value: binding[bkey], writable: false
  6898. });
  6899. }
  6900. }
  6901. // translation table for return codes.
  6902. var codes = {
  6903. Z_OK: binding.Z_OK,
  6904. Z_STREAM_END: binding.Z_STREAM_END,
  6905. Z_NEED_DICT: binding.Z_NEED_DICT,
  6906. Z_ERRNO: binding.Z_ERRNO,
  6907. Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
  6908. Z_DATA_ERROR: binding.Z_DATA_ERROR,
  6909. Z_MEM_ERROR: binding.Z_MEM_ERROR,
  6910. Z_BUF_ERROR: binding.Z_BUF_ERROR,
  6911. Z_VERSION_ERROR: binding.Z_VERSION_ERROR
  6912. };
  6913. var ckeys = Object.keys(codes);
  6914. for (var ck = 0; ck < ckeys.length; ck++) {
  6915. var ckey = ckeys[ck];
  6916. codes[codes[ckey]] = ckey;
  6917. }
  6918. Object.defineProperty(exports, 'codes', {
  6919. enumerable: true, value: Object.freeze(codes), writable: false
  6920. });
  6921. exports.Deflate = Deflate;
  6922. exports.Inflate = Inflate;
  6923. exports.Gzip = Gzip;
  6924. exports.Gunzip = Gunzip;
  6925. exports.DeflateRaw = DeflateRaw;
  6926. exports.InflateRaw = InflateRaw;
  6927. exports.Unzip = Unzip;
  6928. exports.createDeflate = function (o) {
  6929. return new Deflate(o);
  6930. };
  6931. exports.createInflate = function (o) {
  6932. return new Inflate(o);
  6933. };
  6934. exports.createDeflateRaw = function (o) {
  6935. return new DeflateRaw(o);
  6936. };
  6937. exports.createInflateRaw = function (o) {
  6938. return new InflateRaw(o);
  6939. };
  6940. exports.createGzip = function (o) {
  6941. return new Gzip(o);
  6942. };
  6943. exports.createGunzip = function (o) {
  6944. return new Gunzip(o);
  6945. };
  6946. exports.createUnzip = function (o) {
  6947. return new Unzip(o);
  6948. };
  6949. // Convenience methods.
  6950. // compress/decompress a string or buffer in one step.
  6951. exports.deflate = function (buffer, opts, callback) {
  6952. if (typeof opts === 'function') {
  6953. callback = opts;
  6954. opts = {};
  6955. }
  6956. return zlibBuffer(new Deflate(opts), buffer, callback);
  6957. };
  6958. exports.deflateSync = function (buffer, opts) {
  6959. return zlibBufferSync(new Deflate(opts), buffer);
  6960. };
  6961. exports.gzip = function (buffer, opts, callback) {
  6962. if (typeof opts === 'function') {
  6963. callback = opts;
  6964. opts = {};
  6965. }
  6966. return zlibBuffer(new Gzip(opts), buffer, callback);
  6967. };
  6968. exports.gzipSync = function (buffer, opts) {
  6969. return zlibBufferSync(new Gzip(opts), buffer);
  6970. };
  6971. exports.deflateRaw = function (buffer, opts, callback) {
  6972. if (typeof opts === 'function') {
  6973. callback = opts;
  6974. opts = {};
  6975. }
  6976. return zlibBuffer(new DeflateRaw(opts), buffer, callback);
  6977. };
  6978. exports.deflateRawSync = function (buffer, opts) {
  6979. return zlibBufferSync(new DeflateRaw(opts), buffer);
  6980. };
  6981. exports.unzip = function (buffer, opts, callback) {
  6982. if (typeof opts === 'function') {
  6983. callback = opts;
  6984. opts = {};
  6985. }
  6986. return zlibBuffer(new Unzip(opts), buffer, callback);
  6987. };
  6988. exports.unzipSync = function (buffer, opts) {
  6989. return zlibBufferSync(new Unzip(opts), buffer);
  6990. };
  6991. exports.inflate = function (buffer, opts, callback) {
  6992. if (typeof opts === 'function') {
  6993. callback = opts;
  6994. opts = {};
  6995. }
  6996. return zlibBuffer(new Inflate(opts), buffer, callback);
  6997. };
  6998. exports.inflateSync = function (buffer, opts) {
  6999. return zlibBufferSync(new Inflate(opts), buffer);
  7000. };
  7001. exports.gunzip = function (buffer, opts, callback) {
  7002. if (typeof opts === 'function') {
  7003. callback = opts;
  7004. opts = {};
  7005. }
  7006. return zlibBuffer(new Gunzip(opts), buffer, callback);
  7007. };
  7008. exports.gunzipSync = function (buffer, opts) {
  7009. return zlibBufferSync(new Gunzip(opts), buffer);
  7010. };
  7011. exports.inflateRaw = function (buffer, opts, callback) {
  7012. if (typeof opts === 'function') {
  7013. callback = opts;
  7014. opts = {};
  7015. }
  7016. return zlibBuffer(new InflateRaw(opts), buffer, callback);
  7017. };
  7018. exports.inflateRawSync = function (buffer, opts) {
  7019. return zlibBufferSync(new InflateRaw(opts), buffer);
  7020. };
  7021. function zlibBuffer(engine, buffer, callback) {
  7022. var buffers = [];
  7023. var nread = 0;
  7024. engine.on('error', onError);
  7025. engine.on('end', onEnd);
  7026. engine.end(buffer);
  7027. flow();
  7028. function flow() {
  7029. var chunk;
  7030. while (null !== (chunk = engine.read())) {
  7031. buffers.push(chunk);
  7032. nread += chunk.length;
  7033. }
  7034. engine.once('readable', flow);
  7035. }
  7036. function onError(err) {
  7037. engine.removeListener('end', onEnd);
  7038. engine.removeListener('readable', flow);
  7039. callback(err);
  7040. }
  7041. function onEnd() {
  7042. var buf;
  7043. var err = null;
  7044. if (nread >= kMaxLength) {
  7045. err = new RangeError(kRangeErrorMessage);
  7046. } else {
  7047. buf = Buffer.concat(buffers, nread);
  7048. }
  7049. buffers = [];
  7050. engine.close();
  7051. callback(err, buf);
  7052. }
  7053. }
  7054. function zlibBufferSync(engine, buffer) {
  7055. if (typeof buffer === 'string') buffer = Buffer.from(buffer);
  7056. if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer');
  7057. var flushFlag = engine._finishFlushFlag;
  7058. return engine._processChunk(buffer, flushFlag);
  7059. }
  7060. // generic zlib
  7061. // minimal 2-byte header
  7062. function Deflate(opts) {
  7063. if (!(this instanceof Deflate)) return new Deflate(opts);
  7064. Zlib.call(this, opts, binding.DEFLATE);
  7065. }
  7066. function Inflate(opts) {
  7067. if (!(this instanceof Inflate)) return new Inflate(opts);
  7068. Zlib.call(this, opts, binding.INFLATE);
  7069. }
  7070. // gzip - bigger header, same deflate compression
  7071. function Gzip(opts) {
  7072. if (!(this instanceof Gzip)) return new Gzip(opts);
  7073. Zlib.call(this, opts, binding.GZIP);
  7074. }
  7075. function Gunzip(opts) {
  7076. if (!(this instanceof Gunzip)) return new Gunzip(opts);
  7077. Zlib.call(this, opts, binding.GUNZIP);
  7078. }
  7079. // raw - no header
  7080. function DeflateRaw(opts) {
  7081. if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
  7082. Zlib.call(this, opts, binding.DEFLATERAW);
  7083. }
  7084. function InflateRaw(opts) {
  7085. if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
  7086. Zlib.call(this, opts, binding.INFLATERAW);
  7087. }
  7088. // auto-detect header.
  7089. function Unzip(opts) {
  7090. if (!(this instanceof Unzip)) return new Unzip(opts);
  7091. Zlib.call(this, opts, binding.UNZIP);
  7092. }
  7093. function isValidFlushFlag(flag) {
  7094. return flag === binding.Z_NO_FLUSH || flag === binding.Z_PARTIAL_FLUSH || flag === binding.Z_SYNC_FLUSH || flag === binding.Z_FULL_FLUSH || flag === binding.Z_FINISH || flag === binding.Z_BLOCK;
  7095. }
  7096. // the Zlib class they all inherit from
  7097. // This thing manages the queue of requests, and returns
  7098. // true or false if there is anything in the queue when
  7099. // you call the .write() method.
  7100. function Zlib(opts, mode) {
  7101. var _this = this;
  7102. this._opts = opts = opts || {};
  7103. this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
  7104. Transform.call(this, opts);
  7105. if (opts.flush && !isValidFlushFlag(opts.flush)) {
  7106. throw new Error('Invalid flush flag: ' + opts.flush);
  7107. }
  7108. if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) {
  7109. throw new Error('Invalid flush flag: ' + opts.finishFlush);
  7110. }
  7111. this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
  7112. this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH;
  7113. if (opts.chunkSize) {
  7114. if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) {
  7115. throw new Error('Invalid chunk size: ' + opts.chunkSize);
  7116. }
  7117. }
  7118. if (opts.windowBits) {
  7119. if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) {
  7120. throw new Error('Invalid windowBits: ' + opts.windowBits);
  7121. }
  7122. }
  7123. if (opts.level) {
  7124. if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) {
  7125. throw new Error('Invalid compression level: ' + opts.level);
  7126. }
  7127. }
  7128. if (opts.memLevel) {
  7129. if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) {
  7130. throw new Error('Invalid memLevel: ' + opts.memLevel);
  7131. }
  7132. }
  7133. if (opts.strategy) {
  7134. if (opts.strategy != exports.Z_FILTERED && opts.strategy != exports.Z_HUFFMAN_ONLY && opts.strategy != exports.Z_RLE && opts.strategy != exports.Z_FIXED && opts.strategy != exports.Z_DEFAULT_STRATEGY) {
  7135. throw new Error('Invalid strategy: ' + opts.strategy);
  7136. }
  7137. }
  7138. if (opts.dictionary) {
  7139. if (!Buffer.isBuffer(opts.dictionary)) {
  7140. throw new Error('Invalid dictionary: it should be a Buffer instance');
  7141. }
  7142. }
  7143. this._handle = new binding.Zlib(mode);
  7144. var self = this;
  7145. this._hadError = false;
  7146. this._handle.onerror = function (message, errno) {
  7147. // there is no way to cleanly recover.
  7148. // continuing only obscures problems.
  7149. _close(self);
  7150. self._hadError = true;
  7151. var error = new Error(message);
  7152. error.errno = errno;
  7153. error.code = exports.codes[errno];
  7154. self.emit('error', error);
  7155. };
  7156. var level = exports.Z_DEFAULT_COMPRESSION;
  7157. if (typeof opts.level === 'number') level = opts.level;
  7158. var strategy = exports.Z_DEFAULT_STRATEGY;
  7159. if (typeof opts.strategy === 'number') strategy = opts.strategy;
  7160. this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary);
  7161. this._buffer = Buffer.allocUnsafe(this._chunkSize);
  7162. this._offset = 0;
  7163. this._level = level;
  7164. this._strategy = strategy;
  7165. this.once('end', this.close);
  7166. Object.defineProperty(this, '_closed', {
  7167. get: function () {
  7168. return !_this._handle;
  7169. },
  7170. configurable: true,
  7171. enumerable: true
  7172. });
  7173. }
  7174. util.inherits(Zlib, Transform);
  7175. Zlib.prototype.params = function (level, strategy, callback) {
  7176. if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) {
  7177. throw new RangeError('Invalid compression level: ' + level);
  7178. }
  7179. if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) {
  7180. throw new TypeError('Invalid strategy: ' + strategy);
  7181. }
  7182. if (this._level !== level || this._strategy !== strategy) {
  7183. var self = this;
  7184. this.flush(binding.Z_SYNC_FLUSH, function () {
  7185. assert(self._handle, 'zlib binding closed');
  7186. self._handle.params(level, strategy);
  7187. if (!self._hadError) {
  7188. self._level = level;
  7189. self._strategy = strategy;
  7190. if (callback) callback();
  7191. }
  7192. });
  7193. } else {
  7194. process.nextTick(callback);
  7195. }
  7196. };
  7197. Zlib.prototype.reset = function () {
  7198. assert(this._handle, 'zlib binding closed');
  7199. return this._handle.reset();
  7200. };
  7201. // This is the _flush function called by the transform class,
  7202. // internally, when the last chunk has been written.
  7203. Zlib.prototype._flush = function (callback) {
  7204. this._transform(Buffer.alloc(0), '', callback);
  7205. };
  7206. Zlib.prototype.flush = function (kind, callback) {
  7207. var _this2 = this;
  7208. var ws = this._writableState;
  7209. if (typeof kind === 'function' || kind === undefined && !callback) {
  7210. callback = kind;
  7211. kind = binding.Z_FULL_FLUSH;
  7212. }
  7213. if (ws.ended) {
  7214. if (callback) process.nextTick(callback);
  7215. } else if (ws.ending) {
  7216. if (callback) this.once('end', callback);
  7217. } else if (ws.needDrain) {
  7218. if (callback) {
  7219. this.once('drain', function () {
  7220. return _this2.flush(kind, callback);
  7221. });
  7222. }
  7223. } else {
  7224. this._flushFlag = kind;
  7225. this.write(Buffer.alloc(0), '', callback);
  7226. }
  7227. };
  7228. Zlib.prototype.close = function (callback) {
  7229. _close(this, callback);
  7230. process.nextTick(emitCloseNT, this);
  7231. };
  7232. function _close(engine, callback) {
  7233. if (callback) process.nextTick(callback);
  7234. // Caller may invoke .close after a zlib error (which will null _handle).
  7235. if (!engine._handle) return;
  7236. engine._handle.close();
  7237. engine._handle = null;
  7238. }
  7239. function emitCloseNT(self) {
  7240. self.emit('close');
  7241. }
  7242. Zlib.prototype._transform = function (chunk, encoding, cb) {
  7243. var flushFlag;
  7244. var ws = this._writableState;
  7245. var ending = ws.ending || ws.ended;
  7246. var last = ending && (!chunk || ws.length === chunk.length);
  7247. if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input'));
  7248. if (!this._handle) return cb(new Error('zlib binding closed'));
  7249. // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag
  7250. // (or whatever flag was provided using opts.finishFlush).
  7251. // If it's explicitly flushing at some other time, then we use
  7252. // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
  7253. // goodness.
  7254. if (last) flushFlag = this._finishFlushFlag;else {
  7255. flushFlag = this._flushFlag;
  7256. // once we've flushed the last of the queue, stop flushing and
  7257. // go back to the normal behavior.
  7258. if (chunk.length >= ws.length) {
  7259. this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
  7260. }
  7261. }
  7262. this._processChunk(chunk, flushFlag, cb);
  7263. };
  7264. Zlib.prototype._processChunk = function (chunk, flushFlag, cb) {
  7265. var availInBefore = chunk && chunk.length;
  7266. var availOutBefore = this._chunkSize - this._offset;
  7267. var inOff = 0;
  7268. var self = this;
  7269. var async = typeof cb === 'function';
  7270. if (!async) {
  7271. var buffers = [];
  7272. var nread = 0;
  7273. var error;
  7274. this.on('error', function (er) {
  7275. error = er;
  7276. });
  7277. assert(this._handle, 'zlib binding closed');
  7278. do {
  7279. var res = this._handle.writeSync(flushFlag, chunk, // in
  7280. inOff, // in_off
  7281. availInBefore, // in_len
  7282. this._buffer, // out
  7283. this._offset, //out_off
  7284. availOutBefore); // out_len
  7285. } while (!this._hadError && callback(res[0], res[1]));
  7286. if (this._hadError) {
  7287. throw error;
  7288. }
  7289. if (nread >= kMaxLength) {
  7290. _close(this);
  7291. throw new RangeError(kRangeErrorMessage);
  7292. }
  7293. var buf = Buffer.concat(buffers, nread);
  7294. _close(this);
  7295. return buf;
  7296. }
  7297. assert(this._handle, 'zlib binding closed');
  7298. var req = this._handle.write(flushFlag, chunk, // in
  7299. inOff, // in_off
  7300. availInBefore, // in_len
  7301. this._buffer, // out
  7302. this._offset, //out_off
  7303. availOutBefore); // out_len
  7304. req.buffer = chunk;
  7305. req.callback = callback;
  7306. function callback(availInAfter, availOutAfter) {
  7307. // When the callback is used in an async write, the callback's
  7308. // context is the `req` object that was created. The req object
  7309. // is === this._handle, and that's why it's important to null
  7310. // out the values after they are done being used. `this._handle`
  7311. // can stay in memory longer than the callback and buffer are needed.
  7312. if (this) {
  7313. this.buffer = null;
  7314. this.callback = null;
  7315. }
  7316. if (self._hadError) return;
  7317. var have = availOutBefore - availOutAfter;
  7318. assert(have >= 0, 'have should not go down');
  7319. if (have > 0) {
  7320. var out = self._buffer.slice(self._offset, self._offset + have);
  7321. self._offset += have;
  7322. // serve some output to the consumer.
  7323. if (async) {
  7324. self.push(out);
  7325. } else {
  7326. buffers.push(out);
  7327. nread += out.length;
  7328. }
  7329. }
  7330. // exhausted the output buffer, or used all the input create a new one.
  7331. if (availOutAfter === 0 || self._offset >= self._chunkSize) {
  7332. availOutBefore = self._chunkSize;
  7333. self._offset = 0;
  7334. self._buffer = Buffer.allocUnsafe(self._chunkSize);
  7335. }
  7336. if (availOutAfter === 0) {
  7337. // Not actually done. Need to reprocess.
  7338. // Also, update the availInBefore to the availInAfter value,
  7339. // so that if we have to hit it a third (fourth, etc.) time,
  7340. // it'll have the correct byte counts.
  7341. inOff += availInBefore - availInAfter;
  7342. availInBefore = availInAfter;
  7343. if (!async) return true;
  7344. var newReq = self._handle.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize);
  7345. newReq.callback = callback; // this same function
  7346. newReq.buffer = chunk;
  7347. return;
  7348. }
  7349. if (!async) return false;
  7350. // finished with the chunk.
  7351. cb();
  7352. }
  7353. };
  7354. util.inherits(Deflate, Zlib);
  7355. util.inherits(Inflate, Zlib);
  7356. util.inherits(Gzip, Zlib);
  7357. util.inherits(Gunzip, Zlib);
  7358. util.inherits(DeflateRaw, Zlib);
  7359. util.inherits(InflateRaw, Zlib);
  7360. util.inherits(Unzip, Zlib);
  7361. }).call(this,require('_process'))
  7362. },{"./binding":47,"_process":134,"assert":15,"buffer":50,"stream":166,"util":171}],49:[function(require,module,exports){
  7363. (function (Buffer){
  7364. module.exports = function xor (a, b) {
  7365. var length = Math.min(a.length, b.length)
  7366. var buffer = new Buffer(length)
  7367. for (var i = 0; i < length; ++i) {
  7368. buffer[i] = a[i] ^ b[i]
  7369. }
  7370. return buffer
  7371. }
  7372. }).call(this,require("buffer").Buffer)
  7373. },{"buffer":50}],50:[function(require,module,exports){
  7374. /*!
  7375. * The buffer module from node.js, for the browser.
  7376. *
  7377. * @author Feross Aboukhadijeh <https://feross.org>
  7378. * @license MIT
  7379. */
  7380. /* eslint-disable no-proto */
  7381. 'use strict'
  7382. var base64 = require('base64-js')
  7383. var ieee754 = require('ieee754')
  7384. exports.Buffer = Buffer
  7385. exports.SlowBuffer = SlowBuffer
  7386. exports.INSPECT_MAX_BYTES = 50
  7387. var K_MAX_LENGTH = 0x7fffffff
  7388. exports.kMaxLength = K_MAX_LENGTH
  7389. /**
  7390. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  7391. * === true Use Uint8Array implementation (fastest)
  7392. * === false Print warning and recommend using `buffer` v4.x which has an Object
  7393. * implementation (most compatible, even IE6)
  7394. *
  7395. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  7396. * Opera 11.6+, iOS 4.2+.
  7397. *
  7398. * We report that the browser does not support typed arrays if the are not subclassable
  7399. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  7400. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  7401. * for __proto__ and has a buggy typed array implementation.
  7402. */
  7403. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  7404. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  7405. typeof console.error === 'function') {
  7406. console.error(
  7407. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  7408. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  7409. )
  7410. }
  7411. function typedArraySupport () {
  7412. // Can typed array instances can be augmented?
  7413. try {
  7414. var arr = new Uint8Array(1)
  7415. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  7416. return arr.foo() === 42
  7417. } catch (e) {
  7418. return false
  7419. }
  7420. }
  7421. function createBuffer (length) {
  7422. if (length > K_MAX_LENGTH) {
  7423. throw new RangeError('Invalid typed array length')
  7424. }
  7425. // Return an augmented `Uint8Array` instance
  7426. var buf = new Uint8Array(length)
  7427. buf.__proto__ = Buffer.prototype
  7428. return buf
  7429. }
  7430. /**
  7431. * The Buffer constructor returns instances of `Uint8Array` that have their
  7432. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  7433. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  7434. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  7435. * returns a single octet.
  7436. *
  7437. * The `Uint8Array` prototype remains unmodified.
  7438. */
  7439. function Buffer (arg, encodingOrOffset, length) {
  7440. // Common case.
  7441. if (typeof arg === 'number') {
  7442. if (typeof encodingOrOffset === 'string') {
  7443. throw new Error(
  7444. 'If encoding is specified then the first argument must be a string'
  7445. )
  7446. }
  7447. return allocUnsafe(arg)
  7448. }
  7449. return from(arg, encodingOrOffset, length)
  7450. }
  7451. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  7452. if (typeof Symbol !== 'undefined' && Symbol.species &&
  7453. Buffer[Symbol.species] === Buffer) {
  7454. Object.defineProperty(Buffer, Symbol.species, {
  7455. value: null,
  7456. configurable: true,
  7457. enumerable: false,
  7458. writable: false
  7459. })
  7460. }
  7461. Buffer.poolSize = 8192 // not used by this implementation
  7462. function from (value, encodingOrOffset, length) {
  7463. if (typeof value === 'number') {
  7464. throw new TypeError('"value" argument must not be a number')
  7465. }
  7466. if (isArrayBuffer(value)) {
  7467. return fromArrayBuffer(value, encodingOrOffset, length)
  7468. }
  7469. if (typeof value === 'string') {
  7470. return fromString(value, encodingOrOffset)
  7471. }
  7472. return fromObject(value)
  7473. }
  7474. /**
  7475. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  7476. * if value is a number.
  7477. * Buffer.from(str[, encoding])
  7478. * Buffer.from(array)
  7479. * Buffer.from(buffer)
  7480. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  7481. **/
  7482. Buffer.from = function (value, encodingOrOffset, length) {
  7483. return from(value, encodingOrOffset, length)
  7484. }
  7485. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  7486. // https://github.com/feross/buffer/pull/148
  7487. Buffer.prototype.__proto__ = Uint8Array.prototype
  7488. Buffer.__proto__ = Uint8Array
  7489. function assertSize (size) {
  7490. if (typeof size !== 'number') {
  7491. throw new TypeError('"size" argument must be a number')
  7492. } else if (size < 0) {
  7493. throw new RangeError('"size" argument must not be negative')
  7494. }
  7495. }
  7496. function alloc (size, fill, encoding) {
  7497. assertSize(size)
  7498. if (size <= 0) {
  7499. return createBuffer(size)
  7500. }
  7501. if (fill !== undefined) {
  7502. // Only pay attention to encoding if it's a string. This
  7503. // prevents accidentally sending in a number that would
  7504. // be interpretted as a start offset.
  7505. return typeof encoding === 'string'
  7506. ? createBuffer(size).fill(fill, encoding)
  7507. : createBuffer(size).fill(fill)
  7508. }
  7509. return createBuffer(size)
  7510. }
  7511. /**
  7512. * Creates a new filled Buffer instance.
  7513. * alloc(size[, fill[, encoding]])
  7514. **/
  7515. Buffer.alloc = function (size, fill, encoding) {
  7516. return alloc(size, fill, encoding)
  7517. }
  7518. function allocUnsafe (size) {
  7519. assertSize(size)
  7520. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  7521. }
  7522. /**
  7523. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  7524. * */
  7525. Buffer.allocUnsafe = function (size) {
  7526. return allocUnsafe(size)
  7527. }
  7528. /**
  7529. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  7530. */
  7531. Buffer.allocUnsafeSlow = function (size) {
  7532. return allocUnsafe(size)
  7533. }
  7534. function fromString (string, encoding) {
  7535. if (typeof encoding !== 'string' || encoding === '') {
  7536. encoding = 'utf8'
  7537. }
  7538. if (!Buffer.isEncoding(encoding)) {
  7539. throw new TypeError('"encoding" must be a valid string encoding')
  7540. }
  7541. var length = byteLength(string, encoding) | 0
  7542. var buf = createBuffer(length)
  7543. var actual = buf.write(string, encoding)
  7544. if (actual !== length) {
  7545. // Writing a hex string, for example, that contains invalid characters will
  7546. // cause everything after the first invalid character to be ignored. (e.g.
  7547. // 'abxxcd' will be treated as 'ab')
  7548. buf = buf.slice(0, actual)
  7549. }
  7550. return buf
  7551. }
  7552. function fromArrayLike (array) {
  7553. var length = array.length < 0 ? 0 : checked(array.length) | 0
  7554. var buf = createBuffer(length)
  7555. for (var i = 0; i < length; i += 1) {
  7556. buf[i] = array[i] & 255
  7557. }
  7558. return buf
  7559. }
  7560. function fromArrayBuffer (array, byteOffset, length) {
  7561. if (byteOffset < 0 || array.byteLength < byteOffset) {
  7562. throw new RangeError('\'offset\' is out of bounds')
  7563. }
  7564. if (array.byteLength < byteOffset + (length || 0)) {
  7565. throw new RangeError('\'length\' is out of bounds')
  7566. }
  7567. var buf
  7568. if (byteOffset === undefined && length === undefined) {
  7569. buf = new Uint8Array(array)
  7570. } else if (length === undefined) {
  7571. buf = new Uint8Array(array, byteOffset)
  7572. } else {
  7573. buf = new Uint8Array(array, byteOffset, length)
  7574. }
  7575. // Return an augmented `Uint8Array` instance
  7576. buf.__proto__ = Buffer.prototype
  7577. return buf
  7578. }
  7579. function fromObject (obj) {
  7580. if (Buffer.isBuffer(obj)) {
  7581. var len = checked(obj.length) | 0
  7582. var buf = createBuffer(len)
  7583. if (buf.length === 0) {
  7584. return buf
  7585. }
  7586. obj.copy(buf, 0, 0, len)
  7587. return buf
  7588. }
  7589. if (obj) {
  7590. if (isArrayBufferView(obj) || 'length' in obj) {
  7591. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  7592. return createBuffer(0)
  7593. }
  7594. return fromArrayLike(obj)
  7595. }
  7596. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  7597. return fromArrayLike(obj.data)
  7598. }
  7599. }
  7600. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  7601. }
  7602. function checked (length) {
  7603. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  7604. // length is NaN (which is otherwise coerced to zero.)
  7605. if (length >= K_MAX_LENGTH) {
  7606. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  7607. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  7608. }
  7609. return length | 0
  7610. }
  7611. function SlowBuffer (length) {
  7612. if (+length != length) { // eslint-disable-line eqeqeq
  7613. length = 0
  7614. }
  7615. return Buffer.alloc(+length)
  7616. }
  7617. Buffer.isBuffer = function isBuffer (b) {
  7618. return b != null && b._isBuffer === true
  7619. }
  7620. Buffer.compare = function compare (a, b) {
  7621. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  7622. throw new TypeError('Arguments must be Buffers')
  7623. }
  7624. if (a === b) return 0
  7625. var x = a.length
  7626. var y = b.length
  7627. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  7628. if (a[i] !== b[i]) {
  7629. x = a[i]
  7630. y = b[i]
  7631. break
  7632. }
  7633. }
  7634. if (x < y) return -1
  7635. if (y < x) return 1
  7636. return 0
  7637. }
  7638. Buffer.isEncoding = function isEncoding (encoding) {
  7639. switch (String(encoding).toLowerCase()) {
  7640. case 'hex':
  7641. case 'utf8':
  7642. case 'utf-8':
  7643. case 'ascii':
  7644. case 'latin1':
  7645. case 'binary':
  7646. case 'base64':
  7647. case 'ucs2':
  7648. case 'ucs-2':
  7649. case 'utf16le':
  7650. case 'utf-16le':
  7651. return true
  7652. default:
  7653. return false
  7654. }
  7655. }
  7656. Buffer.concat = function concat (list, length) {
  7657. if (!Array.isArray(list)) {
  7658. throw new TypeError('"list" argument must be an Array of Buffers')
  7659. }
  7660. if (list.length === 0) {
  7661. return Buffer.alloc(0)
  7662. }
  7663. var i
  7664. if (length === undefined) {
  7665. length = 0
  7666. for (i = 0; i < list.length; ++i) {
  7667. length += list[i].length
  7668. }
  7669. }
  7670. var buffer = Buffer.allocUnsafe(length)
  7671. var pos = 0
  7672. for (i = 0; i < list.length; ++i) {
  7673. var buf = list[i]
  7674. if (!Buffer.isBuffer(buf)) {
  7675. throw new TypeError('"list" argument must be an Array of Buffers')
  7676. }
  7677. buf.copy(buffer, pos)
  7678. pos += buf.length
  7679. }
  7680. return buffer
  7681. }
  7682. function byteLength (string, encoding) {
  7683. if (Buffer.isBuffer(string)) {
  7684. return string.length
  7685. }
  7686. if (isArrayBufferView(string) || isArrayBuffer(string)) {
  7687. return string.byteLength
  7688. }
  7689. if (typeof string !== 'string') {
  7690. string = '' + string
  7691. }
  7692. var len = string.length
  7693. if (len === 0) return 0
  7694. // Use a for loop to avoid recursion
  7695. var loweredCase = false
  7696. for (;;) {
  7697. switch (encoding) {
  7698. case 'ascii':
  7699. case 'latin1':
  7700. case 'binary':
  7701. return len
  7702. case 'utf8':
  7703. case 'utf-8':
  7704. case undefined:
  7705. return utf8ToBytes(string).length
  7706. case 'ucs2':
  7707. case 'ucs-2':
  7708. case 'utf16le':
  7709. case 'utf-16le':
  7710. return len * 2
  7711. case 'hex':
  7712. return len >>> 1
  7713. case 'base64':
  7714. return base64ToBytes(string).length
  7715. default:
  7716. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  7717. encoding = ('' + encoding).toLowerCase()
  7718. loweredCase = true
  7719. }
  7720. }
  7721. }
  7722. Buffer.byteLength = byteLength
  7723. function slowToString (encoding, start, end) {
  7724. var loweredCase = false
  7725. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  7726. // property of a typed array.
  7727. // This behaves neither like String nor Uint8Array in that we set start/end
  7728. // to their upper/lower bounds if the value passed is out of range.
  7729. // undefined is handled specially as per ECMA-262 6th Edition,
  7730. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  7731. if (start === undefined || start < 0) {
  7732. start = 0
  7733. }
  7734. // Return early if start > this.length. Done here to prevent potential uint32
  7735. // coercion fail below.
  7736. if (start > this.length) {
  7737. return ''
  7738. }
  7739. if (end === undefined || end > this.length) {
  7740. end = this.length
  7741. }
  7742. if (end <= 0) {
  7743. return ''
  7744. }
  7745. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  7746. end >>>= 0
  7747. start >>>= 0
  7748. if (end <= start) {
  7749. return ''
  7750. }
  7751. if (!encoding) encoding = 'utf8'
  7752. while (true) {
  7753. switch (encoding) {
  7754. case 'hex':
  7755. return hexSlice(this, start, end)
  7756. case 'utf8':
  7757. case 'utf-8':
  7758. return utf8Slice(this, start, end)
  7759. case 'ascii':
  7760. return asciiSlice(this, start, end)
  7761. case 'latin1':
  7762. case 'binary':
  7763. return latin1Slice(this, start, end)
  7764. case 'base64':
  7765. return base64Slice(this, start, end)
  7766. case 'ucs2':
  7767. case 'ucs-2':
  7768. case 'utf16le':
  7769. case 'utf-16le':
  7770. return utf16leSlice(this, start, end)
  7771. default:
  7772. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  7773. encoding = (encoding + '').toLowerCase()
  7774. loweredCase = true
  7775. }
  7776. }
  7777. }
  7778. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  7779. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  7780. // reliably in a browserify context because there could be multiple different
  7781. // copies of the 'buffer' package in use. This method works even for Buffer
  7782. // instances that were created from another copy of the `buffer` package.
  7783. // See: https://github.com/feross/buffer/issues/154
  7784. Buffer.prototype._isBuffer = true
  7785. function swap (b, n, m) {
  7786. var i = b[n]
  7787. b[n] = b[m]
  7788. b[m] = i
  7789. }
  7790. Buffer.prototype.swap16 = function swap16 () {
  7791. var len = this.length
  7792. if (len % 2 !== 0) {
  7793. throw new RangeError('Buffer size must be a multiple of 16-bits')
  7794. }
  7795. for (var i = 0; i < len; i += 2) {
  7796. swap(this, i, i + 1)
  7797. }
  7798. return this
  7799. }
  7800. Buffer.prototype.swap32 = function swap32 () {
  7801. var len = this.length
  7802. if (len % 4 !== 0) {
  7803. throw new RangeError('Buffer size must be a multiple of 32-bits')
  7804. }
  7805. for (var i = 0; i < len; i += 4) {
  7806. swap(this, i, i + 3)
  7807. swap(this, i + 1, i + 2)
  7808. }
  7809. return this
  7810. }
  7811. Buffer.prototype.swap64 = function swap64 () {
  7812. var len = this.length
  7813. if (len % 8 !== 0) {
  7814. throw new RangeError('Buffer size must be a multiple of 64-bits')
  7815. }
  7816. for (var i = 0; i < len; i += 8) {
  7817. swap(this, i, i + 7)
  7818. swap(this, i + 1, i + 6)
  7819. swap(this, i + 2, i + 5)
  7820. swap(this, i + 3, i + 4)
  7821. }
  7822. return this
  7823. }
  7824. Buffer.prototype.toString = function toString () {
  7825. var length = this.length
  7826. if (length === 0) return ''
  7827. if (arguments.length === 0) return utf8Slice(this, 0, length)
  7828. return slowToString.apply(this, arguments)
  7829. }
  7830. Buffer.prototype.equals = function equals (b) {
  7831. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  7832. if (this === b) return true
  7833. return Buffer.compare(this, b) === 0
  7834. }
  7835. Buffer.prototype.inspect = function inspect () {
  7836. var str = ''
  7837. var max = exports.INSPECT_MAX_BYTES
  7838. if (this.length > 0) {
  7839. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  7840. if (this.length > max) str += ' ... '
  7841. }
  7842. return '<Buffer ' + str + '>'
  7843. }
  7844. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  7845. if (!Buffer.isBuffer(target)) {
  7846. throw new TypeError('Argument must be a Buffer')
  7847. }
  7848. if (start === undefined) {
  7849. start = 0
  7850. }
  7851. if (end === undefined) {
  7852. end = target ? target.length : 0
  7853. }
  7854. if (thisStart === undefined) {
  7855. thisStart = 0
  7856. }
  7857. if (thisEnd === undefined) {
  7858. thisEnd = this.length
  7859. }
  7860. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  7861. throw new RangeError('out of range index')
  7862. }
  7863. if (thisStart >= thisEnd && start >= end) {
  7864. return 0
  7865. }
  7866. if (thisStart >= thisEnd) {
  7867. return -1
  7868. }
  7869. if (start >= end) {
  7870. return 1
  7871. }
  7872. start >>>= 0
  7873. end >>>= 0
  7874. thisStart >>>= 0
  7875. thisEnd >>>= 0
  7876. if (this === target) return 0
  7877. var x = thisEnd - thisStart
  7878. var y = end - start
  7879. var len = Math.min(x, y)
  7880. var thisCopy = this.slice(thisStart, thisEnd)
  7881. var targetCopy = target.slice(start, end)
  7882. for (var i = 0; i < len; ++i) {
  7883. if (thisCopy[i] !== targetCopy[i]) {
  7884. x = thisCopy[i]
  7885. y = targetCopy[i]
  7886. break
  7887. }
  7888. }
  7889. if (x < y) return -1
  7890. if (y < x) return 1
  7891. return 0
  7892. }
  7893. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  7894. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  7895. //
  7896. // Arguments:
  7897. // - buffer - a Buffer to search
  7898. // - val - a string, Buffer, or number
  7899. // - byteOffset - an index into `buffer`; will be clamped to an int32
  7900. // - encoding - an optional encoding, relevant is val is a string
  7901. // - dir - true for indexOf, false for lastIndexOf
  7902. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  7903. // Empty buffer means no match
  7904. if (buffer.length === 0) return -1
  7905. // Normalize byteOffset
  7906. if (typeof byteOffset === 'string') {
  7907. encoding = byteOffset
  7908. byteOffset = 0
  7909. } else if (byteOffset > 0x7fffffff) {
  7910. byteOffset = 0x7fffffff
  7911. } else if (byteOffset < -0x80000000) {
  7912. byteOffset = -0x80000000
  7913. }
  7914. byteOffset = +byteOffset // Coerce to Number.
  7915. if (numberIsNaN(byteOffset)) {
  7916. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  7917. byteOffset = dir ? 0 : (buffer.length - 1)
  7918. }
  7919. // Normalize byteOffset: negative offsets start from the end of the buffer
  7920. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  7921. if (byteOffset >= buffer.length) {
  7922. if (dir) return -1
  7923. else byteOffset = buffer.length - 1
  7924. } else if (byteOffset < 0) {
  7925. if (dir) byteOffset = 0
  7926. else return -1
  7927. }
  7928. // Normalize val
  7929. if (typeof val === 'string') {
  7930. val = Buffer.from(val, encoding)
  7931. }
  7932. // Finally, search either indexOf (if dir is true) or lastIndexOf
  7933. if (Buffer.isBuffer(val)) {
  7934. // Special case: looking for empty string/buffer always fails
  7935. if (val.length === 0) {
  7936. return -1
  7937. }
  7938. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  7939. } else if (typeof val === 'number') {
  7940. val = val & 0xFF // Search for a byte value [0-255]
  7941. if (typeof Uint8Array.prototype.indexOf === 'function') {
  7942. if (dir) {
  7943. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  7944. } else {
  7945. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  7946. }
  7947. }
  7948. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  7949. }
  7950. throw new TypeError('val must be string, number or Buffer')
  7951. }
  7952. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  7953. var indexSize = 1
  7954. var arrLength = arr.length
  7955. var valLength = val.length
  7956. if (encoding !== undefined) {
  7957. encoding = String(encoding).toLowerCase()
  7958. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  7959. encoding === 'utf16le' || encoding === 'utf-16le') {
  7960. if (arr.length < 2 || val.length < 2) {
  7961. return -1
  7962. }
  7963. indexSize = 2
  7964. arrLength /= 2
  7965. valLength /= 2
  7966. byteOffset /= 2
  7967. }
  7968. }
  7969. function read (buf, i) {
  7970. if (indexSize === 1) {
  7971. return buf[i]
  7972. } else {
  7973. return buf.readUInt16BE(i * indexSize)
  7974. }
  7975. }
  7976. var i
  7977. if (dir) {
  7978. var foundIndex = -1
  7979. for (i = byteOffset; i < arrLength; i++) {
  7980. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  7981. if (foundIndex === -1) foundIndex = i
  7982. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  7983. } else {
  7984. if (foundIndex !== -1) i -= i - foundIndex
  7985. foundIndex = -1
  7986. }
  7987. }
  7988. } else {
  7989. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  7990. for (i = byteOffset; i >= 0; i--) {
  7991. var found = true
  7992. for (var j = 0; j < valLength; j++) {
  7993. if (read(arr, i + j) !== read(val, j)) {
  7994. found = false
  7995. break
  7996. }
  7997. }
  7998. if (found) return i
  7999. }
  8000. }
  8001. return -1
  8002. }
  8003. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  8004. return this.indexOf(val, byteOffset, encoding) !== -1
  8005. }
  8006. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  8007. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  8008. }
  8009. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  8010. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  8011. }
  8012. function hexWrite (buf, string, offset, length) {
  8013. offset = Number(offset) || 0
  8014. var remaining = buf.length - offset
  8015. if (!length) {
  8016. length = remaining
  8017. } else {
  8018. length = Number(length)
  8019. if (length > remaining) {
  8020. length = remaining
  8021. }
  8022. }
  8023. // must be an even number of digits
  8024. var strLen = string.length
  8025. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  8026. if (length > strLen / 2) {
  8027. length = strLen / 2
  8028. }
  8029. for (var i = 0; i < length; ++i) {
  8030. var parsed = parseInt(string.substr(i * 2, 2), 16)
  8031. if (numberIsNaN(parsed)) return i
  8032. buf[offset + i] = parsed
  8033. }
  8034. return i
  8035. }
  8036. function utf8Write (buf, string, offset, length) {
  8037. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  8038. }
  8039. function asciiWrite (buf, string, offset, length) {
  8040. return blitBuffer(asciiToBytes(string), buf, offset, length)
  8041. }
  8042. function latin1Write (buf, string, offset, length) {
  8043. return asciiWrite(buf, string, offset, length)
  8044. }
  8045. function base64Write (buf, string, offset, length) {
  8046. return blitBuffer(base64ToBytes(string), buf, offset, length)
  8047. }
  8048. function ucs2Write (buf, string, offset, length) {
  8049. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  8050. }
  8051. Buffer.prototype.write = function write (string, offset, length, encoding) {
  8052. // Buffer#write(string)
  8053. if (offset === undefined) {
  8054. encoding = 'utf8'
  8055. length = this.length
  8056. offset = 0
  8057. // Buffer#write(string, encoding)
  8058. } else if (length === undefined && typeof offset === 'string') {
  8059. encoding = offset
  8060. length = this.length
  8061. offset = 0
  8062. // Buffer#write(string, offset[, length][, encoding])
  8063. } else if (isFinite(offset)) {
  8064. offset = offset >>> 0
  8065. if (isFinite(length)) {
  8066. length = length >>> 0
  8067. if (encoding === undefined) encoding = 'utf8'
  8068. } else {
  8069. encoding = length
  8070. length = undefined
  8071. }
  8072. } else {
  8073. throw new Error(
  8074. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  8075. )
  8076. }
  8077. var remaining = this.length - offset
  8078. if (length === undefined || length > remaining) length = remaining
  8079. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  8080. throw new RangeError('Attempt to write outside buffer bounds')
  8081. }
  8082. if (!encoding) encoding = 'utf8'
  8083. var loweredCase = false
  8084. for (;;) {
  8085. switch (encoding) {
  8086. case 'hex':
  8087. return hexWrite(this, string, offset, length)
  8088. case 'utf8':
  8089. case 'utf-8':
  8090. return utf8Write(this, string, offset, length)
  8091. case 'ascii':
  8092. return asciiWrite(this, string, offset, length)
  8093. case 'latin1':
  8094. case 'binary':
  8095. return latin1Write(this, string, offset, length)
  8096. case 'base64':
  8097. // Warning: maxLength not taken into account in base64Write
  8098. return base64Write(this, string, offset, length)
  8099. case 'ucs2':
  8100. case 'ucs-2':
  8101. case 'utf16le':
  8102. case 'utf-16le':
  8103. return ucs2Write(this, string, offset, length)
  8104. default:
  8105. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  8106. encoding = ('' + encoding).toLowerCase()
  8107. loweredCase = true
  8108. }
  8109. }
  8110. }
  8111. Buffer.prototype.toJSON = function toJSON () {
  8112. return {
  8113. type: 'Buffer',
  8114. data: Array.prototype.slice.call(this._arr || this, 0)
  8115. }
  8116. }
  8117. function base64Slice (buf, start, end) {
  8118. if (start === 0 && end === buf.length) {
  8119. return base64.fromByteArray(buf)
  8120. } else {
  8121. return base64.fromByteArray(buf.slice(start, end))
  8122. }
  8123. }
  8124. function utf8Slice (buf, start, end) {
  8125. end = Math.min(buf.length, end)
  8126. var res = []
  8127. var i = start
  8128. while (i < end) {
  8129. var firstByte = buf[i]
  8130. var codePoint = null
  8131. var bytesPerSequence = (firstByte > 0xEF) ? 4
  8132. : (firstByte > 0xDF) ? 3
  8133. : (firstByte > 0xBF) ? 2
  8134. : 1
  8135. if (i + bytesPerSequence <= end) {
  8136. var secondByte, thirdByte, fourthByte, tempCodePoint
  8137. switch (bytesPerSequence) {
  8138. case 1:
  8139. if (firstByte < 0x80) {
  8140. codePoint = firstByte
  8141. }
  8142. break
  8143. case 2:
  8144. secondByte = buf[i + 1]
  8145. if ((secondByte & 0xC0) === 0x80) {
  8146. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  8147. if (tempCodePoint > 0x7F) {
  8148. codePoint = tempCodePoint
  8149. }
  8150. }
  8151. break
  8152. case 3:
  8153. secondByte = buf[i + 1]
  8154. thirdByte = buf[i + 2]
  8155. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  8156. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  8157. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  8158. codePoint = tempCodePoint
  8159. }
  8160. }
  8161. break
  8162. case 4:
  8163. secondByte = buf[i + 1]
  8164. thirdByte = buf[i + 2]
  8165. fourthByte = buf[i + 3]
  8166. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  8167. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  8168. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  8169. codePoint = tempCodePoint
  8170. }
  8171. }
  8172. }
  8173. }
  8174. if (codePoint === null) {
  8175. // we did not generate a valid codePoint so insert a
  8176. // replacement char (U+FFFD) and advance only 1 byte
  8177. codePoint = 0xFFFD
  8178. bytesPerSequence = 1
  8179. } else if (codePoint > 0xFFFF) {
  8180. // encode to utf16 (surrogate pair dance)
  8181. codePoint -= 0x10000
  8182. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  8183. codePoint = 0xDC00 | codePoint & 0x3FF
  8184. }
  8185. res.push(codePoint)
  8186. i += bytesPerSequence
  8187. }
  8188. return decodeCodePointsArray(res)
  8189. }
  8190. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  8191. // the lowest limit is Chrome, with 0x10000 args.
  8192. // We go 1 magnitude less, for safety
  8193. var MAX_ARGUMENTS_LENGTH = 0x1000
  8194. function decodeCodePointsArray (codePoints) {
  8195. var len = codePoints.length
  8196. if (len <= MAX_ARGUMENTS_LENGTH) {
  8197. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  8198. }
  8199. // Decode in chunks to avoid "call stack size exceeded".
  8200. var res = ''
  8201. var i = 0
  8202. while (i < len) {
  8203. res += String.fromCharCode.apply(
  8204. String,
  8205. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  8206. )
  8207. }
  8208. return res
  8209. }
  8210. function asciiSlice (buf, start, end) {
  8211. var ret = ''
  8212. end = Math.min(buf.length, end)
  8213. for (var i = start; i < end; ++i) {
  8214. ret += String.fromCharCode(buf[i] & 0x7F)
  8215. }
  8216. return ret
  8217. }
  8218. function latin1Slice (buf, start, end) {
  8219. var ret = ''
  8220. end = Math.min(buf.length, end)
  8221. for (var i = start; i < end; ++i) {
  8222. ret += String.fromCharCode(buf[i])
  8223. }
  8224. return ret
  8225. }
  8226. function hexSlice (buf, start, end) {
  8227. var len = buf.length
  8228. if (!start || start < 0) start = 0
  8229. if (!end || end < 0 || end > len) end = len
  8230. var out = ''
  8231. for (var i = start; i < end; ++i) {
  8232. out += toHex(buf[i])
  8233. }
  8234. return out
  8235. }
  8236. function utf16leSlice (buf, start, end) {
  8237. var bytes = buf.slice(start, end)
  8238. var res = ''
  8239. for (var i = 0; i < bytes.length; i += 2) {
  8240. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  8241. }
  8242. return res
  8243. }
  8244. Buffer.prototype.slice = function slice (start, end) {
  8245. var len = this.length
  8246. start = ~~start
  8247. end = end === undefined ? len : ~~end
  8248. if (start < 0) {
  8249. start += len
  8250. if (start < 0) start = 0
  8251. } else if (start > len) {
  8252. start = len
  8253. }
  8254. if (end < 0) {
  8255. end += len
  8256. if (end < 0) end = 0
  8257. } else if (end > len) {
  8258. end = len
  8259. }
  8260. if (end < start) end = start
  8261. var newBuf = this.subarray(start, end)
  8262. // Return an augmented `Uint8Array` instance
  8263. newBuf.__proto__ = Buffer.prototype
  8264. return newBuf
  8265. }
  8266. /*
  8267. * Need to make sure that buffer isn't trying to write out of bounds.
  8268. */
  8269. function checkOffset (offset, ext, length) {
  8270. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  8271. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  8272. }
  8273. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  8274. offset = offset >>> 0
  8275. byteLength = byteLength >>> 0
  8276. if (!noAssert) checkOffset(offset, byteLength, this.length)
  8277. var val = this[offset]
  8278. var mul = 1
  8279. var i = 0
  8280. while (++i < byteLength && (mul *= 0x100)) {
  8281. val += this[offset + i] * mul
  8282. }
  8283. return val
  8284. }
  8285. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  8286. offset = offset >>> 0
  8287. byteLength = byteLength >>> 0
  8288. if (!noAssert) {
  8289. checkOffset(offset, byteLength, this.length)
  8290. }
  8291. var val = this[offset + --byteLength]
  8292. var mul = 1
  8293. while (byteLength > 0 && (mul *= 0x100)) {
  8294. val += this[offset + --byteLength] * mul
  8295. }
  8296. return val
  8297. }
  8298. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  8299. offset = offset >>> 0
  8300. if (!noAssert) checkOffset(offset, 1, this.length)
  8301. return this[offset]
  8302. }
  8303. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  8304. offset = offset >>> 0
  8305. if (!noAssert) checkOffset(offset, 2, this.length)
  8306. return this[offset] | (this[offset + 1] << 8)
  8307. }
  8308. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  8309. offset = offset >>> 0
  8310. if (!noAssert) checkOffset(offset, 2, this.length)
  8311. return (this[offset] << 8) | this[offset + 1]
  8312. }
  8313. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  8314. offset = offset >>> 0
  8315. if (!noAssert) checkOffset(offset, 4, this.length)
  8316. return ((this[offset]) |
  8317. (this[offset + 1] << 8) |
  8318. (this[offset + 2] << 16)) +
  8319. (this[offset + 3] * 0x1000000)
  8320. }
  8321. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  8322. offset = offset >>> 0
  8323. if (!noAssert) checkOffset(offset, 4, this.length)
  8324. return (this[offset] * 0x1000000) +
  8325. ((this[offset + 1] << 16) |
  8326. (this[offset + 2] << 8) |
  8327. this[offset + 3])
  8328. }
  8329. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  8330. offset = offset >>> 0
  8331. byteLength = byteLength >>> 0
  8332. if (!noAssert) checkOffset(offset, byteLength, this.length)
  8333. var val = this[offset]
  8334. var mul = 1
  8335. var i = 0
  8336. while (++i < byteLength && (mul *= 0x100)) {
  8337. val += this[offset + i] * mul
  8338. }
  8339. mul *= 0x80
  8340. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  8341. return val
  8342. }
  8343. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  8344. offset = offset >>> 0
  8345. byteLength = byteLength >>> 0
  8346. if (!noAssert) checkOffset(offset, byteLength, this.length)
  8347. var i = byteLength
  8348. var mul = 1
  8349. var val = this[offset + --i]
  8350. while (i > 0 && (mul *= 0x100)) {
  8351. val += this[offset + --i] * mul
  8352. }
  8353. mul *= 0x80
  8354. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  8355. return val
  8356. }
  8357. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  8358. offset = offset >>> 0
  8359. if (!noAssert) checkOffset(offset, 1, this.length)
  8360. if (!(this[offset] & 0x80)) return (this[offset])
  8361. return ((0xff - this[offset] + 1) * -1)
  8362. }
  8363. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  8364. offset = offset >>> 0
  8365. if (!noAssert) checkOffset(offset, 2, this.length)
  8366. var val = this[offset] | (this[offset + 1] << 8)
  8367. return (val & 0x8000) ? val | 0xFFFF0000 : val
  8368. }
  8369. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  8370. offset = offset >>> 0
  8371. if (!noAssert) checkOffset(offset, 2, this.length)
  8372. var val = this[offset + 1] | (this[offset] << 8)
  8373. return (val & 0x8000) ? val | 0xFFFF0000 : val
  8374. }
  8375. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  8376. offset = offset >>> 0
  8377. if (!noAssert) checkOffset(offset, 4, this.length)
  8378. return (this[offset]) |
  8379. (this[offset + 1] << 8) |
  8380. (this[offset + 2] << 16) |
  8381. (this[offset + 3] << 24)
  8382. }
  8383. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  8384. offset = offset >>> 0
  8385. if (!noAssert) checkOffset(offset, 4, this.length)
  8386. return (this[offset] << 24) |
  8387. (this[offset + 1] << 16) |
  8388. (this[offset + 2] << 8) |
  8389. (this[offset + 3])
  8390. }
  8391. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  8392. offset = offset >>> 0
  8393. if (!noAssert) checkOffset(offset, 4, this.length)
  8394. return ieee754.read(this, offset, true, 23, 4)
  8395. }
  8396. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  8397. offset = offset >>> 0
  8398. if (!noAssert) checkOffset(offset, 4, this.length)
  8399. return ieee754.read(this, offset, false, 23, 4)
  8400. }
  8401. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  8402. offset = offset >>> 0
  8403. if (!noAssert) checkOffset(offset, 8, this.length)
  8404. return ieee754.read(this, offset, true, 52, 8)
  8405. }
  8406. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  8407. offset = offset >>> 0
  8408. if (!noAssert) checkOffset(offset, 8, this.length)
  8409. return ieee754.read(this, offset, false, 52, 8)
  8410. }
  8411. function checkInt (buf, value, offset, ext, max, min) {
  8412. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  8413. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  8414. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  8415. }
  8416. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  8417. value = +value
  8418. offset = offset >>> 0
  8419. byteLength = byteLength >>> 0
  8420. if (!noAssert) {
  8421. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  8422. checkInt(this, value, offset, byteLength, maxBytes, 0)
  8423. }
  8424. var mul = 1
  8425. var i = 0
  8426. this[offset] = value & 0xFF
  8427. while (++i < byteLength && (mul *= 0x100)) {
  8428. this[offset + i] = (value / mul) & 0xFF
  8429. }
  8430. return offset + byteLength
  8431. }
  8432. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  8433. value = +value
  8434. offset = offset >>> 0
  8435. byteLength = byteLength >>> 0
  8436. if (!noAssert) {
  8437. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  8438. checkInt(this, value, offset, byteLength, maxBytes, 0)
  8439. }
  8440. var i = byteLength - 1
  8441. var mul = 1
  8442. this[offset + i] = value & 0xFF
  8443. while (--i >= 0 && (mul *= 0x100)) {
  8444. this[offset + i] = (value / mul) & 0xFF
  8445. }
  8446. return offset + byteLength
  8447. }
  8448. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  8449. value = +value
  8450. offset = offset >>> 0
  8451. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  8452. this[offset] = (value & 0xff)
  8453. return offset + 1
  8454. }
  8455. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  8456. value = +value
  8457. offset = offset >>> 0
  8458. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  8459. this[offset] = (value & 0xff)
  8460. this[offset + 1] = (value >>> 8)
  8461. return offset + 2
  8462. }
  8463. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  8464. value = +value
  8465. offset = offset >>> 0
  8466. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  8467. this[offset] = (value >>> 8)
  8468. this[offset + 1] = (value & 0xff)
  8469. return offset + 2
  8470. }
  8471. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  8472. value = +value
  8473. offset = offset >>> 0
  8474. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  8475. this[offset + 3] = (value >>> 24)
  8476. this[offset + 2] = (value >>> 16)
  8477. this[offset + 1] = (value >>> 8)
  8478. this[offset] = (value & 0xff)
  8479. return offset + 4
  8480. }
  8481. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  8482. value = +value
  8483. offset = offset >>> 0
  8484. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  8485. this[offset] = (value >>> 24)
  8486. this[offset + 1] = (value >>> 16)
  8487. this[offset + 2] = (value >>> 8)
  8488. this[offset + 3] = (value & 0xff)
  8489. return offset + 4
  8490. }
  8491. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  8492. value = +value
  8493. offset = offset >>> 0
  8494. if (!noAssert) {
  8495. var limit = Math.pow(2, (8 * byteLength) - 1)
  8496. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  8497. }
  8498. var i = 0
  8499. var mul = 1
  8500. var sub = 0
  8501. this[offset] = value & 0xFF
  8502. while (++i < byteLength && (mul *= 0x100)) {
  8503. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  8504. sub = 1
  8505. }
  8506. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  8507. }
  8508. return offset + byteLength
  8509. }
  8510. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  8511. value = +value
  8512. offset = offset >>> 0
  8513. if (!noAssert) {
  8514. var limit = Math.pow(2, (8 * byteLength) - 1)
  8515. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  8516. }
  8517. var i = byteLength - 1
  8518. var mul = 1
  8519. var sub = 0
  8520. this[offset + i] = value & 0xFF
  8521. while (--i >= 0 && (mul *= 0x100)) {
  8522. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  8523. sub = 1
  8524. }
  8525. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  8526. }
  8527. return offset + byteLength
  8528. }
  8529. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  8530. value = +value
  8531. offset = offset >>> 0
  8532. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  8533. if (value < 0) value = 0xff + value + 1
  8534. this[offset] = (value & 0xff)
  8535. return offset + 1
  8536. }
  8537. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  8538. value = +value
  8539. offset = offset >>> 0
  8540. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  8541. this[offset] = (value & 0xff)
  8542. this[offset + 1] = (value >>> 8)
  8543. return offset + 2
  8544. }
  8545. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  8546. value = +value
  8547. offset = offset >>> 0
  8548. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  8549. this[offset] = (value >>> 8)
  8550. this[offset + 1] = (value & 0xff)
  8551. return offset + 2
  8552. }
  8553. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  8554. value = +value
  8555. offset = offset >>> 0
  8556. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  8557. this[offset] = (value & 0xff)
  8558. this[offset + 1] = (value >>> 8)
  8559. this[offset + 2] = (value >>> 16)
  8560. this[offset + 3] = (value >>> 24)
  8561. return offset + 4
  8562. }
  8563. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  8564. value = +value
  8565. offset = offset >>> 0
  8566. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  8567. if (value < 0) value = 0xffffffff + value + 1
  8568. this[offset] = (value >>> 24)
  8569. this[offset + 1] = (value >>> 16)
  8570. this[offset + 2] = (value >>> 8)
  8571. this[offset + 3] = (value & 0xff)
  8572. return offset + 4
  8573. }
  8574. function checkIEEE754 (buf, value, offset, ext, max, min) {
  8575. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  8576. if (offset < 0) throw new RangeError('Index out of range')
  8577. }
  8578. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  8579. value = +value
  8580. offset = offset >>> 0
  8581. if (!noAssert) {
  8582. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  8583. }
  8584. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  8585. return offset + 4
  8586. }
  8587. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  8588. return writeFloat(this, value, offset, true, noAssert)
  8589. }
  8590. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  8591. return writeFloat(this, value, offset, false, noAssert)
  8592. }
  8593. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  8594. value = +value
  8595. offset = offset >>> 0
  8596. if (!noAssert) {
  8597. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  8598. }
  8599. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  8600. return offset + 8
  8601. }
  8602. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  8603. return writeDouble(this, value, offset, true, noAssert)
  8604. }
  8605. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  8606. return writeDouble(this, value, offset, false, noAssert)
  8607. }
  8608. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  8609. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  8610. if (!start) start = 0
  8611. if (!end && end !== 0) end = this.length
  8612. if (targetStart >= target.length) targetStart = target.length
  8613. if (!targetStart) targetStart = 0
  8614. if (end > 0 && end < start) end = start
  8615. // Copy 0 bytes; we're done
  8616. if (end === start) return 0
  8617. if (target.length === 0 || this.length === 0) return 0
  8618. // Fatal error conditions
  8619. if (targetStart < 0) {
  8620. throw new RangeError('targetStart out of bounds')
  8621. }
  8622. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  8623. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  8624. // Are we oob?
  8625. if (end > this.length) end = this.length
  8626. if (target.length - targetStart < end - start) {
  8627. end = target.length - targetStart + start
  8628. }
  8629. var len = end - start
  8630. var i
  8631. if (this === target && start < targetStart && targetStart < end) {
  8632. // descending copy from end
  8633. for (i = len - 1; i >= 0; --i) {
  8634. target[i + targetStart] = this[i + start]
  8635. }
  8636. } else if (len < 1000) {
  8637. // ascending copy from start
  8638. for (i = 0; i < len; ++i) {
  8639. target[i + targetStart] = this[i + start]
  8640. }
  8641. } else {
  8642. Uint8Array.prototype.set.call(
  8643. target,
  8644. this.subarray(start, start + len),
  8645. targetStart
  8646. )
  8647. }
  8648. return len
  8649. }
  8650. // Usage:
  8651. // buffer.fill(number[, offset[, end]])
  8652. // buffer.fill(buffer[, offset[, end]])
  8653. // buffer.fill(string[, offset[, end]][, encoding])
  8654. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  8655. // Handle string cases:
  8656. if (typeof val === 'string') {
  8657. if (typeof start === 'string') {
  8658. encoding = start
  8659. start = 0
  8660. end = this.length
  8661. } else if (typeof end === 'string') {
  8662. encoding = end
  8663. end = this.length
  8664. }
  8665. if (val.length === 1) {
  8666. var code = val.charCodeAt(0)
  8667. if (code < 256) {
  8668. val = code
  8669. }
  8670. }
  8671. if (encoding !== undefined && typeof encoding !== 'string') {
  8672. throw new TypeError('encoding must be a string')
  8673. }
  8674. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  8675. throw new TypeError('Unknown encoding: ' + encoding)
  8676. }
  8677. } else if (typeof val === 'number') {
  8678. val = val & 255
  8679. }
  8680. // Invalid ranges are not set to a default, so can range check early.
  8681. if (start < 0 || this.length < start || this.length < end) {
  8682. throw new RangeError('Out of range index')
  8683. }
  8684. if (end <= start) {
  8685. return this
  8686. }
  8687. start = start >>> 0
  8688. end = end === undefined ? this.length : end >>> 0
  8689. if (!val) val = 0
  8690. var i
  8691. if (typeof val === 'number') {
  8692. for (i = start; i < end; ++i) {
  8693. this[i] = val
  8694. }
  8695. } else {
  8696. var bytes = Buffer.isBuffer(val)
  8697. ? val
  8698. : new Buffer(val, encoding)
  8699. var len = bytes.length
  8700. for (i = 0; i < end - start; ++i) {
  8701. this[i + start] = bytes[i % len]
  8702. }
  8703. }
  8704. return this
  8705. }
  8706. // HELPER FUNCTIONS
  8707. // ================
  8708. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  8709. function base64clean (str) {
  8710. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  8711. str = str.trim().replace(INVALID_BASE64_RE, '')
  8712. // Node converts strings with length < 2 to ''
  8713. if (str.length < 2) return ''
  8714. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  8715. while (str.length % 4 !== 0) {
  8716. str = str + '='
  8717. }
  8718. return str
  8719. }
  8720. function toHex (n) {
  8721. if (n < 16) return '0' + n.toString(16)
  8722. return n.toString(16)
  8723. }
  8724. function utf8ToBytes (string, units) {
  8725. units = units || Infinity
  8726. var codePoint
  8727. var length = string.length
  8728. var leadSurrogate = null
  8729. var bytes = []
  8730. for (var i = 0; i < length; ++i) {
  8731. codePoint = string.charCodeAt(i)
  8732. // is surrogate component
  8733. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  8734. // last char was a lead
  8735. if (!leadSurrogate) {
  8736. // no lead yet
  8737. if (codePoint > 0xDBFF) {
  8738. // unexpected trail
  8739. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  8740. continue
  8741. } else if (i + 1 === length) {
  8742. // unpaired lead
  8743. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  8744. continue
  8745. }
  8746. // valid lead
  8747. leadSurrogate = codePoint
  8748. continue
  8749. }
  8750. // 2 leads in a row
  8751. if (codePoint < 0xDC00) {
  8752. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  8753. leadSurrogate = codePoint
  8754. continue
  8755. }
  8756. // valid surrogate pair
  8757. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  8758. } else if (leadSurrogate) {
  8759. // valid bmp char, but last char was a lead
  8760. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  8761. }
  8762. leadSurrogate = null
  8763. // encode utf8
  8764. if (codePoint < 0x80) {
  8765. if ((units -= 1) < 0) break
  8766. bytes.push(codePoint)
  8767. } else if (codePoint < 0x800) {
  8768. if ((units -= 2) < 0) break
  8769. bytes.push(
  8770. codePoint >> 0x6 | 0xC0,
  8771. codePoint & 0x3F | 0x80
  8772. )
  8773. } else if (codePoint < 0x10000) {
  8774. if ((units -= 3) < 0) break
  8775. bytes.push(
  8776. codePoint >> 0xC | 0xE0,
  8777. codePoint >> 0x6 & 0x3F | 0x80,
  8778. codePoint & 0x3F | 0x80
  8779. )
  8780. } else if (codePoint < 0x110000) {
  8781. if ((units -= 4) < 0) break
  8782. bytes.push(
  8783. codePoint >> 0x12 | 0xF0,
  8784. codePoint >> 0xC & 0x3F | 0x80,
  8785. codePoint >> 0x6 & 0x3F | 0x80,
  8786. codePoint & 0x3F | 0x80
  8787. )
  8788. } else {
  8789. throw new Error('Invalid code point')
  8790. }
  8791. }
  8792. return bytes
  8793. }
  8794. function asciiToBytes (str) {
  8795. var byteArray = []
  8796. for (var i = 0; i < str.length; ++i) {
  8797. // Node's code seems to be doing this and not & 0x7F..
  8798. byteArray.push(str.charCodeAt(i) & 0xFF)
  8799. }
  8800. return byteArray
  8801. }
  8802. function utf16leToBytes (str, units) {
  8803. var c, hi, lo
  8804. var byteArray = []
  8805. for (var i = 0; i < str.length; ++i) {
  8806. if ((units -= 2) < 0) break
  8807. c = str.charCodeAt(i)
  8808. hi = c >> 8
  8809. lo = c % 256
  8810. byteArray.push(lo)
  8811. byteArray.push(hi)
  8812. }
  8813. return byteArray
  8814. }
  8815. function base64ToBytes (str) {
  8816. return base64.toByteArray(base64clean(str))
  8817. }
  8818. function blitBuffer (src, dst, offset, length) {
  8819. for (var i = 0; i < length; ++i) {
  8820. if ((i + offset >= dst.length) || (i >= src.length)) break
  8821. dst[i + offset] = src[i]
  8822. }
  8823. return i
  8824. }
  8825. // ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check
  8826. // but they should be treated as valid. See: https://github.com/feross/buffer/issues/166
  8827. function isArrayBuffer (obj) {
  8828. return obj instanceof ArrayBuffer ||
  8829. (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&
  8830. typeof obj.byteLength === 'number')
  8831. }
  8832. // Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
  8833. function isArrayBufferView (obj) {
  8834. return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
  8835. }
  8836. function numberIsNaN (obj) {
  8837. return obj !== obj // eslint-disable-line no-self-compare
  8838. }
  8839. },{"base64-js":16,"ieee754":102}],51:[function(require,module,exports){
  8840. var Buffer = require('safe-buffer').Buffer
  8841. var Transform = require('stream').Transform
  8842. var StringDecoder = require('string_decoder').StringDecoder
  8843. var inherits = require('inherits')
  8844. function CipherBase (hashMode) {
  8845. Transform.call(this)
  8846. this.hashMode = typeof hashMode === 'string'
  8847. if (this.hashMode) {
  8848. this[hashMode] = this._finalOrDigest
  8849. } else {
  8850. this.final = this._finalOrDigest
  8851. }
  8852. if (this._final) {
  8853. this.__final = this._final
  8854. this._final = null
  8855. }
  8856. this._decoder = null
  8857. this._encoding = null
  8858. }
  8859. inherits(CipherBase, Transform)
  8860. CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
  8861. if (typeof data === 'string') {
  8862. data = Buffer.from(data, inputEnc)
  8863. }
  8864. var outData = this._update(data)
  8865. if (this.hashMode) return this
  8866. if (outputEnc) {
  8867. outData = this._toString(outData, outputEnc)
  8868. }
  8869. return outData
  8870. }
  8871. CipherBase.prototype.setAutoPadding = function () {}
  8872. CipherBase.prototype.getAuthTag = function () {
  8873. throw new Error('trying to get auth tag in unsupported state')
  8874. }
  8875. CipherBase.prototype.setAuthTag = function () {
  8876. throw new Error('trying to set auth tag in unsupported state')
  8877. }
  8878. CipherBase.prototype.setAAD = function () {
  8879. throw new Error('trying to set aad in unsupported state')
  8880. }
  8881. CipherBase.prototype._transform = function (data, _, next) {
  8882. var err
  8883. try {
  8884. if (this.hashMode) {
  8885. this._update(data)
  8886. } else {
  8887. this.push(this._update(data))
  8888. }
  8889. } catch (e) {
  8890. err = e
  8891. } finally {
  8892. next(err)
  8893. }
  8894. }
  8895. CipherBase.prototype._flush = function (done) {
  8896. var err
  8897. try {
  8898. this.push(this.__final())
  8899. } catch (e) {
  8900. err = e
  8901. }
  8902. done(err)
  8903. }
  8904. CipherBase.prototype._finalOrDigest = function (outputEnc) {
  8905. var outData = this.__final() || Buffer.alloc(0)
  8906. if (outputEnc) {
  8907. outData = this._toString(outData, outputEnc, true)
  8908. }
  8909. return outData
  8910. }
  8911. CipherBase.prototype._toString = function (value, enc, fin) {
  8912. if (!this._decoder) {
  8913. this._decoder = new StringDecoder(enc)
  8914. this._encoding = enc
  8915. }
  8916. if (this._encoding !== enc) throw new Error('can\'t switch encodings')
  8917. var out = this._decoder.write(value)
  8918. if (fin) {
  8919. out += this._decoder.end()
  8920. }
  8921. return out
  8922. }
  8923. module.exports = CipherBase
  8924. },{"inherits":104,"safe-buffer":157,"stream":166,"string_decoder":167}],52:[function(require,module,exports){
  8925. (function (Buffer){
  8926. // Copyright Joyent, Inc. and other Node contributors.
  8927. //
  8928. // Permission is hereby granted, free of charge, to any person obtaining a
  8929. // copy of this software and associated documentation files (the
  8930. // "Software"), to deal in the Software without restriction, including
  8931. // without limitation the rights to use, copy, modify, merge, publish,
  8932. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8933. // persons to whom the Software is furnished to do so, subject to the
  8934. // following conditions:
  8935. //
  8936. // The above copyright notice and this permission notice shall be included
  8937. // in all copies or substantial portions of the Software.
  8938. //
  8939. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8940. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8941. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8942. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8943. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8944. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8945. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8946. // NOTE: These type checking functions intentionally don't use `instanceof`
  8947. // because it is fragile and can be easily faked with `Object.create()`.
  8948. function isArray(arg) {
  8949. if (Array.isArray) {
  8950. return Array.isArray(arg);
  8951. }
  8952. return objectToString(arg) === '[object Array]';
  8953. }
  8954. exports.isArray = isArray;
  8955. function isBoolean(arg) {
  8956. return typeof arg === 'boolean';
  8957. }
  8958. exports.isBoolean = isBoolean;
  8959. function isNull(arg) {
  8960. return arg === null;
  8961. }
  8962. exports.isNull = isNull;
  8963. function isNullOrUndefined(arg) {
  8964. return arg == null;
  8965. }
  8966. exports.isNullOrUndefined = isNullOrUndefined;
  8967. function isNumber(arg) {
  8968. return typeof arg === 'number';
  8969. }
  8970. exports.isNumber = isNumber;
  8971. function isString(arg) {
  8972. return typeof arg === 'string';
  8973. }
  8974. exports.isString = isString;
  8975. function isSymbol(arg) {
  8976. return typeof arg === 'symbol';
  8977. }
  8978. exports.isSymbol = isSymbol;
  8979. function isUndefined(arg) {
  8980. return arg === void 0;
  8981. }
  8982. exports.isUndefined = isUndefined;
  8983. function isRegExp(re) {
  8984. return objectToString(re) === '[object RegExp]';
  8985. }
  8986. exports.isRegExp = isRegExp;
  8987. function isObject(arg) {
  8988. return typeof arg === 'object' && arg !== null;
  8989. }
  8990. exports.isObject = isObject;
  8991. function isDate(d) {
  8992. return objectToString(d) === '[object Date]';
  8993. }
  8994. exports.isDate = isDate;
  8995. function isError(e) {
  8996. return (objectToString(e) === '[object Error]' || e instanceof Error);
  8997. }
  8998. exports.isError = isError;
  8999. function isFunction(arg) {
  9000. return typeof arg === 'function';
  9001. }
  9002. exports.isFunction = isFunction;
  9003. function isPrimitive(arg) {
  9004. return arg === null ||
  9005. typeof arg === 'boolean' ||
  9006. typeof arg === 'number' ||
  9007. typeof arg === 'string' ||
  9008. typeof arg === 'symbol' || // ES6 symbol
  9009. typeof arg === 'undefined';
  9010. }
  9011. exports.isPrimitive = isPrimitive;
  9012. exports.isBuffer = Buffer.isBuffer;
  9013. function objectToString(o) {
  9014. return Object.prototype.toString.call(o);
  9015. }
  9016. }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
  9017. },{"../../is-buffer/index.js":105}],53:[function(require,module,exports){
  9018. (function (Buffer){
  9019. var elliptic = require('elliptic');
  9020. var BN = require('bn.js');
  9021. module.exports = function createECDH(curve) {
  9022. return new ECDH(curve);
  9023. };
  9024. var aliases = {
  9025. secp256k1: {
  9026. name: 'secp256k1',
  9027. byteLength: 32
  9028. },
  9029. secp224r1: {
  9030. name: 'p224',
  9031. byteLength: 28
  9032. },
  9033. prime256v1: {
  9034. name: 'p256',
  9035. byteLength: 32
  9036. },
  9037. prime192v1: {
  9038. name: 'p192',
  9039. byteLength: 24
  9040. },
  9041. ed25519: {
  9042. name: 'ed25519',
  9043. byteLength: 32
  9044. },
  9045. secp384r1: {
  9046. name: 'p384',
  9047. byteLength: 48
  9048. },
  9049. secp521r1: {
  9050. name: 'p521',
  9051. byteLength: 66
  9052. }
  9053. };
  9054. aliases.p224 = aliases.secp224r1;
  9055. aliases.p256 = aliases.secp256r1 = aliases.prime256v1;
  9056. aliases.p192 = aliases.secp192r1 = aliases.prime192v1;
  9057. aliases.p384 = aliases.secp384r1;
  9058. aliases.p521 = aliases.secp521r1;
  9059. function ECDH(curve) {
  9060. this.curveType = aliases[curve];
  9061. if (!this.curveType ) {
  9062. this.curveType = {
  9063. name: curve
  9064. };
  9065. }
  9066. this.curve = new elliptic.ec(this.curveType.name);
  9067. this.keys = void 0;
  9068. }
  9069. ECDH.prototype.generateKeys = function (enc, format) {
  9070. this.keys = this.curve.genKeyPair();
  9071. return this.getPublicKey(enc, format);
  9072. };
  9073. ECDH.prototype.computeSecret = function (other, inenc, enc) {
  9074. inenc = inenc || 'utf8';
  9075. if (!Buffer.isBuffer(other)) {
  9076. other = new Buffer(other, inenc);
  9077. }
  9078. var otherPub = this.curve.keyFromPublic(other).getPublic();
  9079. var out = otherPub.mul(this.keys.getPrivate()).getX();
  9080. return formatReturnValue(out, enc, this.curveType.byteLength);
  9081. };
  9082. ECDH.prototype.getPublicKey = function (enc, format) {
  9083. var key = this.keys.getPublic(format === 'compressed', true);
  9084. if (format === 'hybrid') {
  9085. if (key[key.length - 1] % 2) {
  9086. key[0] = 7;
  9087. } else {
  9088. key [0] = 6;
  9089. }
  9090. }
  9091. return formatReturnValue(key, enc);
  9092. };
  9093. ECDH.prototype.getPrivateKey = function (enc) {
  9094. return formatReturnValue(this.keys.getPrivate(), enc);
  9095. };
  9096. ECDH.prototype.setPublicKey = function (pub, enc) {
  9097. enc = enc || 'utf8';
  9098. if (!Buffer.isBuffer(pub)) {
  9099. pub = new Buffer(pub, enc);
  9100. }
  9101. this.keys._importPublic(pub);
  9102. return this;
  9103. };
  9104. ECDH.prototype.setPrivateKey = function (priv, enc) {
  9105. enc = enc || 'utf8';
  9106. if (!Buffer.isBuffer(priv)) {
  9107. priv = new Buffer(priv, enc);
  9108. }
  9109. var _priv = new BN(priv);
  9110. _priv = _priv.toString(16);
  9111. this.keys._importPrivate(_priv);
  9112. return this;
  9113. };
  9114. function formatReturnValue(bn, enc, len) {
  9115. if (!Array.isArray(bn)) {
  9116. bn = bn.toArray();
  9117. }
  9118. var buf = new Buffer(bn);
  9119. if (len && buf.length < len) {
  9120. var zeros = new Buffer(len - buf.length);
  9121. zeros.fill(0);
  9122. buf = Buffer.concat([zeros, buf]);
  9123. }
  9124. if (!enc) {
  9125. return buf;
  9126. } else {
  9127. return buf.toString(enc);
  9128. }
  9129. }
  9130. }).call(this,require("buffer").Buffer)
  9131. },{"bn.js":17,"buffer":50,"elliptic":70}],54:[function(require,module,exports){
  9132. (function (Buffer){
  9133. 'use strict'
  9134. var inherits = require('inherits')
  9135. var md5 = require('./md5')
  9136. var RIPEMD160 = require('ripemd160')
  9137. var sha = require('sha.js')
  9138. var Base = require('cipher-base')
  9139. function HashNoConstructor (hash) {
  9140. Base.call(this, 'digest')
  9141. this._hash = hash
  9142. this.buffers = []
  9143. }
  9144. inherits(HashNoConstructor, Base)
  9145. HashNoConstructor.prototype._update = function (data) {
  9146. this.buffers.push(data)
  9147. }
  9148. HashNoConstructor.prototype._final = function () {
  9149. var buf = Buffer.concat(this.buffers)
  9150. var r = this._hash(buf)
  9151. this.buffers = null
  9152. return r
  9153. }
  9154. function Hash (hash) {
  9155. Base.call(this, 'digest')
  9156. this._hash = hash
  9157. }
  9158. inherits(Hash, Base)
  9159. Hash.prototype._update = function (data) {
  9160. this._hash.update(data)
  9161. }
  9162. Hash.prototype._final = function () {
  9163. return this._hash.digest()
  9164. }
  9165. module.exports = function createHash (alg) {
  9166. alg = alg.toLowerCase()
  9167. if (alg === 'md5') return new HashNoConstructor(md5)
  9168. if (alg === 'rmd160' || alg === 'ripemd160') return new Hash(new RIPEMD160())
  9169. return new Hash(sha(alg))
  9170. }
  9171. }).call(this,require("buffer").Buffer)
  9172. },{"./md5":56,"buffer":50,"cipher-base":51,"inherits":104,"ripemd160":156,"sha.js":159}],55:[function(require,module,exports){
  9173. (function (Buffer){
  9174. 'use strict'
  9175. var intSize = 4
  9176. var zeroBuffer = new Buffer(intSize)
  9177. zeroBuffer.fill(0)
  9178. var charSize = 8
  9179. var hashSize = 16
  9180. function toArray (buf) {
  9181. if ((buf.length % intSize) !== 0) {
  9182. var len = buf.length + (intSize - (buf.length % intSize))
  9183. buf = Buffer.concat([buf, zeroBuffer], len)
  9184. }
  9185. var arr = new Array(buf.length >>> 2)
  9186. for (var i = 0, j = 0; i < buf.length; i += intSize, j++) {
  9187. arr[j] = buf.readInt32LE(i)
  9188. }
  9189. return arr
  9190. }
  9191. module.exports = function hash (buf, fn) {
  9192. var arr = fn(toArray(buf), buf.length * charSize)
  9193. buf = new Buffer(hashSize)
  9194. for (var i = 0; i < arr.length; i++) {
  9195. buf.writeInt32LE(arr[i], i << 2, true)
  9196. }
  9197. return buf
  9198. }
  9199. }).call(this,require("buffer").Buffer)
  9200. },{"buffer":50}],56:[function(require,module,exports){
  9201. 'use strict'
  9202. /*
  9203. * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
  9204. * Digest Algorithm, as defined in RFC 1321.
  9205. * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
  9206. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  9207. * Distributed under the BSD License
  9208. * See http://pajhome.org.uk/crypt/md5 for more info.
  9209. */
  9210. var makeHash = require('./make-hash')
  9211. /*
  9212. * Calculate the MD5 of an array of little-endian words, and a bit length
  9213. */
  9214. function core_md5 (x, len) {
  9215. /* append padding */
  9216. x[len >> 5] |= 0x80 << ((len) % 32)
  9217. x[(((len + 64) >>> 9) << 4) + 14] = len
  9218. var a = 1732584193
  9219. var b = -271733879
  9220. var c = -1732584194
  9221. var d = 271733878
  9222. for (var i = 0; i < x.length; i += 16) {
  9223. var olda = a
  9224. var oldb = b
  9225. var oldc = c
  9226. var oldd = d
  9227. a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936)
  9228. d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586)
  9229. c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819)
  9230. b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330)
  9231. a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897)
  9232. d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426)
  9233. c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341)
  9234. b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983)
  9235. a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416)
  9236. d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417)
  9237. c = md5_ff(c, d, a, b, x[i + 10], 17, -42063)
  9238. b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162)
  9239. a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682)
  9240. d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101)
  9241. c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290)
  9242. b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329)
  9243. a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510)
  9244. d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632)
  9245. c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713)
  9246. b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302)
  9247. a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691)
  9248. d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083)
  9249. c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335)
  9250. b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848)
  9251. a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438)
  9252. d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690)
  9253. c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961)
  9254. b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501)
  9255. a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467)
  9256. d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784)
  9257. c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473)
  9258. b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734)
  9259. a = md5_hh(a, b, c, d, x[i + 5], 4, -378558)
  9260. d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463)
  9261. c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562)
  9262. b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556)
  9263. a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060)
  9264. d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353)
  9265. c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632)
  9266. b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640)
  9267. a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174)
  9268. d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222)
  9269. c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979)
  9270. b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189)
  9271. a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487)
  9272. d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835)
  9273. c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520)
  9274. b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651)
  9275. a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844)
  9276. d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415)
  9277. c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905)
  9278. b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055)
  9279. a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571)
  9280. d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606)
  9281. c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523)
  9282. b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799)
  9283. a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359)
  9284. d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744)
  9285. c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380)
  9286. b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649)
  9287. a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070)
  9288. d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379)
  9289. c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259)
  9290. b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551)
  9291. a = safe_add(a, olda)
  9292. b = safe_add(b, oldb)
  9293. c = safe_add(c, oldc)
  9294. d = safe_add(d, oldd)
  9295. }
  9296. return [a, b, c, d]
  9297. }
  9298. /*
  9299. * These functions implement the four basic operations the algorithm uses.
  9300. */
  9301. function md5_cmn (q, a, b, x, s, t) {
  9302. return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b)
  9303. }
  9304. function md5_ff (a, b, c, d, x, s, t) {
  9305. return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t)
  9306. }
  9307. function md5_gg (a, b, c, d, x, s, t) {
  9308. return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t)
  9309. }
  9310. function md5_hh (a, b, c, d, x, s, t) {
  9311. return md5_cmn(b ^ c ^ d, a, b, x, s, t)
  9312. }
  9313. function md5_ii (a, b, c, d, x, s, t) {
  9314. return md5_cmn(c ^ (b | (~d)), a, b, x, s, t)
  9315. }
  9316. /*
  9317. * Add integers, wrapping at 2^32. This uses 16-bit operations internally
  9318. * to work around bugs in some JS interpreters.
  9319. */
  9320. function safe_add (x, y) {
  9321. var lsw = (x & 0xFFFF) + (y & 0xFFFF)
  9322. var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
  9323. return (msw << 16) | (lsw & 0xFFFF)
  9324. }
  9325. /*
  9326. * Bitwise rotate a 32-bit number to the left.
  9327. */
  9328. function bit_rol (num, cnt) {
  9329. return (num << cnt) | (num >>> (32 - cnt))
  9330. }
  9331. module.exports = function md5 (buf) {
  9332. return makeHash(buf, core_md5)
  9333. }
  9334. },{"./make-hash":55}],57:[function(require,module,exports){
  9335. 'use strict'
  9336. var inherits = require('inherits')
  9337. var Legacy = require('./legacy')
  9338. var Base = require('cipher-base')
  9339. var Buffer = require('safe-buffer').Buffer
  9340. var md5 = require('create-hash/md5')
  9341. var RIPEMD160 = require('ripemd160')
  9342. var sha = require('sha.js')
  9343. var ZEROS = Buffer.alloc(128)
  9344. function Hmac (alg, key) {
  9345. Base.call(this, 'digest')
  9346. if (typeof key === 'string') {
  9347. key = Buffer.from(key)
  9348. }
  9349. var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
  9350. this._alg = alg
  9351. this._key = key
  9352. if (key.length > blocksize) {
  9353. var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
  9354. key = hash.update(key).digest()
  9355. } else if (key.length < blocksize) {
  9356. key = Buffer.concat([key, ZEROS], blocksize)
  9357. }
  9358. var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
  9359. var opad = this._opad = Buffer.allocUnsafe(blocksize)
  9360. for (var i = 0; i < blocksize; i++) {
  9361. ipad[i] = key[i] ^ 0x36
  9362. opad[i] = key[i] ^ 0x5C
  9363. }
  9364. this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
  9365. this._hash.update(ipad)
  9366. }
  9367. inherits(Hmac, Base)
  9368. Hmac.prototype._update = function (data) {
  9369. this._hash.update(data)
  9370. }
  9371. Hmac.prototype._final = function () {
  9372. var h = this._hash.digest()
  9373. var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg)
  9374. return hash.update(this._opad).update(h).digest()
  9375. }
  9376. module.exports = function createHmac (alg, key) {
  9377. alg = alg.toLowerCase()
  9378. if (alg === 'rmd160' || alg === 'ripemd160') {
  9379. return new Hmac('rmd160', key)
  9380. }
  9381. if (alg === 'md5') {
  9382. return new Legacy(md5, key)
  9383. }
  9384. return new Hmac(alg, key)
  9385. }
  9386. },{"./legacy":58,"cipher-base":51,"create-hash/md5":56,"inherits":104,"ripemd160":156,"safe-buffer":157,"sha.js":159}],58:[function(require,module,exports){
  9387. 'use strict'
  9388. var inherits = require('inherits')
  9389. var Buffer = require('safe-buffer').Buffer
  9390. var Base = require('cipher-base')
  9391. var ZEROS = Buffer.alloc(128)
  9392. var blocksize = 64
  9393. function Hmac (alg, key) {
  9394. Base.call(this, 'digest')
  9395. if (typeof key === 'string') {
  9396. key = Buffer.from(key)
  9397. }
  9398. this._alg = alg
  9399. this._key = key
  9400. if (key.length > blocksize) {
  9401. key = alg(key)
  9402. } else if (key.length < blocksize) {
  9403. key = Buffer.concat([key, ZEROS], blocksize)
  9404. }
  9405. var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
  9406. var opad = this._opad = Buffer.allocUnsafe(blocksize)
  9407. for (var i = 0; i < blocksize; i++) {
  9408. ipad[i] = key[i] ^ 0x36
  9409. opad[i] = key[i] ^ 0x5C
  9410. }
  9411. this._hash = [ipad]
  9412. }
  9413. inherits(Hmac, Base)
  9414. Hmac.prototype._update = function (data) {
  9415. this._hash.push(data)
  9416. }
  9417. Hmac.prototype._final = function () {
  9418. var h = this._alg(Buffer.concat(this._hash))
  9419. return this._alg(Buffer.concat([this._opad, h]))
  9420. }
  9421. module.exports = Hmac
  9422. },{"cipher-base":51,"inherits":104,"safe-buffer":157}],59:[function(require,module,exports){
  9423. 'use strict'
  9424. exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes')
  9425. exports.createHash = exports.Hash = require('create-hash')
  9426. exports.createHmac = exports.Hmac = require('create-hmac')
  9427. var algos = require('browserify-sign/algos')
  9428. var algoKeys = Object.keys(algos)
  9429. var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys)
  9430. exports.getHashes = function () {
  9431. return hashes
  9432. }
  9433. var p = require('pbkdf2')
  9434. exports.pbkdf2 = p.pbkdf2
  9435. exports.pbkdf2Sync = p.pbkdf2Sync
  9436. var aes = require('browserify-cipher')
  9437. exports.Cipher = aes.Cipher
  9438. exports.createCipher = aes.createCipher
  9439. exports.Cipheriv = aes.Cipheriv
  9440. exports.createCipheriv = aes.createCipheriv
  9441. exports.Decipher = aes.Decipher
  9442. exports.createDecipher = aes.createDecipher
  9443. exports.Decipheriv = aes.Decipheriv
  9444. exports.createDecipheriv = aes.createDecipheriv
  9445. exports.getCiphers = aes.getCiphers
  9446. exports.listCiphers = aes.listCiphers
  9447. var dh = require('diffie-hellman')
  9448. exports.DiffieHellmanGroup = dh.DiffieHellmanGroup
  9449. exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup
  9450. exports.getDiffieHellman = dh.getDiffieHellman
  9451. exports.createDiffieHellman = dh.createDiffieHellman
  9452. exports.DiffieHellman = dh.DiffieHellman
  9453. var sign = require('browserify-sign')
  9454. exports.createSign = sign.createSign
  9455. exports.Sign = sign.Sign
  9456. exports.createVerify = sign.createVerify
  9457. exports.Verify = sign.Verify
  9458. exports.createECDH = require('create-ecdh')
  9459. var publicEncrypt = require('public-encrypt')
  9460. exports.publicEncrypt = publicEncrypt.publicEncrypt
  9461. exports.privateEncrypt = publicEncrypt.privateEncrypt
  9462. exports.publicDecrypt = publicEncrypt.publicDecrypt
  9463. exports.privateDecrypt = publicEncrypt.privateDecrypt
  9464. // the least I can do is make error messages for the rest of the node.js/crypto api.
  9465. // ;[
  9466. // 'createCredentials'
  9467. // ].forEach(function (name) {
  9468. // exports[name] = function () {
  9469. // throw new Error([
  9470. // 'sorry, ' + name + ' is not implemented yet',
  9471. // 'we accept pull requests',
  9472. // 'https://github.com/crypto-browserify/crypto-browserify'
  9473. // ].join('\n'))
  9474. // }
  9475. // })
  9476. var rf = require('randomfill')
  9477. exports.randomFill = rf.randomFill
  9478. exports.randomFillSync = rf.randomFillSync
  9479. exports.createCredentials = function () {
  9480. throw new Error([
  9481. 'sorry, createCredentials is not implemented yet',
  9482. 'we accept pull requests',
  9483. 'https://github.com/crypto-browserify/crypto-browserify'
  9484. ].join('\n'))
  9485. }
  9486. exports.constants = {
  9487. 'DH_CHECK_P_NOT_SAFE_PRIME': 2,
  9488. 'DH_CHECK_P_NOT_PRIME': 1,
  9489. 'DH_UNABLE_TO_CHECK_GENERATOR': 4,
  9490. 'DH_NOT_SUITABLE_GENERATOR': 8,
  9491. 'NPN_ENABLED': 1,
  9492. 'ALPN_ENABLED': 1,
  9493. 'RSA_PKCS1_PADDING': 1,
  9494. 'RSA_SSLV23_PADDING': 2,
  9495. 'RSA_NO_PADDING': 3,
  9496. 'RSA_PKCS1_OAEP_PADDING': 4,
  9497. 'RSA_X931_PADDING': 5,
  9498. 'RSA_PKCS1_PSS_PADDING': 6,
  9499. 'POINT_CONVERSION_COMPRESSED': 2,
  9500. 'POINT_CONVERSION_UNCOMPRESSED': 4,
  9501. 'POINT_CONVERSION_HYBRID': 6
  9502. }
  9503. },{"browserify-cipher":37,"browserify-sign":44,"browserify-sign/algos":41,"create-ecdh":53,"create-hash":54,"create-hmac":57,"diffie-hellman":66,"pbkdf2":128,"public-encrypt":135,"randombytes":141,"randomfill":142}],60:[function(require,module,exports){
  9504. 'use strict';
  9505. exports.utils = require('./des/utils');
  9506. exports.Cipher = require('./des/cipher');
  9507. exports.DES = require('./des/des');
  9508. exports.CBC = require('./des/cbc');
  9509. exports.EDE = require('./des/ede');
  9510. },{"./des/cbc":61,"./des/cipher":62,"./des/des":63,"./des/ede":64,"./des/utils":65}],61:[function(require,module,exports){
  9511. 'use strict';
  9512. var assert = require('minimalistic-assert');
  9513. var inherits = require('inherits');
  9514. var proto = {};
  9515. function CBCState(iv) {
  9516. assert.equal(iv.length, 8, 'Invalid IV length');
  9517. this.iv = new Array(8);
  9518. for (var i = 0; i < this.iv.length; i++)
  9519. this.iv[i] = iv[i];
  9520. }
  9521. function instantiate(Base) {
  9522. function CBC(options) {
  9523. Base.call(this, options);
  9524. this._cbcInit();
  9525. }
  9526. inherits(CBC, Base);
  9527. var keys = Object.keys(proto);
  9528. for (var i = 0; i < keys.length; i++) {
  9529. var key = keys[i];
  9530. CBC.prototype[key] = proto[key];
  9531. }
  9532. CBC.create = function create(options) {
  9533. return new CBC(options);
  9534. };
  9535. return CBC;
  9536. }
  9537. exports.instantiate = instantiate;
  9538. proto._cbcInit = function _cbcInit() {
  9539. var state = new CBCState(this.options.iv);
  9540. this._cbcState = state;
  9541. };
  9542. proto._update = function _update(inp, inOff, out, outOff) {
  9543. var state = this._cbcState;
  9544. var superProto = this.constructor.super_.prototype;
  9545. var iv = state.iv;
  9546. if (this.type === 'encrypt') {
  9547. for (var i = 0; i < this.blockSize; i++)
  9548. iv[i] ^= inp[inOff + i];
  9549. superProto._update.call(this, iv, 0, out, outOff);
  9550. for (var i = 0; i < this.blockSize; i++)
  9551. iv[i] = out[outOff + i];
  9552. } else {
  9553. superProto._update.call(this, inp, inOff, out, outOff);
  9554. for (var i = 0; i < this.blockSize; i++)
  9555. out[outOff + i] ^= iv[i];
  9556. for (var i = 0; i < this.blockSize; i++)
  9557. iv[i] = inp[inOff + i];
  9558. }
  9559. };
  9560. },{"inherits":104,"minimalistic-assert":110}],62:[function(require,module,exports){
  9561. 'use strict';
  9562. var assert = require('minimalistic-assert');
  9563. function Cipher(options) {
  9564. this.options = options;
  9565. this.type = this.options.type;
  9566. this.blockSize = 8;
  9567. this._init();
  9568. this.buffer = new Array(this.blockSize);
  9569. this.bufferOff = 0;
  9570. }
  9571. module.exports = Cipher;
  9572. Cipher.prototype._init = function _init() {
  9573. // Might be overrided
  9574. };
  9575. Cipher.prototype.update = function update(data) {
  9576. if (data.length === 0)
  9577. return [];
  9578. if (this.type === 'decrypt')
  9579. return this._updateDecrypt(data);
  9580. else
  9581. return this._updateEncrypt(data);
  9582. };
  9583. Cipher.prototype._buffer = function _buffer(data, off) {
  9584. // Append data to buffer
  9585. var min = Math.min(this.buffer.length - this.bufferOff, data.length - off);
  9586. for (var i = 0; i < min; i++)
  9587. this.buffer[this.bufferOff + i] = data[off + i];
  9588. this.bufferOff += min;
  9589. // Shift next
  9590. return min;
  9591. };
  9592. Cipher.prototype._flushBuffer = function _flushBuffer(out, off) {
  9593. this._update(this.buffer, 0, out, off);
  9594. this.bufferOff = 0;
  9595. return this.blockSize;
  9596. };
  9597. Cipher.prototype._updateEncrypt = function _updateEncrypt(data) {
  9598. var inputOff = 0;
  9599. var outputOff = 0;
  9600. var count = ((this.bufferOff + data.length) / this.blockSize) | 0;
  9601. var out = new Array(count * this.blockSize);
  9602. if (this.bufferOff !== 0) {
  9603. inputOff += this._buffer(data, inputOff);
  9604. if (this.bufferOff === this.buffer.length)
  9605. outputOff += this._flushBuffer(out, outputOff);
  9606. }
  9607. // Write blocks
  9608. var max = data.length - ((data.length - inputOff) % this.blockSize);
  9609. for (; inputOff < max; inputOff += this.blockSize) {
  9610. this._update(data, inputOff, out, outputOff);
  9611. outputOff += this.blockSize;
  9612. }
  9613. // Queue rest
  9614. for (; inputOff < data.length; inputOff++, this.bufferOff++)
  9615. this.buffer[this.bufferOff] = data[inputOff];
  9616. return out;
  9617. };
  9618. Cipher.prototype._updateDecrypt = function _updateDecrypt(data) {
  9619. var inputOff = 0;
  9620. var outputOff = 0;
  9621. var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1;
  9622. var out = new Array(count * this.blockSize);
  9623. // TODO(indutny): optimize it, this is far from optimal
  9624. for (; count > 0; count--) {
  9625. inputOff += this._buffer(data, inputOff);
  9626. outputOff += this._flushBuffer(out, outputOff);
  9627. }
  9628. // Buffer rest of the input
  9629. inputOff += this._buffer(data, inputOff);
  9630. return out;
  9631. };
  9632. Cipher.prototype.final = function final(buffer) {
  9633. var first;
  9634. if (buffer)
  9635. first = this.update(buffer);
  9636. var last;
  9637. if (this.type === 'encrypt')
  9638. last = this._finalEncrypt();
  9639. else
  9640. last = this._finalDecrypt();
  9641. if (first)
  9642. return first.concat(last);
  9643. else
  9644. return last;
  9645. };
  9646. Cipher.prototype._pad = function _pad(buffer, off) {
  9647. if (off === 0)
  9648. return false;
  9649. while (off < buffer.length)
  9650. buffer[off++] = 0;
  9651. return true;
  9652. };
  9653. Cipher.prototype._finalEncrypt = function _finalEncrypt() {
  9654. if (!this._pad(this.buffer, this.bufferOff))
  9655. return [];
  9656. var out = new Array(this.blockSize);
  9657. this._update(this.buffer, 0, out, 0);
  9658. return out;
  9659. };
  9660. Cipher.prototype._unpad = function _unpad(buffer) {
  9661. return buffer;
  9662. };
  9663. Cipher.prototype._finalDecrypt = function _finalDecrypt() {
  9664. assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt');
  9665. var out = new Array(this.blockSize);
  9666. this._flushBuffer(out, 0);
  9667. return this._unpad(out);
  9668. };
  9669. },{"minimalistic-assert":110}],63:[function(require,module,exports){
  9670. 'use strict';
  9671. var assert = require('minimalistic-assert');
  9672. var inherits = require('inherits');
  9673. var des = require('../des');
  9674. var utils = des.utils;
  9675. var Cipher = des.Cipher;
  9676. function DESState() {
  9677. this.tmp = new Array(2);
  9678. this.keys = null;
  9679. }
  9680. function DES(options) {
  9681. Cipher.call(this, options);
  9682. var state = new DESState();
  9683. this._desState = state;
  9684. this.deriveKeys(state, options.key);
  9685. }
  9686. inherits(DES, Cipher);
  9687. module.exports = DES;
  9688. DES.create = function create(options) {
  9689. return new DES(options);
  9690. };
  9691. var shiftTable = [
  9692. 1, 1, 2, 2, 2, 2, 2, 2,
  9693. 1, 2, 2, 2, 2, 2, 2, 1
  9694. ];
  9695. DES.prototype.deriveKeys = function deriveKeys(state, key) {
  9696. state.keys = new Array(16 * 2);
  9697. assert.equal(key.length, this.blockSize, 'Invalid key length');
  9698. var kL = utils.readUInt32BE(key, 0);
  9699. var kR = utils.readUInt32BE(key, 4);
  9700. utils.pc1(kL, kR, state.tmp, 0);
  9701. kL = state.tmp[0];
  9702. kR = state.tmp[1];
  9703. for (var i = 0; i < state.keys.length; i += 2) {
  9704. var shift = shiftTable[i >>> 1];
  9705. kL = utils.r28shl(kL, shift);
  9706. kR = utils.r28shl(kR, shift);
  9707. utils.pc2(kL, kR, state.keys, i);
  9708. }
  9709. };
  9710. DES.prototype._update = function _update(inp, inOff, out, outOff) {
  9711. var state = this._desState;
  9712. var l = utils.readUInt32BE(inp, inOff);
  9713. var r = utils.readUInt32BE(inp, inOff + 4);
  9714. // Initial Permutation
  9715. utils.ip(l, r, state.tmp, 0);
  9716. l = state.tmp[0];
  9717. r = state.tmp[1];
  9718. if (this.type === 'encrypt')
  9719. this._encrypt(state, l, r, state.tmp, 0);
  9720. else
  9721. this._decrypt(state, l, r, state.tmp, 0);
  9722. l = state.tmp[0];
  9723. r = state.tmp[1];
  9724. utils.writeUInt32BE(out, l, outOff);
  9725. utils.writeUInt32BE(out, r, outOff + 4);
  9726. };
  9727. DES.prototype._pad = function _pad(buffer, off) {
  9728. var value = buffer.length - off;
  9729. for (var i = off; i < buffer.length; i++)
  9730. buffer[i] = value;
  9731. return true;
  9732. };
  9733. DES.prototype._unpad = function _unpad(buffer) {
  9734. var pad = buffer[buffer.length - 1];
  9735. for (var i = buffer.length - pad; i < buffer.length; i++)
  9736. assert.equal(buffer[i], pad);
  9737. return buffer.slice(0, buffer.length - pad);
  9738. };
  9739. DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) {
  9740. var l = lStart;
  9741. var r = rStart;
  9742. // Apply f() x16 times
  9743. for (var i = 0; i < state.keys.length; i += 2) {
  9744. var keyL = state.keys[i];
  9745. var keyR = state.keys[i + 1];
  9746. // f(r, k)
  9747. utils.expand(r, state.tmp, 0);
  9748. keyL ^= state.tmp[0];
  9749. keyR ^= state.tmp[1];
  9750. var s = utils.substitute(keyL, keyR);
  9751. var f = utils.permute(s);
  9752. var t = r;
  9753. r = (l ^ f) >>> 0;
  9754. l = t;
  9755. }
  9756. // Reverse Initial Permutation
  9757. utils.rip(r, l, out, off);
  9758. };
  9759. DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) {
  9760. var l = rStart;
  9761. var r = lStart;
  9762. // Apply f() x16 times
  9763. for (var i = state.keys.length - 2; i >= 0; i -= 2) {
  9764. var keyL = state.keys[i];
  9765. var keyR = state.keys[i + 1];
  9766. // f(r, k)
  9767. utils.expand(l, state.tmp, 0);
  9768. keyL ^= state.tmp[0];
  9769. keyR ^= state.tmp[1];
  9770. var s = utils.substitute(keyL, keyR);
  9771. var f = utils.permute(s);
  9772. var t = l;
  9773. l = (r ^ f) >>> 0;
  9774. r = t;
  9775. }
  9776. // Reverse Initial Permutation
  9777. utils.rip(l, r, out, off);
  9778. };
  9779. },{"../des":60,"inherits":104,"minimalistic-assert":110}],64:[function(require,module,exports){
  9780. 'use strict';
  9781. var assert = require('minimalistic-assert');
  9782. var inherits = require('inherits');
  9783. var des = require('../des');
  9784. var Cipher = des.Cipher;
  9785. var DES = des.DES;
  9786. function EDEState(type, key) {
  9787. assert.equal(key.length, 24, 'Invalid key length');
  9788. var k1 = key.slice(0, 8);
  9789. var k2 = key.slice(8, 16);
  9790. var k3 = key.slice(16, 24);
  9791. if (type === 'encrypt') {
  9792. this.ciphers = [
  9793. DES.create({ type: 'encrypt', key: k1 }),
  9794. DES.create({ type: 'decrypt', key: k2 }),
  9795. DES.create({ type: 'encrypt', key: k3 })
  9796. ];
  9797. } else {
  9798. this.ciphers = [
  9799. DES.create({ type: 'decrypt', key: k3 }),
  9800. DES.create({ type: 'encrypt', key: k2 }),
  9801. DES.create({ type: 'decrypt', key: k1 })
  9802. ];
  9803. }
  9804. }
  9805. function EDE(options) {
  9806. Cipher.call(this, options);
  9807. var state = new EDEState(this.type, this.options.key);
  9808. this._edeState = state;
  9809. }
  9810. inherits(EDE, Cipher);
  9811. module.exports = EDE;
  9812. EDE.create = function create(options) {
  9813. return new EDE(options);
  9814. };
  9815. EDE.prototype._update = function _update(inp, inOff, out, outOff) {
  9816. var state = this._edeState;
  9817. state.ciphers[0]._update(inp, inOff, out, outOff);
  9818. state.ciphers[1]._update(out, outOff, out, outOff);
  9819. state.ciphers[2]._update(out, outOff, out, outOff);
  9820. };
  9821. EDE.prototype._pad = DES.prototype._pad;
  9822. EDE.prototype._unpad = DES.prototype._unpad;
  9823. },{"../des":60,"inherits":104,"minimalistic-assert":110}],65:[function(require,module,exports){
  9824. 'use strict';
  9825. exports.readUInt32BE = function readUInt32BE(bytes, off) {
  9826. var res = (bytes[0 + off] << 24) |
  9827. (bytes[1 + off] << 16) |
  9828. (bytes[2 + off] << 8) |
  9829. bytes[3 + off];
  9830. return res >>> 0;
  9831. };
  9832. exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) {
  9833. bytes[0 + off] = value >>> 24;
  9834. bytes[1 + off] = (value >>> 16) & 0xff;
  9835. bytes[2 + off] = (value >>> 8) & 0xff;
  9836. bytes[3 + off] = value & 0xff;
  9837. };
  9838. exports.ip = function ip(inL, inR, out, off) {
  9839. var outL = 0;
  9840. var outR = 0;
  9841. for (var i = 6; i >= 0; i -= 2) {
  9842. for (var j = 0; j <= 24; j += 8) {
  9843. outL <<= 1;
  9844. outL |= (inR >>> (j + i)) & 1;
  9845. }
  9846. for (var j = 0; j <= 24; j += 8) {
  9847. outL <<= 1;
  9848. outL |= (inL >>> (j + i)) & 1;
  9849. }
  9850. }
  9851. for (var i = 6; i >= 0; i -= 2) {
  9852. for (var j = 1; j <= 25; j += 8) {
  9853. outR <<= 1;
  9854. outR |= (inR >>> (j + i)) & 1;
  9855. }
  9856. for (var j = 1; j <= 25; j += 8) {
  9857. outR <<= 1;
  9858. outR |= (inL >>> (j + i)) & 1;
  9859. }
  9860. }
  9861. out[off + 0] = outL >>> 0;
  9862. out[off + 1] = outR >>> 0;
  9863. };
  9864. exports.rip = function rip(inL, inR, out, off) {
  9865. var outL = 0;
  9866. var outR = 0;
  9867. for (var i = 0; i < 4; i++) {
  9868. for (var j = 24; j >= 0; j -= 8) {
  9869. outL <<= 1;
  9870. outL |= (inR >>> (j + i)) & 1;
  9871. outL <<= 1;
  9872. outL |= (inL >>> (j + i)) & 1;
  9873. }
  9874. }
  9875. for (var i = 4; i < 8; i++) {
  9876. for (var j = 24; j >= 0; j -= 8) {
  9877. outR <<= 1;
  9878. outR |= (inR >>> (j + i)) & 1;
  9879. outR <<= 1;
  9880. outR |= (inL >>> (j + i)) & 1;
  9881. }
  9882. }
  9883. out[off + 0] = outL >>> 0;
  9884. out[off + 1] = outR >>> 0;
  9885. };
  9886. exports.pc1 = function pc1(inL, inR, out, off) {
  9887. var outL = 0;
  9888. var outR = 0;
  9889. // 7, 15, 23, 31, 39, 47, 55, 63
  9890. // 6, 14, 22, 30, 39, 47, 55, 63
  9891. // 5, 13, 21, 29, 39, 47, 55, 63
  9892. // 4, 12, 20, 28
  9893. for (var i = 7; i >= 5; i--) {
  9894. for (var j = 0; j <= 24; j += 8) {
  9895. outL <<= 1;
  9896. outL |= (inR >> (j + i)) & 1;
  9897. }
  9898. for (var j = 0; j <= 24; j += 8) {
  9899. outL <<= 1;
  9900. outL |= (inL >> (j + i)) & 1;
  9901. }
  9902. }
  9903. for (var j = 0; j <= 24; j += 8) {
  9904. outL <<= 1;
  9905. outL |= (inR >> (j + i)) & 1;
  9906. }
  9907. // 1, 9, 17, 25, 33, 41, 49, 57
  9908. // 2, 10, 18, 26, 34, 42, 50, 58
  9909. // 3, 11, 19, 27, 35, 43, 51, 59
  9910. // 36, 44, 52, 60
  9911. for (var i = 1; i <= 3; i++) {
  9912. for (var j = 0; j <= 24; j += 8) {
  9913. outR <<= 1;
  9914. outR |= (inR >> (j + i)) & 1;
  9915. }
  9916. for (var j = 0; j <= 24; j += 8) {
  9917. outR <<= 1;
  9918. outR |= (inL >> (j + i)) & 1;
  9919. }
  9920. }
  9921. for (var j = 0; j <= 24; j += 8) {
  9922. outR <<= 1;
  9923. outR |= (inL >> (j + i)) & 1;
  9924. }
  9925. out[off + 0] = outL >>> 0;
  9926. out[off + 1] = outR >>> 0;
  9927. };
  9928. exports.r28shl = function r28shl(num, shift) {
  9929. return ((num << shift) & 0xfffffff) | (num >>> (28 - shift));
  9930. };
  9931. var pc2table = [
  9932. // inL => outL
  9933. 14, 11, 17, 4, 27, 23, 25, 0,
  9934. 13, 22, 7, 18, 5, 9, 16, 24,
  9935. 2, 20, 12, 21, 1, 8, 15, 26,
  9936. // inR => outR
  9937. 15, 4, 25, 19, 9, 1, 26, 16,
  9938. 5, 11, 23, 8, 12, 7, 17, 0,
  9939. 22, 3, 10, 14, 6, 20, 27, 24
  9940. ];
  9941. exports.pc2 = function pc2(inL, inR, out, off) {
  9942. var outL = 0;
  9943. var outR = 0;
  9944. var len = pc2table.length >>> 1;
  9945. for (var i = 0; i < len; i++) {
  9946. outL <<= 1;
  9947. outL |= (inL >>> pc2table[i]) & 0x1;
  9948. }
  9949. for (var i = len; i < pc2table.length; i++) {
  9950. outR <<= 1;
  9951. outR |= (inR >>> pc2table[i]) & 0x1;
  9952. }
  9953. out[off + 0] = outL >>> 0;
  9954. out[off + 1] = outR >>> 0;
  9955. };
  9956. exports.expand = function expand(r, out, off) {
  9957. var outL = 0;
  9958. var outR = 0;
  9959. outL = ((r & 1) << 5) | (r >>> 27);
  9960. for (var i = 23; i >= 15; i -= 4) {
  9961. outL <<= 6;
  9962. outL |= (r >>> i) & 0x3f;
  9963. }
  9964. for (var i = 11; i >= 3; i -= 4) {
  9965. outR |= (r >>> i) & 0x3f;
  9966. outR <<= 6;
  9967. }
  9968. outR |= ((r & 0x1f) << 1) | (r >>> 31);
  9969. out[off + 0] = outL >>> 0;
  9970. out[off + 1] = outR >>> 0;
  9971. };
  9972. var sTable = [
  9973. 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1,
  9974. 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8,
  9975. 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7,
  9976. 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13,
  9977. 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14,
  9978. 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5,
  9979. 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2,
  9980. 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9,
  9981. 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10,
  9982. 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1,
  9983. 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7,
  9984. 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12,
  9985. 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3,
  9986. 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9,
  9987. 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8,
  9988. 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14,
  9989. 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1,
  9990. 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6,
  9991. 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13,
  9992. 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3,
  9993. 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5,
  9994. 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8,
  9995. 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10,
  9996. 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13,
  9997. 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10,
  9998. 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6,
  9999. 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7,
  10000. 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12,
  10001. 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4,
  10002. 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2,
  10003. 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13,
  10004. 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11
  10005. ];
  10006. exports.substitute = function substitute(inL, inR) {
  10007. var out = 0;
  10008. for (var i = 0; i < 4; i++) {
  10009. var b = (inL >>> (18 - i * 6)) & 0x3f;
  10010. var sb = sTable[i * 0x40 + b];
  10011. out <<= 4;
  10012. out |= sb;
  10013. }
  10014. for (var i = 0; i < 4; i++) {
  10015. var b = (inR >>> (18 - i * 6)) & 0x3f;
  10016. var sb = sTable[4 * 0x40 + i * 0x40 + b];
  10017. out <<= 4;
  10018. out |= sb;
  10019. }
  10020. return out >>> 0;
  10021. };
  10022. var permuteTable = [
  10023. 16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22,
  10024. 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7
  10025. ];
  10026. exports.permute = function permute(num) {
  10027. var out = 0;
  10028. for (var i = 0; i < permuteTable.length; i++) {
  10029. out <<= 1;
  10030. out |= (num >>> permuteTable[i]) & 0x1;
  10031. }
  10032. return out >>> 0;
  10033. };
  10034. exports.padSplit = function padSplit(num, size, group) {
  10035. var str = num.toString(2);
  10036. while (str.length < size)
  10037. str = '0' + str;
  10038. var out = [];
  10039. for (var i = 0; i < size; i += group)
  10040. out.push(str.slice(i, i + group));
  10041. return out.join(' ');
  10042. };
  10043. },{}],66:[function(require,module,exports){
  10044. (function (Buffer){
  10045. var generatePrime = require('./lib/generatePrime')
  10046. var primes = require('./lib/primes.json')
  10047. var DH = require('./lib/dh')
  10048. function getDiffieHellman (mod) {
  10049. var prime = new Buffer(primes[mod].prime, 'hex')
  10050. var gen = new Buffer(primes[mod].gen, 'hex')
  10051. return new DH(prime, gen)
  10052. }
  10053. var ENCODINGS = {
  10054. 'binary': true, 'hex': true, 'base64': true
  10055. }
  10056. function createDiffieHellman (prime, enc, generator, genc) {
  10057. if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) {
  10058. return createDiffieHellman(prime, 'binary', enc, generator)
  10059. }
  10060. enc = enc || 'binary'
  10061. genc = genc || 'binary'
  10062. generator = generator || new Buffer([2])
  10063. if (!Buffer.isBuffer(generator)) {
  10064. generator = new Buffer(generator, genc)
  10065. }
  10066. if (typeof prime === 'number') {
  10067. return new DH(generatePrime(prime, generator), generator, true)
  10068. }
  10069. if (!Buffer.isBuffer(prime)) {
  10070. prime = new Buffer(prime, enc)
  10071. }
  10072. return new DH(prime, generator, true)
  10073. }
  10074. exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman
  10075. exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman
  10076. }).call(this,require("buffer").Buffer)
  10077. },{"./lib/dh":67,"./lib/generatePrime":68,"./lib/primes.json":69,"buffer":50}],67:[function(require,module,exports){
  10078. (function (Buffer){
  10079. var BN = require('bn.js');
  10080. var MillerRabin = require('miller-rabin');
  10081. var millerRabin = new MillerRabin();
  10082. var TWENTYFOUR = new BN(24);
  10083. var ELEVEN = new BN(11);
  10084. var TEN = new BN(10);
  10085. var THREE = new BN(3);
  10086. var SEVEN = new BN(7);
  10087. var primes = require('./generatePrime');
  10088. var randomBytes = require('randombytes');
  10089. module.exports = DH;
  10090. function setPublicKey(pub, enc) {
  10091. enc = enc || 'utf8';
  10092. if (!Buffer.isBuffer(pub)) {
  10093. pub = new Buffer(pub, enc);
  10094. }
  10095. this._pub = new BN(pub);
  10096. return this;
  10097. }
  10098. function setPrivateKey(priv, enc) {
  10099. enc = enc || 'utf8';
  10100. if (!Buffer.isBuffer(priv)) {
  10101. priv = new Buffer(priv, enc);
  10102. }
  10103. this._priv = new BN(priv);
  10104. return this;
  10105. }
  10106. var primeCache = {};
  10107. function checkPrime(prime, generator) {
  10108. var gen = generator.toString('hex');
  10109. var hex = [gen, prime.toString(16)].join('_');
  10110. if (hex in primeCache) {
  10111. return primeCache[hex];
  10112. }
  10113. var error = 0;
  10114. if (prime.isEven() ||
  10115. !primes.simpleSieve ||
  10116. !primes.fermatTest(prime) ||
  10117. !millerRabin.test(prime)) {
  10118. //not a prime so +1
  10119. error += 1;
  10120. if (gen === '02' || gen === '05') {
  10121. // we'd be able to check the generator
  10122. // it would fail so +8
  10123. error += 8;
  10124. } else {
  10125. //we wouldn't be able to test the generator
  10126. // so +4
  10127. error += 4;
  10128. }
  10129. primeCache[hex] = error;
  10130. return error;
  10131. }
  10132. if (!millerRabin.test(prime.shrn(1))) {
  10133. //not a safe prime
  10134. error += 2;
  10135. }
  10136. var rem;
  10137. switch (gen) {
  10138. case '02':
  10139. if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) {
  10140. // unsuidable generator
  10141. error += 8;
  10142. }
  10143. break;
  10144. case '05':
  10145. rem = prime.mod(TEN);
  10146. if (rem.cmp(THREE) && rem.cmp(SEVEN)) {
  10147. // prime mod 10 needs to equal 3 or 7
  10148. error += 8;
  10149. }
  10150. break;
  10151. default:
  10152. error += 4;
  10153. }
  10154. primeCache[hex] = error;
  10155. return error;
  10156. }
  10157. function DH(prime, generator, malleable) {
  10158. this.setGenerator(generator);
  10159. this.__prime = new BN(prime);
  10160. this._prime = BN.mont(this.__prime);
  10161. this._primeLen = prime.length;
  10162. this._pub = undefined;
  10163. this._priv = undefined;
  10164. this._primeCode = undefined;
  10165. if (malleable) {
  10166. this.setPublicKey = setPublicKey;
  10167. this.setPrivateKey = setPrivateKey;
  10168. } else {
  10169. this._primeCode = 8;
  10170. }
  10171. }
  10172. Object.defineProperty(DH.prototype, 'verifyError', {
  10173. enumerable: true,
  10174. get: function () {
  10175. if (typeof this._primeCode !== 'number') {
  10176. this._primeCode = checkPrime(this.__prime, this.__gen);
  10177. }
  10178. return this._primeCode;
  10179. }
  10180. });
  10181. DH.prototype.generateKeys = function () {
  10182. if (!this._priv) {
  10183. this._priv = new BN(randomBytes(this._primeLen));
  10184. }
  10185. this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed();
  10186. return this.getPublicKey();
  10187. };
  10188. DH.prototype.computeSecret = function (other) {
  10189. other = new BN(other);
  10190. other = other.toRed(this._prime);
  10191. var secret = other.redPow(this._priv).fromRed();
  10192. var out = new Buffer(secret.toArray());
  10193. var prime = this.getPrime();
  10194. if (out.length < prime.length) {
  10195. var front = new Buffer(prime.length - out.length);
  10196. front.fill(0);
  10197. out = Buffer.concat([front, out]);
  10198. }
  10199. return out;
  10200. };
  10201. DH.prototype.getPublicKey = function getPublicKey(enc) {
  10202. return formatReturnValue(this._pub, enc);
  10203. };
  10204. DH.prototype.getPrivateKey = function getPrivateKey(enc) {
  10205. return formatReturnValue(this._priv, enc);
  10206. };
  10207. DH.prototype.getPrime = function (enc) {
  10208. return formatReturnValue(this.__prime, enc);
  10209. };
  10210. DH.prototype.getGenerator = function (enc) {
  10211. return formatReturnValue(this._gen, enc);
  10212. };
  10213. DH.prototype.setGenerator = function (gen, enc) {
  10214. enc = enc || 'utf8';
  10215. if (!Buffer.isBuffer(gen)) {
  10216. gen = new Buffer(gen, enc);
  10217. }
  10218. this.__gen = gen;
  10219. this._gen = new BN(gen);
  10220. return this;
  10221. };
  10222. function formatReturnValue(bn, enc) {
  10223. var buf = new Buffer(bn.toArray());
  10224. if (!enc) {
  10225. return buf;
  10226. } else {
  10227. return buf.toString(enc);
  10228. }
  10229. }
  10230. }).call(this,require("buffer").Buffer)
  10231. },{"./generatePrime":68,"bn.js":17,"buffer":50,"miller-rabin":109,"randombytes":141}],68:[function(require,module,exports){
  10232. var randomBytes = require('randombytes');
  10233. module.exports = findPrime;
  10234. findPrime.simpleSieve = simpleSieve;
  10235. findPrime.fermatTest = fermatTest;
  10236. var BN = require('bn.js');
  10237. var TWENTYFOUR = new BN(24);
  10238. var MillerRabin = require('miller-rabin');
  10239. var millerRabin = new MillerRabin();
  10240. var ONE = new BN(1);
  10241. var TWO = new BN(2);
  10242. var FIVE = new BN(5);
  10243. var SIXTEEN = new BN(16);
  10244. var EIGHT = new BN(8);
  10245. var TEN = new BN(10);
  10246. var THREE = new BN(3);
  10247. var SEVEN = new BN(7);
  10248. var ELEVEN = new BN(11);
  10249. var FOUR = new BN(4);
  10250. var TWELVE = new BN(12);
  10251. var primes = null;
  10252. function _getPrimes() {
  10253. if (primes !== null)
  10254. return primes;
  10255. var limit = 0x100000;
  10256. var res = [];
  10257. res[0] = 2;
  10258. for (var i = 1, k = 3; k < limit; k += 2) {
  10259. var sqrt = Math.ceil(Math.sqrt(k));
  10260. for (var j = 0; j < i && res[j] <= sqrt; j++)
  10261. if (k % res[j] === 0)
  10262. break;
  10263. if (i !== j && res[j] <= sqrt)
  10264. continue;
  10265. res[i++] = k;
  10266. }
  10267. primes = res;
  10268. return res;
  10269. }
  10270. function simpleSieve(p) {
  10271. var primes = _getPrimes();
  10272. for (var i = 0; i < primes.length; i++)
  10273. if (p.modn(primes[i]) === 0) {
  10274. if (p.cmpn(primes[i]) === 0) {
  10275. return true;
  10276. } else {
  10277. return false;
  10278. }
  10279. }
  10280. return true;
  10281. }
  10282. function fermatTest(p) {
  10283. var red = BN.mont(p);
  10284. return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0;
  10285. }
  10286. function findPrime(bits, gen) {
  10287. if (bits < 16) {
  10288. // this is what openssl does
  10289. if (gen === 2 || gen === 5) {
  10290. return new BN([0x8c, 0x7b]);
  10291. } else {
  10292. return new BN([0x8c, 0x27]);
  10293. }
  10294. }
  10295. gen = new BN(gen);
  10296. var num, n2;
  10297. while (true) {
  10298. num = new BN(randomBytes(Math.ceil(bits / 8)));
  10299. while (num.bitLength() > bits) {
  10300. num.ishrn(1);
  10301. }
  10302. if (num.isEven()) {
  10303. num.iadd(ONE);
  10304. }
  10305. if (!num.testn(1)) {
  10306. num.iadd(TWO);
  10307. }
  10308. if (!gen.cmp(TWO)) {
  10309. while (num.mod(TWENTYFOUR).cmp(ELEVEN)) {
  10310. num.iadd(FOUR);
  10311. }
  10312. } else if (!gen.cmp(FIVE)) {
  10313. while (num.mod(TEN).cmp(THREE)) {
  10314. num.iadd(FOUR);
  10315. }
  10316. }
  10317. n2 = num.shrn(1);
  10318. if (simpleSieve(n2) && simpleSieve(num) &&
  10319. fermatTest(n2) && fermatTest(num) &&
  10320. millerRabin.test(n2) && millerRabin.test(num)) {
  10321. return num;
  10322. }
  10323. }
  10324. }
  10325. },{"bn.js":17,"miller-rabin":109,"randombytes":141}],69:[function(require,module,exports){
  10326. module.exports={
  10327. "modp1": {
  10328. "gen": "02",
  10329. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"
  10330. },
  10331. "modp2": {
  10332. "gen": "02",
  10333. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"
  10334. },
  10335. "modp5": {
  10336. "gen": "02",
  10337. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"
  10338. },
  10339. "modp14": {
  10340. "gen": "02",
  10341. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"
  10342. },
  10343. "modp15": {
  10344. "gen": "02",
  10345. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"
  10346. },
  10347. "modp16": {
  10348. "gen": "02",
  10349. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"
  10350. },
  10351. "modp17": {
  10352. "gen": "02",
  10353. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"
  10354. },
  10355. "modp18": {
  10356. "gen": "02",
  10357. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"
  10358. }
  10359. }
  10360. },{}],70:[function(require,module,exports){
  10361. 'use strict';
  10362. var elliptic = exports;
  10363. elliptic.version = require('../package.json').version;
  10364. elliptic.utils = require('./elliptic/utils');
  10365. elliptic.rand = require('brorand');
  10366. elliptic.curve = require('./elliptic/curve');
  10367. elliptic.curves = require('./elliptic/curves');
  10368. // Protocols
  10369. elliptic.ec = require('./elliptic/ec');
  10370. elliptic.eddsa = require('./elliptic/eddsa');
  10371. },{"../package.json":85,"./elliptic/curve":73,"./elliptic/curves":76,"./elliptic/ec":77,"./elliptic/eddsa":80,"./elliptic/utils":84,"brorand":18}],71:[function(require,module,exports){
  10372. 'use strict';
  10373. var BN = require('bn.js');
  10374. var elliptic = require('../../elliptic');
  10375. var utils = elliptic.utils;
  10376. var getNAF = utils.getNAF;
  10377. var getJSF = utils.getJSF;
  10378. var assert = utils.assert;
  10379. function BaseCurve(type, conf) {
  10380. this.type = type;
  10381. this.p = new BN(conf.p, 16);
  10382. // Use Montgomery, when there is no fast reduction for the prime
  10383. this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);
  10384. // Useful for many curves
  10385. this.zero = new BN(0).toRed(this.red);
  10386. this.one = new BN(1).toRed(this.red);
  10387. this.two = new BN(2).toRed(this.red);
  10388. // Curve configuration, optional
  10389. this.n = conf.n && new BN(conf.n, 16);
  10390. this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
  10391. // Temporary arrays
  10392. this._wnafT1 = new Array(4);
  10393. this._wnafT2 = new Array(4);
  10394. this._wnafT3 = new Array(4);
  10395. this._wnafT4 = new Array(4);
  10396. // Generalized Greg Maxwell's trick
  10397. var adjustCount = this.n && this.p.div(this.n);
  10398. if (!adjustCount || adjustCount.cmpn(100) > 0) {
  10399. this.redN = null;
  10400. } else {
  10401. this._maxwellTrick = true;
  10402. this.redN = this.n.toRed(this.red);
  10403. }
  10404. }
  10405. module.exports = BaseCurve;
  10406. BaseCurve.prototype.point = function point() {
  10407. throw new Error('Not implemented');
  10408. };
  10409. BaseCurve.prototype.validate = function validate() {
  10410. throw new Error('Not implemented');
  10411. };
  10412. BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
  10413. assert(p.precomputed);
  10414. var doubles = p._getDoubles();
  10415. var naf = getNAF(k, 1);
  10416. var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
  10417. I /= 3;
  10418. // Translate into more windowed form
  10419. var repr = [];
  10420. for (var j = 0; j < naf.length; j += doubles.step) {
  10421. var nafW = 0;
  10422. for (var k = j + doubles.step - 1; k >= j; k--)
  10423. nafW = (nafW << 1) + naf[k];
  10424. repr.push(nafW);
  10425. }
  10426. var a = this.jpoint(null, null, null);
  10427. var b = this.jpoint(null, null, null);
  10428. for (var i = I; i > 0; i--) {
  10429. for (var j = 0; j < repr.length; j++) {
  10430. var nafW = repr[j];
  10431. if (nafW === i)
  10432. b = b.mixedAdd(doubles.points[j]);
  10433. else if (nafW === -i)
  10434. b = b.mixedAdd(doubles.points[j].neg());
  10435. }
  10436. a = a.add(b);
  10437. }
  10438. return a.toP();
  10439. };
  10440. BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
  10441. var w = 4;
  10442. // Precompute window
  10443. var nafPoints = p._getNAFPoints(w);
  10444. w = nafPoints.wnd;
  10445. var wnd = nafPoints.points;
  10446. // Get NAF form
  10447. var naf = getNAF(k, w);
  10448. // Add `this`*(N+1) for every w-NAF index
  10449. var acc = this.jpoint(null, null, null);
  10450. for (var i = naf.length - 1; i >= 0; i--) {
  10451. // Count zeroes
  10452. for (var k = 0; i >= 0 && naf[i] === 0; i--)
  10453. k++;
  10454. if (i >= 0)
  10455. k++;
  10456. acc = acc.dblp(k);
  10457. if (i < 0)
  10458. break;
  10459. var z = naf[i];
  10460. assert(z !== 0);
  10461. if (p.type === 'affine') {
  10462. // J +- P
  10463. if (z > 0)
  10464. acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
  10465. else
  10466. acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
  10467. } else {
  10468. // J +- J
  10469. if (z > 0)
  10470. acc = acc.add(wnd[(z - 1) >> 1]);
  10471. else
  10472. acc = acc.add(wnd[(-z - 1) >> 1].neg());
  10473. }
  10474. }
  10475. return p.type === 'affine' ? acc.toP() : acc;
  10476. };
  10477. BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
  10478. points,
  10479. coeffs,
  10480. len,
  10481. jacobianResult) {
  10482. var wndWidth = this._wnafT1;
  10483. var wnd = this._wnafT2;
  10484. var naf = this._wnafT3;
  10485. // Fill all arrays
  10486. var max = 0;
  10487. for (var i = 0; i < len; i++) {
  10488. var p = points[i];
  10489. var nafPoints = p._getNAFPoints(defW);
  10490. wndWidth[i] = nafPoints.wnd;
  10491. wnd[i] = nafPoints.points;
  10492. }
  10493. // Comb small window NAFs
  10494. for (var i = len - 1; i >= 1; i -= 2) {
  10495. var a = i - 1;
  10496. var b = i;
  10497. if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
  10498. naf[a] = getNAF(coeffs[a], wndWidth[a]);
  10499. naf[b] = getNAF(coeffs[b], wndWidth[b]);
  10500. max = Math.max(naf[a].length, max);
  10501. max = Math.max(naf[b].length, max);
  10502. continue;
  10503. }
  10504. var comb = [
  10505. points[a], /* 1 */
  10506. null, /* 3 */
  10507. null, /* 5 */
  10508. points[b] /* 7 */
  10509. ];
  10510. // Try to avoid Projective points, if possible
  10511. if (points[a].y.cmp(points[b].y) === 0) {
  10512. comb[1] = points[a].add(points[b]);
  10513. comb[2] = points[a].toJ().mixedAdd(points[b].neg());
  10514. } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
  10515. comb[1] = points[a].toJ().mixedAdd(points[b]);
  10516. comb[2] = points[a].add(points[b].neg());
  10517. } else {
  10518. comb[1] = points[a].toJ().mixedAdd(points[b]);
  10519. comb[2] = points[a].toJ().mixedAdd(points[b].neg());
  10520. }
  10521. var index = [
  10522. -3, /* -1 -1 */
  10523. -1, /* -1 0 */
  10524. -5, /* -1 1 */
  10525. -7, /* 0 -1 */
  10526. 0, /* 0 0 */
  10527. 7, /* 0 1 */
  10528. 5, /* 1 -1 */
  10529. 1, /* 1 0 */
  10530. 3 /* 1 1 */
  10531. ];
  10532. var jsf = getJSF(coeffs[a], coeffs[b]);
  10533. max = Math.max(jsf[0].length, max);
  10534. naf[a] = new Array(max);
  10535. naf[b] = new Array(max);
  10536. for (var j = 0; j < max; j++) {
  10537. var ja = jsf[0][j] | 0;
  10538. var jb = jsf[1][j] | 0;
  10539. naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
  10540. naf[b][j] = 0;
  10541. wnd[a] = comb;
  10542. }
  10543. }
  10544. var acc = this.jpoint(null, null, null);
  10545. var tmp = this._wnafT4;
  10546. for (var i = max; i >= 0; i--) {
  10547. var k = 0;
  10548. while (i >= 0) {
  10549. var zero = true;
  10550. for (var j = 0; j < len; j++) {
  10551. tmp[j] = naf[j][i] | 0;
  10552. if (tmp[j] !== 0)
  10553. zero = false;
  10554. }
  10555. if (!zero)
  10556. break;
  10557. k++;
  10558. i--;
  10559. }
  10560. if (i >= 0)
  10561. k++;
  10562. acc = acc.dblp(k);
  10563. if (i < 0)
  10564. break;
  10565. for (var j = 0; j < len; j++) {
  10566. var z = tmp[j];
  10567. var p;
  10568. if (z === 0)
  10569. continue;
  10570. else if (z > 0)
  10571. p = wnd[j][(z - 1) >> 1];
  10572. else if (z < 0)
  10573. p = wnd[j][(-z - 1) >> 1].neg();
  10574. if (p.type === 'affine')
  10575. acc = acc.mixedAdd(p);
  10576. else
  10577. acc = acc.add(p);
  10578. }
  10579. }
  10580. // Zeroify references
  10581. for (var i = 0; i < len; i++)
  10582. wnd[i] = null;
  10583. if (jacobianResult)
  10584. return acc;
  10585. else
  10586. return acc.toP();
  10587. };
  10588. function BasePoint(curve, type) {
  10589. this.curve = curve;
  10590. this.type = type;
  10591. this.precomputed = null;
  10592. }
  10593. BaseCurve.BasePoint = BasePoint;
  10594. BasePoint.prototype.eq = function eq(/*other*/) {
  10595. throw new Error('Not implemented');
  10596. };
  10597. BasePoint.prototype.validate = function validate() {
  10598. return this.curve.validate(this);
  10599. };
  10600. BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
  10601. bytes = utils.toArray(bytes, enc);
  10602. var len = this.p.byteLength();
  10603. // uncompressed, hybrid-odd, hybrid-even
  10604. if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
  10605. bytes.length - 1 === 2 * len) {
  10606. if (bytes[0] === 0x06)
  10607. assert(bytes[bytes.length - 1] % 2 === 0);
  10608. else if (bytes[0] === 0x07)
  10609. assert(bytes[bytes.length - 1] % 2 === 1);
  10610. var res = this.point(bytes.slice(1, 1 + len),
  10611. bytes.slice(1 + len, 1 + 2 * len));
  10612. return res;
  10613. } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
  10614. bytes.length - 1 === len) {
  10615. return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
  10616. }
  10617. throw new Error('Unknown point format');
  10618. };
  10619. BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
  10620. return this.encode(enc, true);
  10621. };
  10622. BasePoint.prototype._encode = function _encode(compact) {
  10623. var len = this.curve.p.byteLength();
  10624. var x = this.getX().toArray('be', len);
  10625. if (compact)
  10626. return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);
  10627. return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;
  10628. };
  10629. BasePoint.prototype.encode = function encode(enc, compact) {
  10630. return utils.encode(this._encode(compact), enc);
  10631. };
  10632. BasePoint.prototype.precompute = function precompute(power) {
  10633. if (this.precomputed)
  10634. return this;
  10635. var precomputed = {
  10636. doubles: null,
  10637. naf: null,
  10638. beta: null
  10639. };
  10640. precomputed.naf = this._getNAFPoints(8);
  10641. precomputed.doubles = this._getDoubles(4, power);
  10642. precomputed.beta = this._getBeta();
  10643. this.precomputed = precomputed;
  10644. return this;
  10645. };
  10646. BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
  10647. if (!this.precomputed)
  10648. return false;
  10649. var doubles = this.precomputed.doubles;
  10650. if (!doubles)
  10651. return false;
  10652. return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
  10653. };
  10654. BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
  10655. if (this.precomputed && this.precomputed.doubles)
  10656. return this.precomputed.doubles;
  10657. var doubles = [ this ];
  10658. var acc = this;
  10659. for (var i = 0; i < power; i += step) {
  10660. for (var j = 0; j < step; j++)
  10661. acc = acc.dbl();
  10662. doubles.push(acc);
  10663. }
  10664. return {
  10665. step: step,
  10666. points: doubles
  10667. };
  10668. };
  10669. BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
  10670. if (this.precomputed && this.precomputed.naf)
  10671. return this.precomputed.naf;
  10672. var res = [ this ];
  10673. var max = (1 << wnd) - 1;
  10674. var dbl = max === 1 ? null : this.dbl();
  10675. for (var i = 1; i < max; i++)
  10676. res[i] = res[i - 1].add(dbl);
  10677. return {
  10678. wnd: wnd,
  10679. points: res
  10680. };
  10681. };
  10682. BasePoint.prototype._getBeta = function _getBeta() {
  10683. return null;
  10684. };
  10685. BasePoint.prototype.dblp = function dblp(k) {
  10686. var r = this;
  10687. for (var i = 0; i < k; i++)
  10688. r = r.dbl();
  10689. return r;
  10690. };
  10691. },{"../../elliptic":70,"bn.js":17}],72:[function(require,module,exports){
  10692. 'use strict';
  10693. var curve = require('../curve');
  10694. var elliptic = require('../../elliptic');
  10695. var BN = require('bn.js');
  10696. var inherits = require('inherits');
  10697. var Base = curve.base;
  10698. var assert = elliptic.utils.assert;
  10699. function EdwardsCurve(conf) {
  10700. // NOTE: Important as we are creating point in Base.call()
  10701. this.twisted = (conf.a | 0) !== 1;
  10702. this.mOneA = this.twisted && (conf.a | 0) === -1;
  10703. this.extended = this.mOneA;
  10704. Base.call(this, 'edwards', conf);
  10705. this.a = new BN(conf.a, 16).umod(this.red.m);
  10706. this.a = this.a.toRed(this.red);
  10707. this.c = new BN(conf.c, 16).toRed(this.red);
  10708. this.c2 = this.c.redSqr();
  10709. this.d = new BN(conf.d, 16).toRed(this.red);
  10710. this.dd = this.d.redAdd(this.d);
  10711. assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);
  10712. this.oneC = (conf.c | 0) === 1;
  10713. }
  10714. inherits(EdwardsCurve, Base);
  10715. module.exports = EdwardsCurve;
  10716. EdwardsCurve.prototype._mulA = function _mulA(num) {
  10717. if (this.mOneA)
  10718. return num.redNeg();
  10719. else
  10720. return this.a.redMul(num);
  10721. };
  10722. EdwardsCurve.prototype._mulC = function _mulC(num) {
  10723. if (this.oneC)
  10724. return num;
  10725. else
  10726. return this.c.redMul(num);
  10727. };
  10728. // Just for compatibility with Short curve
  10729. EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
  10730. return this.point(x, y, z, t);
  10731. };
  10732. EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {
  10733. x = new BN(x, 16);
  10734. if (!x.red)
  10735. x = x.toRed(this.red);
  10736. var x2 = x.redSqr();
  10737. var rhs = this.c2.redSub(this.a.redMul(x2));
  10738. var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));
  10739. var y2 = rhs.redMul(lhs.redInvm());
  10740. var y = y2.redSqrt();
  10741. if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
  10742. throw new Error('invalid point');
  10743. var isOdd = y.fromRed().isOdd();
  10744. if (odd && !isOdd || !odd && isOdd)
  10745. y = y.redNeg();
  10746. return this.point(x, y);
  10747. };
  10748. EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {
  10749. y = new BN(y, 16);
  10750. if (!y.red)
  10751. y = y.toRed(this.red);
  10752. // x^2 = (y^2 - 1) / (d y^2 + 1)
  10753. var y2 = y.redSqr();
  10754. var lhs = y2.redSub(this.one);
  10755. var rhs = y2.redMul(this.d).redAdd(this.one);
  10756. var x2 = lhs.redMul(rhs.redInvm());
  10757. if (x2.cmp(this.zero) === 0) {
  10758. if (odd)
  10759. throw new Error('invalid point');
  10760. else
  10761. return this.point(this.zero, y);
  10762. }
  10763. var x = x2.redSqrt();
  10764. if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)
  10765. throw new Error('invalid point');
  10766. if (x.isOdd() !== odd)
  10767. x = x.redNeg();
  10768. return this.point(x, y);
  10769. };
  10770. EdwardsCurve.prototype.validate = function validate(point) {
  10771. if (point.isInfinity())
  10772. return true;
  10773. // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
  10774. point.normalize();
  10775. var x2 = point.x.redSqr();
  10776. var y2 = point.y.redSqr();
  10777. var lhs = x2.redMul(this.a).redAdd(y2);
  10778. var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
  10779. return lhs.cmp(rhs) === 0;
  10780. };
  10781. function Point(curve, x, y, z, t) {
  10782. Base.BasePoint.call(this, curve, 'projective');
  10783. if (x === null && y === null && z === null) {
  10784. this.x = this.curve.zero;
  10785. this.y = this.curve.one;
  10786. this.z = this.curve.one;
  10787. this.t = this.curve.zero;
  10788. this.zOne = true;
  10789. } else {
  10790. this.x = new BN(x, 16);
  10791. this.y = new BN(y, 16);
  10792. this.z = z ? new BN(z, 16) : this.curve.one;
  10793. this.t = t && new BN(t, 16);
  10794. if (!this.x.red)
  10795. this.x = this.x.toRed(this.curve.red);
  10796. if (!this.y.red)
  10797. this.y = this.y.toRed(this.curve.red);
  10798. if (!this.z.red)
  10799. this.z = this.z.toRed(this.curve.red);
  10800. if (this.t && !this.t.red)
  10801. this.t = this.t.toRed(this.curve.red);
  10802. this.zOne = this.z === this.curve.one;
  10803. // Use extended coordinates
  10804. if (this.curve.extended && !this.t) {
  10805. this.t = this.x.redMul(this.y);
  10806. if (!this.zOne)
  10807. this.t = this.t.redMul(this.z.redInvm());
  10808. }
  10809. }
  10810. }
  10811. inherits(Point, Base.BasePoint);
  10812. EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
  10813. return Point.fromJSON(this, obj);
  10814. };
  10815. EdwardsCurve.prototype.point = function point(x, y, z, t) {
  10816. return new Point(this, x, y, z, t);
  10817. };
  10818. Point.fromJSON = function fromJSON(curve, obj) {
  10819. return new Point(curve, obj[0], obj[1], obj[2]);
  10820. };
  10821. Point.prototype.inspect = function inspect() {
  10822. if (this.isInfinity())
  10823. return '<EC Point Infinity>';
  10824. return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
  10825. ' y: ' + this.y.fromRed().toString(16, 2) +
  10826. ' z: ' + this.z.fromRed().toString(16, 2) + '>';
  10827. };
  10828. Point.prototype.isInfinity = function isInfinity() {
  10829. // XXX This code assumes that zero is always zero in red
  10830. return this.x.cmpn(0) === 0 &&
  10831. this.y.cmp(this.z) === 0;
  10832. };
  10833. Point.prototype._extDbl = function _extDbl() {
  10834. // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
  10835. // #doubling-dbl-2008-hwcd
  10836. // 4M + 4S
  10837. // A = X1^2
  10838. var a = this.x.redSqr();
  10839. // B = Y1^2
  10840. var b = this.y.redSqr();
  10841. // C = 2 * Z1^2
  10842. var c = this.z.redSqr();
  10843. c = c.redIAdd(c);
  10844. // D = a * A
  10845. var d = this.curve._mulA(a);
  10846. // E = (X1 + Y1)^2 - A - B
  10847. var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
  10848. // G = D + B
  10849. var g = d.redAdd(b);
  10850. // F = G - C
  10851. var f = g.redSub(c);
  10852. // H = D - B
  10853. var h = d.redSub(b);
  10854. // X3 = E * F
  10855. var nx = e.redMul(f);
  10856. // Y3 = G * H
  10857. var ny = g.redMul(h);
  10858. // T3 = E * H
  10859. var nt = e.redMul(h);
  10860. // Z3 = F * G
  10861. var nz = f.redMul(g);
  10862. return this.curve.point(nx, ny, nz, nt);
  10863. };
  10864. Point.prototype._projDbl = function _projDbl() {
  10865. // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
  10866. // #doubling-dbl-2008-bbjlp
  10867. // #doubling-dbl-2007-bl
  10868. // and others
  10869. // Generally 3M + 4S or 2M + 4S
  10870. // B = (X1 + Y1)^2
  10871. var b = this.x.redAdd(this.y).redSqr();
  10872. // C = X1^2
  10873. var c = this.x.redSqr();
  10874. // D = Y1^2
  10875. var d = this.y.redSqr();
  10876. var nx;
  10877. var ny;
  10878. var nz;
  10879. if (this.curve.twisted) {
  10880. // E = a * C
  10881. var e = this.curve._mulA(c);
  10882. // F = E + D
  10883. var f = e.redAdd(d);
  10884. if (this.zOne) {
  10885. // X3 = (B - C - D) * (F - 2)
  10886. nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
  10887. // Y3 = F * (E - D)
  10888. ny = f.redMul(e.redSub(d));
  10889. // Z3 = F^2 - 2 * F
  10890. nz = f.redSqr().redSub(f).redSub(f);
  10891. } else {
  10892. // H = Z1^2
  10893. var h = this.z.redSqr();
  10894. // J = F - 2 * H
  10895. var j = f.redSub(h).redISub(h);
  10896. // X3 = (B-C-D)*J
  10897. nx = b.redSub(c).redISub(d).redMul(j);
  10898. // Y3 = F * (E - D)
  10899. ny = f.redMul(e.redSub(d));
  10900. // Z3 = F * J
  10901. nz = f.redMul(j);
  10902. }
  10903. } else {
  10904. // E = C + D
  10905. var e = c.redAdd(d);
  10906. // H = (c * Z1)^2
  10907. var h = this.curve._mulC(this.c.redMul(this.z)).redSqr();
  10908. // J = E - 2 * H
  10909. var j = e.redSub(h).redSub(h);
  10910. // X3 = c * (B - E) * J
  10911. nx = this.curve._mulC(b.redISub(e)).redMul(j);
  10912. // Y3 = c * E * (C - D)
  10913. ny = this.curve._mulC(e).redMul(c.redISub(d));
  10914. // Z3 = E * J
  10915. nz = e.redMul(j);
  10916. }
  10917. return this.curve.point(nx, ny, nz);
  10918. };
  10919. Point.prototype.dbl = function dbl() {
  10920. if (this.isInfinity())
  10921. return this;
  10922. // Double in extended coordinates
  10923. if (this.curve.extended)
  10924. return this._extDbl();
  10925. else
  10926. return this._projDbl();
  10927. };
  10928. Point.prototype._extAdd = function _extAdd(p) {
  10929. // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
  10930. // #addition-add-2008-hwcd-3
  10931. // 8M
  10932. // A = (Y1 - X1) * (Y2 - X2)
  10933. var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
  10934. // B = (Y1 + X1) * (Y2 + X2)
  10935. var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
  10936. // C = T1 * k * T2
  10937. var c = this.t.redMul(this.curve.dd).redMul(p.t);
  10938. // D = Z1 * 2 * Z2
  10939. var d = this.z.redMul(p.z.redAdd(p.z));
  10940. // E = B - A
  10941. var e = b.redSub(a);
  10942. // F = D - C
  10943. var f = d.redSub(c);
  10944. // G = D + C
  10945. var g = d.redAdd(c);
  10946. // H = B + A
  10947. var h = b.redAdd(a);
  10948. // X3 = E * F
  10949. var nx = e.redMul(f);
  10950. // Y3 = G * H
  10951. var ny = g.redMul(h);
  10952. // T3 = E * H
  10953. var nt = e.redMul(h);
  10954. // Z3 = F * G
  10955. var nz = f.redMul(g);
  10956. return this.curve.point(nx, ny, nz, nt);
  10957. };
  10958. Point.prototype._projAdd = function _projAdd(p) {
  10959. // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
  10960. // #addition-add-2008-bbjlp
  10961. // #addition-add-2007-bl
  10962. // 10M + 1S
  10963. // A = Z1 * Z2
  10964. var a = this.z.redMul(p.z);
  10965. // B = A^2
  10966. var b = a.redSqr();
  10967. // C = X1 * X2
  10968. var c = this.x.redMul(p.x);
  10969. // D = Y1 * Y2
  10970. var d = this.y.redMul(p.y);
  10971. // E = d * C * D
  10972. var e = this.curve.d.redMul(c).redMul(d);
  10973. // F = B - E
  10974. var f = b.redSub(e);
  10975. // G = B + E
  10976. var g = b.redAdd(e);
  10977. // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
  10978. var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
  10979. var nx = a.redMul(f).redMul(tmp);
  10980. var ny;
  10981. var nz;
  10982. if (this.curve.twisted) {
  10983. // Y3 = A * G * (D - a * C)
  10984. ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
  10985. // Z3 = F * G
  10986. nz = f.redMul(g);
  10987. } else {
  10988. // Y3 = A * G * (D - C)
  10989. ny = a.redMul(g).redMul(d.redSub(c));
  10990. // Z3 = c * F * G
  10991. nz = this.curve._mulC(f).redMul(g);
  10992. }
  10993. return this.curve.point(nx, ny, nz);
  10994. };
  10995. Point.prototype.add = function add(p) {
  10996. if (this.isInfinity())
  10997. return p;
  10998. if (p.isInfinity())
  10999. return this;
  11000. if (this.curve.extended)
  11001. return this._extAdd(p);
  11002. else
  11003. return this._projAdd(p);
  11004. };
  11005. Point.prototype.mul = function mul(k) {
  11006. if (this._hasDoubles(k))
  11007. return this.curve._fixedNafMul(this, k);
  11008. else
  11009. return this.curve._wnafMul(this, k);
  11010. };
  11011. Point.prototype.mulAdd = function mulAdd(k1, p, k2) {
  11012. return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);
  11013. };
  11014. Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) {
  11015. return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);
  11016. };
  11017. Point.prototype.normalize = function normalize() {
  11018. if (this.zOne)
  11019. return this;
  11020. // Normalize coordinates
  11021. var zi = this.z.redInvm();
  11022. this.x = this.x.redMul(zi);
  11023. this.y = this.y.redMul(zi);
  11024. if (this.t)
  11025. this.t = this.t.redMul(zi);
  11026. this.z = this.curve.one;
  11027. this.zOne = true;
  11028. return this;
  11029. };
  11030. Point.prototype.neg = function neg() {
  11031. return this.curve.point(this.x.redNeg(),
  11032. this.y,
  11033. this.z,
  11034. this.t && this.t.redNeg());
  11035. };
  11036. Point.prototype.getX = function getX() {
  11037. this.normalize();
  11038. return this.x.fromRed();
  11039. };
  11040. Point.prototype.getY = function getY() {
  11041. this.normalize();
  11042. return this.y.fromRed();
  11043. };
  11044. Point.prototype.eq = function eq(other) {
  11045. return this === other ||
  11046. this.getX().cmp(other.getX()) === 0 &&
  11047. this.getY().cmp(other.getY()) === 0;
  11048. };
  11049. Point.prototype.eqXToP = function eqXToP(x) {
  11050. var rx = x.toRed(this.curve.red).redMul(this.z);
  11051. if (this.x.cmp(rx) === 0)
  11052. return true;
  11053. var xc = x.clone();
  11054. var t = this.curve.redN.redMul(this.z);
  11055. for (;;) {
  11056. xc.iadd(this.curve.n);
  11057. if (xc.cmp(this.curve.p) >= 0)
  11058. return false;
  11059. rx.redIAdd(t);
  11060. if (this.x.cmp(rx) === 0)
  11061. return true;
  11062. }
  11063. return false;
  11064. };
  11065. // Compatibility with BaseCurve
  11066. Point.prototype.toP = Point.prototype.normalize;
  11067. Point.prototype.mixedAdd = Point.prototype.add;
  11068. },{"../../elliptic":70,"../curve":73,"bn.js":17,"inherits":104}],73:[function(require,module,exports){
  11069. 'use strict';
  11070. var curve = exports;
  11071. curve.base = require('./base');
  11072. curve.short = require('./short');
  11073. curve.mont = require('./mont');
  11074. curve.edwards = require('./edwards');
  11075. },{"./base":71,"./edwards":72,"./mont":74,"./short":75}],74:[function(require,module,exports){
  11076. 'use strict';
  11077. var curve = require('../curve');
  11078. var BN = require('bn.js');
  11079. var inherits = require('inherits');
  11080. var Base = curve.base;
  11081. var elliptic = require('../../elliptic');
  11082. var utils = elliptic.utils;
  11083. function MontCurve(conf) {
  11084. Base.call(this, 'mont', conf);
  11085. this.a = new BN(conf.a, 16).toRed(this.red);
  11086. this.b = new BN(conf.b, 16).toRed(this.red);
  11087. this.i4 = new BN(4).toRed(this.red).redInvm();
  11088. this.two = new BN(2).toRed(this.red);
  11089. this.a24 = this.i4.redMul(this.a.redAdd(this.two));
  11090. }
  11091. inherits(MontCurve, Base);
  11092. module.exports = MontCurve;
  11093. MontCurve.prototype.validate = function validate(point) {
  11094. var x = point.normalize().x;
  11095. var x2 = x.redSqr();
  11096. var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
  11097. var y = rhs.redSqrt();
  11098. return y.redSqr().cmp(rhs) === 0;
  11099. };
  11100. function Point(curve, x, z) {
  11101. Base.BasePoint.call(this, curve, 'projective');
  11102. if (x === null && z === null) {
  11103. this.x = this.curve.one;
  11104. this.z = this.curve.zero;
  11105. } else {
  11106. this.x = new BN(x, 16);
  11107. this.z = new BN(z, 16);
  11108. if (!this.x.red)
  11109. this.x = this.x.toRed(this.curve.red);
  11110. if (!this.z.red)
  11111. this.z = this.z.toRed(this.curve.red);
  11112. }
  11113. }
  11114. inherits(Point, Base.BasePoint);
  11115. MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
  11116. return this.point(utils.toArray(bytes, enc), 1);
  11117. };
  11118. MontCurve.prototype.point = function point(x, z) {
  11119. return new Point(this, x, z);
  11120. };
  11121. MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
  11122. return Point.fromJSON(this, obj);
  11123. };
  11124. Point.prototype.precompute = function precompute() {
  11125. // No-op
  11126. };
  11127. Point.prototype._encode = function _encode() {
  11128. return this.getX().toArray('be', this.curve.p.byteLength());
  11129. };
  11130. Point.fromJSON = function fromJSON(curve, obj) {
  11131. return new Point(curve, obj[0], obj[1] || curve.one);
  11132. };
  11133. Point.prototype.inspect = function inspect() {
  11134. if (this.isInfinity())
  11135. return '<EC Point Infinity>';
  11136. return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
  11137. ' z: ' + this.z.fromRed().toString(16, 2) + '>';
  11138. };
  11139. Point.prototype.isInfinity = function isInfinity() {
  11140. // XXX This code assumes that zero is always zero in red
  11141. return this.z.cmpn(0) === 0;
  11142. };
  11143. Point.prototype.dbl = function dbl() {
  11144. // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
  11145. // 2M + 2S + 4A
  11146. // A = X1 + Z1
  11147. var a = this.x.redAdd(this.z);
  11148. // AA = A^2
  11149. var aa = a.redSqr();
  11150. // B = X1 - Z1
  11151. var b = this.x.redSub(this.z);
  11152. // BB = B^2
  11153. var bb = b.redSqr();
  11154. // C = AA - BB
  11155. var c = aa.redSub(bb);
  11156. // X3 = AA * BB
  11157. var nx = aa.redMul(bb);
  11158. // Z3 = C * (BB + A24 * C)
  11159. var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
  11160. return this.curve.point(nx, nz);
  11161. };
  11162. Point.prototype.add = function add() {
  11163. throw new Error('Not supported on Montgomery curve');
  11164. };
  11165. Point.prototype.diffAdd = function diffAdd(p, diff) {
  11166. // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
  11167. // 4M + 2S + 6A
  11168. // A = X2 + Z2
  11169. var a = this.x.redAdd(this.z);
  11170. // B = X2 - Z2
  11171. var b = this.x.redSub(this.z);
  11172. // C = X3 + Z3
  11173. var c = p.x.redAdd(p.z);
  11174. // D = X3 - Z3
  11175. var d = p.x.redSub(p.z);
  11176. // DA = D * A
  11177. var da = d.redMul(a);
  11178. // CB = C * B
  11179. var cb = c.redMul(b);
  11180. // X5 = Z1 * (DA + CB)^2
  11181. var nx = diff.z.redMul(da.redAdd(cb).redSqr());
  11182. // Z5 = X1 * (DA - CB)^2
  11183. var nz = diff.x.redMul(da.redISub(cb).redSqr());
  11184. return this.curve.point(nx, nz);
  11185. };
  11186. Point.prototype.mul = function mul(k) {
  11187. var t = k.clone();
  11188. var a = this; // (N / 2) * Q + Q
  11189. var b = this.curve.point(null, null); // (N / 2) * Q
  11190. var c = this; // Q
  11191. for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))
  11192. bits.push(t.andln(1));
  11193. for (var i = bits.length - 1; i >= 0; i--) {
  11194. if (bits[i] === 0) {
  11195. // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
  11196. a = a.diffAdd(b, c);
  11197. // N * Q = 2 * ((N / 2) * Q + Q))
  11198. b = b.dbl();
  11199. } else {
  11200. // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
  11201. b = a.diffAdd(b, c);
  11202. // N * Q + Q = 2 * ((N / 2) * Q + Q)
  11203. a = a.dbl();
  11204. }
  11205. }
  11206. return b;
  11207. };
  11208. Point.prototype.mulAdd = function mulAdd() {
  11209. throw new Error('Not supported on Montgomery curve');
  11210. };
  11211. Point.prototype.jumlAdd = function jumlAdd() {
  11212. throw new Error('Not supported on Montgomery curve');
  11213. };
  11214. Point.prototype.eq = function eq(other) {
  11215. return this.getX().cmp(other.getX()) === 0;
  11216. };
  11217. Point.prototype.normalize = function normalize() {
  11218. this.x = this.x.redMul(this.z.redInvm());
  11219. this.z = this.curve.one;
  11220. return this;
  11221. };
  11222. Point.prototype.getX = function getX() {
  11223. // Normalize coordinates
  11224. this.normalize();
  11225. return this.x.fromRed();
  11226. };
  11227. },{"../../elliptic":70,"../curve":73,"bn.js":17,"inherits":104}],75:[function(require,module,exports){
  11228. 'use strict';
  11229. var curve = require('../curve');
  11230. var elliptic = require('../../elliptic');
  11231. var BN = require('bn.js');
  11232. var inherits = require('inherits');
  11233. var Base = curve.base;
  11234. var assert = elliptic.utils.assert;
  11235. function ShortCurve(conf) {
  11236. Base.call(this, 'short', conf);
  11237. this.a = new BN(conf.a, 16).toRed(this.red);
  11238. this.b = new BN(conf.b, 16).toRed(this.red);
  11239. this.tinv = this.two.redInvm();
  11240. this.zeroA = this.a.fromRed().cmpn(0) === 0;
  11241. this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
  11242. // If the curve is endomorphic, precalculate beta and lambda
  11243. this.endo = this._getEndomorphism(conf);
  11244. this._endoWnafT1 = new Array(4);
  11245. this._endoWnafT2 = new Array(4);
  11246. }
  11247. inherits(ShortCurve, Base);
  11248. module.exports = ShortCurve;
  11249. ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
  11250. // No efficient endomorphism
  11251. if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
  11252. return;
  11253. // Compute beta and lambda, that lambda * P = (beta * Px; Py)
  11254. var beta;
  11255. var lambda;
  11256. if (conf.beta) {
  11257. beta = new BN(conf.beta, 16).toRed(this.red);
  11258. } else {
  11259. var betas = this._getEndoRoots(this.p);
  11260. // Choose the smallest beta
  11261. beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
  11262. beta = beta.toRed(this.red);
  11263. }
  11264. if (conf.lambda) {
  11265. lambda = new BN(conf.lambda, 16);
  11266. } else {
  11267. // Choose the lambda that is matching selected beta
  11268. var lambdas = this._getEndoRoots(this.n);
  11269. if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
  11270. lambda = lambdas[0];
  11271. } else {
  11272. lambda = lambdas[1];
  11273. assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
  11274. }
  11275. }
  11276. // Get basis vectors, used for balanced length-two representation
  11277. var basis;
  11278. if (conf.basis) {
  11279. basis = conf.basis.map(function(vec) {
  11280. return {
  11281. a: new BN(vec.a, 16),
  11282. b: new BN(vec.b, 16)
  11283. };
  11284. });
  11285. } else {
  11286. basis = this._getEndoBasis(lambda);
  11287. }
  11288. return {
  11289. beta: beta,
  11290. lambda: lambda,
  11291. basis: basis
  11292. };
  11293. };
  11294. ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
  11295. // Find roots of for x^2 + x + 1 in F
  11296. // Root = (-1 +- Sqrt(-3)) / 2
  11297. //
  11298. var red = num === this.p ? this.red : BN.mont(num);
  11299. var tinv = new BN(2).toRed(red).redInvm();
  11300. var ntinv = tinv.redNeg();
  11301. var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);
  11302. var l1 = ntinv.redAdd(s).fromRed();
  11303. var l2 = ntinv.redSub(s).fromRed();
  11304. return [ l1, l2 ];
  11305. };
  11306. ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
  11307. // aprxSqrt >= sqrt(this.n)
  11308. var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
  11309. // 3.74
  11310. // Run EGCD, until r(L + 1) < aprxSqrt
  11311. var u = lambda;
  11312. var v = this.n.clone();
  11313. var x1 = new BN(1);
  11314. var y1 = new BN(0);
  11315. var x2 = new BN(0);
  11316. var y2 = new BN(1);
  11317. // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
  11318. var a0;
  11319. var b0;
  11320. // First vector
  11321. var a1;
  11322. var b1;
  11323. // Second vector
  11324. var a2;
  11325. var b2;
  11326. var prevR;
  11327. var i = 0;
  11328. var r;
  11329. var x;
  11330. while (u.cmpn(0) !== 0) {
  11331. var q = v.div(u);
  11332. r = v.sub(q.mul(u));
  11333. x = x2.sub(q.mul(x1));
  11334. var y = y2.sub(q.mul(y1));
  11335. if (!a1 && r.cmp(aprxSqrt) < 0) {
  11336. a0 = prevR.neg();
  11337. b0 = x1;
  11338. a1 = r.neg();
  11339. b1 = x;
  11340. } else if (a1 && ++i === 2) {
  11341. break;
  11342. }
  11343. prevR = r;
  11344. v = u;
  11345. u = r;
  11346. x2 = x1;
  11347. x1 = x;
  11348. y2 = y1;
  11349. y1 = y;
  11350. }
  11351. a2 = r.neg();
  11352. b2 = x;
  11353. var len1 = a1.sqr().add(b1.sqr());
  11354. var len2 = a2.sqr().add(b2.sqr());
  11355. if (len2.cmp(len1) >= 0) {
  11356. a2 = a0;
  11357. b2 = b0;
  11358. }
  11359. // Normalize signs
  11360. if (a1.negative) {
  11361. a1 = a1.neg();
  11362. b1 = b1.neg();
  11363. }
  11364. if (a2.negative) {
  11365. a2 = a2.neg();
  11366. b2 = b2.neg();
  11367. }
  11368. return [
  11369. { a: a1, b: b1 },
  11370. { a: a2, b: b2 }
  11371. ];
  11372. };
  11373. ShortCurve.prototype._endoSplit = function _endoSplit(k) {
  11374. var basis = this.endo.basis;
  11375. var v1 = basis[0];
  11376. var v2 = basis[1];
  11377. var c1 = v2.b.mul(k).divRound(this.n);
  11378. var c2 = v1.b.neg().mul(k).divRound(this.n);
  11379. var p1 = c1.mul(v1.a);
  11380. var p2 = c2.mul(v2.a);
  11381. var q1 = c1.mul(v1.b);
  11382. var q2 = c2.mul(v2.b);
  11383. // Calculate answer
  11384. var k1 = k.sub(p1).sub(p2);
  11385. var k2 = q1.add(q2).neg();
  11386. return { k1: k1, k2: k2 };
  11387. };
  11388. ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
  11389. x = new BN(x, 16);
  11390. if (!x.red)
  11391. x = x.toRed(this.red);
  11392. var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
  11393. var y = y2.redSqrt();
  11394. if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
  11395. throw new Error('invalid point');
  11396. // XXX Is there any way to tell if the number is odd without converting it
  11397. // to non-red form?
  11398. var isOdd = y.fromRed().isOdd();
  11399. if (odd && !isOdd || !odd && isOdd)
  11400. y = y.redNeg();
  11401. return this.point(x, y);
  11402. };
  11403. ShortCurve.prototype.validate = function validate(point) {
  11404. if (point.inf)
  11405. return true;
  11406. var x = point.x;
  11407. var y = point.y;
  11408. var ax = this.a.redMul(x);
  11409. var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
  11410. return y.redSqr().redISub(rhs).cmpn(0) === 0;
  11411. };
  11412. ShortCurve.prototype._endoWnafMulAdd =
  11413. function _endoWnafMulAdd(points, coeffs, jacobianResult) {
  11414. var npoints = this._endoWnafT1;
  11415. var ncoeffs = this._endoWnafT2;
  11416. for (var i = 0; i < points.length; i++) {
  11417. var split = this._endoSplit(coeffs[i]);
  11418. var p = points[i];
  11419. var beta = p._getBeta();
  11420. if (split.k1.negative) {
  11421. split.k1.ineg();
  11422. p = p.neg(true);
  11423. }
  11424. if (split.k2.negative) {
  11425. split.k2.ineg();
  11426. beta = beta.neg(true);
  11427. }
  11428. npoints[i * 2] = p;
  11429. npoints[i * 2 + 1] = beta;
  11430. ncoeffs[i * 2] = split.k1;
  11431. ncoeffs[i * 2 + 1] = split.k2;
  11432. }
  11433. var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);
  11434. // Clean-up references to points and coefficients
  11435. for (var j = 0; j < i * 2; j++) {
  11436. npoints[j] = null;
  11437. ncoeffs[j] = null;
  11438. }
  11439. return res;
  11440. };
  11441. function Point(curve, x, y, isRed) {
  11442. Base.BasePoint.call(this, curve, 'affine');
  11443. if (x === null && y === null) {
  11444. this.x = null;
  11445. this.y = null;
  11446. this.inf = true;
  11447. } else {
  11448. this.x = new BN(x, 16);
  11449. this.y = new BN(y, 16);
  11450. // Force redgomery representation when loading from JSON
  11451. if (isRed) {
  11452. this.x.forceRed(this.curve.red);
  11453. this.y.forceRed(this.curve.red);
  11454. }
  11455. if (!this.x.red)
  11456. this.x = this.x.toRed(this.curve.red);
  11457. if (!this.y.red)
  11458. this.y = this.y.toRed(this.curve.red);
  11459. this.inf = false;
  11460. }
  11461. }
  11462. inherits(Point, Base.BasePoint);
  11463. ShortCurve.prototype.point = function point(x, y, isRed) {
  11464. return new Point(this, x, y, isRed);
  11465. };
  11466. ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
  11467. return Point.fromJSON(this, obj, red);
  11468. };
  11469. Point.prototype._getBeta = function _getBeta() {
  11470. if (!this.curve.endo)
  11471. return;
  11472. var pre = this.precomputed;
  11473. if (pre && pre.beta)
  11474. return pre.beta;
  11475. var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
  11476. if (pre) {
  11477. var curve = this.curve;
  11478. var endoMul = function(p) {
  11479. return curve.point(p.x.redMul(curve.endo.beta), p.y);
  11480. };
  11481. pre.beta = beta;
  11482. beta.precomputed = {
  11483. beta: null,
  11484. naf: pre.naf && {
  11485. wnd: pre.naf.wnd,
  11486. points: pre.naf.points.map(endoMul)
  11487. },
  11488. doubles: pre.doubles && {
  11489. step: pre.doubles.step,
  11490. points: pre.doubles.points.map(endoMul)
  11491. }
  11492. };
  11493. }
  11494. return beta;
  11495. };
  11496. Point.prototype.toJSON = function toJSON() {
  11497. if (!this.precomputed)
  11498. return [ this.x, this.y ];
  11499. return [ this.x, this.y, this.precomputed && {
  11500. doubles: this.precomputed.doubles && {
  11501. step: this.precomputed.doubles.step,
  11502. points: this.precomputed.doubles.points.slice(1)
  11503. },
  11504. naf: this.precomputed.naf && {
  11505. wnd: this.precomputed.naf.wnd,
  11506. points: this.precomputed.naf.points.slice(1)
  11507. }
  11508. } ];
  11509. };
  11510. Point.fromJSON = function fromJSON(curve, obj, red) {
  11511. if (typeof obj === 'string')
  11512. obj = JSON.parse(obj);
  11513. var res = curve.point(obj[0], obj[1], red);
  11514. if (!obj[2])
  11515. return res;
  11516. function obj2point(obj) {
  11517. return curve.point(obj[0], obj[1], red);
  11518. }
  11519. var pre = obj[2];
  11520. res.precomputed = {
  11521. beta: null,
  11522. doubles: pre.doubles && {
  11523. step: pre.doubles.step,
  11524. points: [ res ].concat(pre.doubles.points.map(obj2point))
  11525. },
  11526. naf: pre.naf && {
  11527. wnd: pre.naf.wnd,
  11528. points: [ res ].concat(pre.naf.points.map(obj2point))
  11529. }
  11530. };
  11531. return res;
  11532. };
  11533. Point.prototype.inspect = function inspect() {
  11534. if (this.isInfinity())
  11535. return '<EC Point Infinity>';
  11536. return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
  11537. ' y: ' + this.y.fromRed().toString(16, 2) + '>';
  11538. };
  11539. Point.prototype.isInfinity = function isInfinity() {
  11540. return this.inf;
  11541. };
  11542. Point.prototype.add = function add(p) {
  11543. // O + P = P
  11544. if (this.inf)
  11545. return p;
  11546. // P + O = P
  11547. if (p.inf)
  11548. return this;
  11549. // P + P = 2P
  11550. if (this.eq(p))
  11551. return this.dbl();
  11552. // P + (-P) = O
  11553. if (this.neg().eq(p))
  11554. return this.curve.point(null, null);
  11555. // P + Q = O
  11556. if (this.x.cmp(p.x) === 0)
  11557. return this.curve.point(null, null);
  11558. var c = this.y.redSub(p.y);
  11559. if (c.cmpn(0) !== 0)
  11560. c = c.redMul(this.x.redSub(p.x).redInvm());
  11561. var nx = c.redSqr().redISub(this.x).redISub(p.x);
  11562. var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
  11563. return this.curve.point(nx, ny);
  11564. };
  11565. Point.prototype.dbl = function dbl() {
  11566. if (this.inf)
  11567. return this;
  11568. // 2P = O
  11569. var ys1 = this.y.redAdd(this.y);
  11570. if (ys1.cmpn(0) === 0)
  11571. return this.curve.point(null, null);
  11572. var a = this.curve.a;
  11573. var x2 = this.x.redSqr();
  11574. var dyinv = ys1.redInvm();
  11575. var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
  11576. var nx = c.redSqr().redISub(this.x.redAdd(this.x));
  11577. var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
  11578. return this.curve.point(nx, ny);
  11579. };
  11580. Point.prototype.getX = function getX() {
  11581. return this.x.fromRed();
  11582. };
  11583. Point.prototype.getY = function getY() {
  11584. return this.y.fromRed();
  11585. };
  11586. Point.prototype.mul = function mul(k) {
  11587. k = new BN(k, 16);
  11588. if (this._hasDoubles(k))
  11589. return this.curve._fixedNafMul(this, k);
  11590. else if (this.curve.endo)
  11591. return this.curve._endoWnafMulAdd([ this ], [ k ]);
  11592. else
  11593. return this.curve._wnafMul(this, k);
  11594. };
  11595. Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
  11596. var points = [ this, p2 ];
  11597. var coeffs = [ k1, k2 ];
  11598. if (this.curve.endo)
  11599. return this.curve._endoWnafMulAdd(points, coeffs);
  11600. else
  11601. return this.curve._wnafMulAdd(1, points, coeffs, 2);
  11602. };
  11603. Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
  11604. var points = [ this, p2 ];
  11605. var coeffs = [ k1, k2 ];
  11606. if (this.curve.endo)
  11607. return this.curve._endoWnafMulAdd(points, coeffs, true);
  11608. else
  11609. return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
  11610. };
  11611. Point.prototype.eq = function eq(p) {
  11612. return this === p ||
  11613. this.inf === p.inf &&
  11614. (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
  11615. };
  11616. Point.prototype.neg = function neg(_precompute) {
  11617. if (this.inf)
  11618. return this;
  11619. var res = this.curve.point(this.x, this.y.redNeg());
  11620. if (_precompute && this.precomputed) {
  11621. var pre = this.precomputed;
  11622. var negate = function(p) {
  11623. return p.neg();
  11624. };
  11625. res.precomputed = {
  11626. naf: pre.naf && {
  11627. wnd: pre.naf.wnd,
  11628. points: pre.naf.points.map(negate)
  11629. },
  11630. doubles: pre.doubles && {
  11631. step: pre.doubles.step,
  11632. points: pre.doubles.points.map(negate)
  11633. }
  11634. };
  11635. }
  11636. return res;
  11637. };
  11638. Point.prototype.toJ = function toJ() {
  11639. if (this.inf)
  11640. return this.curve.jpoint(null, null, null);
  11641. var res = this.curve.jpoint(this.x, this.y, this.curve.one);
  11642. return res;
  11643. };
  11644. function JPoint(curve, x, y, z) {
  11645. Base.BasePoint.call(this, curve, 'jacobian');
  11646. if (x === null && y === null && z === null) {
  11647. this.x = this.curve.one;
  11648. this.y = this.curve.one;
  11649. this.z = new BN(0);
  11650. } else {
  11651. this.x = new BN(x, 16);
  11652. this.y = new BN(y, 16);
  11653. this.z = new BN(z, 16);
  11654. }
  11655. if (!this.x.red)
  11656. this.x = this.x.toRed(this.curve.red);
  11657. if (!this.y.red)
  11658. this.y = this.y.toRed(this.curve.red);
  11659. if (!this.z.red)
  11660. this.z = this.z.toRed(this.curve.red);
  11661. this.zOne = this.z === this.curve.one;
  11662. }
  11663. inherits(JPoint, Base.BasePoint);
  11664. ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
  11665. return new JPoint(this, x, y, z);
  11666. };
  11667. JPoint.prototype.toP = function toP() {
  11668. if (this.isInfinity())
  11669. return this.curve.point(null, null);
  11670. var zinv = this.z.redInvm();
  11671. var zinv2 = zinv.redSqr();
  11672. var ax = this.x.redMul(zinv2);
  11673. var ay = this.y.redMul(zinv2).redMul(zinv);
  11674. return this.curve.point(ax, ay);
  11675. };
  11676. JPoint.prototype.neg = function neg() {
  11677. return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
  11678. };
  11679. JPoint.prototype.add = function add(p) {
  11680. // O + P = P
  11681. if (this.isInfinity())
  11682. return p;
  11683. // P + O = P
  11684. if (p.isInfinity())
  11685. return this;
  11686. // 12M + 4S + 7A
  11687. var pz2 = p.z.redSqr();
  11688. var z2 = this.z.redSqr();
  11689. var u1 = this.x.redMul(pz2);
  11690. var u2 = p.x.redMul(z2);
  11691. var s1 = this.y.redMul(pz2.redMul(p.z));
  11692. var s2 = p.y.redMul(z2.redMul(this.z));
  11693. var h = u1.redSub(u2);
  11694. var r = s1.redSub(s2);
  11695. if (h.cmpn(0) === 0) {
  11696. if (r.cmpn(0) !== 0)
  11697. return this.curve.jpoint(null, null, null);
  11698. else
  11699. return this.dbl();
  11700. }
  11701. var h2 = h.redSqr();
  11702. var h3 = h2.redMul(h);
  11703. var v = u1.redMul(h2);
  11704. var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
  11705. var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
  11706. var nz = this.z.redMul(p.z).redMul(h);
  11707. return this.curve.jpoint(nx, ny, nz);
  11708. };
  11709. JPoint.prototype.mixedAdd = function mixedAdd(p) {
  11710. // O + P = P
  11711. if (this.isInfinity())
  11712. return p.toJ();
  11713. // P + O = P
  11714. if (p.isInfinity())
  11715. return this;
  11716. // 8M + 3S + 7A
  11717. var z2 = this.z.redSqr();
  11718. var u1 = this.x;
  11719. var u2 = p.x.redMul(z2);
  11720. var s1 = this.y;
  11721. var s2 = p.y.redMul(z2).redMul(this.z);
  11722. var h = u1.redSub(u2);
  11723. var r = s1.redSub(s2);
  11724. if (h.cmpn(0) === 0) {
  11725. if (r.cmpn(0) !== 0)
  11726. return this.curve.jpoint(null, null, null);
  11727. else
  11728. return this.dbl();
  11729. }
  11730. var h2 = h.redSqr();
  11731. var h3 = h2.redMul(h);
  11732. var v = u1.redMul(h2);
  11733. var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
  11734. var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
  11735. var nz = this.z.redMul(h);
  11736. return this.curve.jpoint(nx, ny, nz);
  11737. };
  11738. JPoint.prototype.dblp = function dblp(pow) {
  11739. if (pow === 0)
  11740. return this;
  11741. if (this.isInfinity())
  11742. return this;
  11743. if (!pow)
  11744. return this.dbl();
  11745. if (this.curve.zeroA || this.curve.threeA) {
  11746. var r = this;
  11747. for (var i = 0; i < pow; i++)
  11748. r = r.dbl();
  11749. return r;
  11750. }
  11751. // 1M + 2S + 1A + N * (4S + 5M + 8A)
  11752. // N = 1 => 6M + 6S + 9A
  11753. var a = this.curve.a;
  11754. var tinv = this.curve.tinv;
  11755. var jx = this.x;
  11756. var jy = this.y;
  11757. var jz = this.z;
  11758. var jz4 = jz.redSqr().redSqr();
  11759. // Reuse results
  11760. var jyd = jy.redAdd(jy);
  11761. for (var i = 0; i < pow; i++) {
  11762. var jx2 = jx.redSqr();
  11763. var jyd2 = jyd.redSqr();
  11764. var jyd4 = jyd2.redSqr();
  11765. var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
  11766. var t1 = jx.redMul(jyd2);
  11767. var nx = c.redSqr().redISub(t1.redAdd(t1));
  11768. var t2 = t1.redISub(nx);
  11769. var dny = c.redMul(t2);
  11770. dny = dny.redIAdd(dny).redISub(jyd4);
  11771. var nz = jyd.redMul(jz);
  11772. if (i + 1 < pow)
  11773. jz4 = jz4.redMul(jyd4);
  11774. jx = nx;
  11775. jz = nz;
  11776. jyd = dny;
  11777. }
  11778. return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
  11779. };
  11780. JPoint.prototype.dbl = function dbl() {
  11781. if (this.isInfinity())
  11782. return this;
  11783. if (this.curve.zeroA)
  11784. return this._zeroDbl();
  11785. else if (this.curve.threeA)
  11786. return this._threeDbl();
  11787. else
  11788. return this._dbl();
  11789. };
  11790. JPoint.prototype._zeroDbl = function _zeroDbl() {
  11791. var nx;
  11792. var ny;
  11793. var nz;
  11794. // Z = 1
  11795. if (this.zOne) {
  11796. // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
  11797. // #doubling-mdbl-2007-bl
  11798. // 1M + 5S + 14A
  11799. // XX = X1^2
  11800. var xx = this.x.redSqr();
  11801. // YY = Y1^2
  11802. var yy = this.y.redSqr();
  11803. // YYYY = YY^2
  11804. var yyyy = yy.redSqr();
  11805. // S = 2 * ((X1 + YY)^2 - XX - YYYY)
  11806. var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
  11807. s = s.redIAdd(s);
  11808. // M = 3 * XX + a; a = 0
  11809. var m = xx.redAdd(xx).redIAdd(xx);
  11810. // T = M ^ 2 - 2*S
  11811. var t = m.redSqr().redISub(s).redISub(s);
  11812. // 8 * YYYY
  11813. var yyyy8 = yyyy.redIAdd(yyyy);
  11814. yyyy8 = yyyy8.redIAdd(yyyy8);
  11815. yyyy8 = yyyy8.redIAdd(yyyy8);
  11816. // X3 = T
  11817. nx = t;
  11818. // Y3 = M * (S - T) - 8 * YYYY
  11819. ny = m.redMul(s.redISub(t)).redISub(yyyy8);
  11820. // Z3 = 2*Y1
  11821. nz = this.y.redAdd(this.y);
  11822. } else {
  11823. // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
  11824. // #doubling-dbl-2009-l
  11825. // 2M + 5S + 13A
  11826. // A = X1^2
  11827. var a = this.x.redSqr();
  11828. // B = Y1^2
  11829. var b = this.y.redSqr();
  11830. // C = B^2
  11831. var c = b.redSqr();
  11832. // D = 2 * ((X1 + B)^2 - A - C)
  11833. var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
  11834. d = d.redIAdd(d);
  11835. // E = 3 * A
  11836. var e = a.redAdd(a).redIAdd(a);
  11837. // F = E^2
  11838. var f = e.redSqr();
  11839. // 8 * C
  11840. var c8 = c.redIAdd(c);
  11841. c8 = c8.redIAdd(c8);
  11842. c8 = c8.redIAdd(c8);
  11843. // X3 = F - 2 * D
  11844. nx = f.redISub(d).redISub(d);
  11845. // Y3 = E * (D - X3) - 8 * C
  11846. ny = e.redMul(d.redISub(nx)).redISub(c8);
  11847. // Z3 = 2 * Y1 * Z1
  11848. nz = this.y.redMul(this.z);
  11849. nz = nz.redIAdd(nz);
  11850. }
  11851. return this.curve.jpoint(nx, ny, nz);
  11852. };
  11853. JPoint.prototype._threeDbl = function _threeDbl() {
  11854. var nx;
  11855. var ny;
  11856. var nz;
  11857. // Z = 1
  11858. if (this.zOne) {
  11859. // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
  11860. // #doubling-mdbl-2007-bl
  11861. // 1M + 5S + 15A
  11862. // XX = X1^2
  11863. var xx = this.x.redSqr();
  11864. // YY = Y1^2
  11865. var yy = this.y.redSqr();
  11866. // YYYY = YY^2
  11867. var yyyy = yy.redSqr();
  11868. // S = 2 * ((X1 + YY)^2 - XX - YYYY)
  11869. var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
  11870. s = s.redIAdd(s);
  11871. // M = 3 * XX + a
  11872. var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
  11873. // T = M^2 - 2 * S
  11874. var t = m.redSqr().redISub(s).redISub(s);
  11875. // X3 = T
  11876. nx = t;
  11877. // Y3 = M * (S - T) - 8 * YYYY
  11878. var yyyy8 = yyyy.redIAdd(yyyy);
  11879. yyyy8 = yyyy8.redIAdd(yyyy8);
  11880. yyyy8 = yyyy8.redIAdd(yyyy8);
  11881. ny = m.redMul(s.redISub(t)).redISub(yyyy8);
  11882. // Z3 = 2 * Y1
  11883. nz = this.y.redAdd(this.y);
  11884. } else {
  11885. // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
  11886. // 3M + 5S
  11887. // delta = Z1^2
  11888. var delta = this.z.redSqr();
  11889. // gamma = Y1^2
  11890. var gamma = this.y.redSqr();
  11891. // beta = X1 * gamma
  11892. var beta = this.x.redMul(gamma);
  11893. // alpha = 3 * (X1 - delta) * (X1 + delta)
  11894. var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
  11895. alpha = alpha.redAdd(alpha).redIAdd(alpha);
  11896. // X3 = alpha^2 - 8 * beta
  11897. var beta4 = beta.redIAdd(beta);
  11898. beta4 = beta4.redIAdd(beta4);
  11899. var beta8 = beta4.redAdd(beta4);
  11900. nx = alpha.redSqr().redISub(beta8);
  11901. // Z3 = (Y1 + Z1)^2 - gamma - delta
  11902. nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
  11903. // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
  11904. var ggamma8 = gamma.redSqr();
  11905. ggamma8 = ggamma8.redIAdd(ggamma8);
  11906. ggamma8 = ggamma8.redIAdd(ggamma8);
  11907. ggamma8 = ggamma8.redIAdd(ggamma8);
  11908. ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
  11909. }
  11910. return this.curve.jpoint(nx, ny, nz);
  11911. };
  11912. JPoint.prototype._dbl = function _dbl() {
  11913. var a = this.curve.a;
  11914. // 4M + 6S + 10A
  11915. var jx = this.x;
  11916. var jy = this.y;
  11917. var jz = this.z;
  11918. var jz4 = jz.redSqr().redSqr();
  11919. var jx2 = jx.redSqr();
  11920. var jy2 = jy.redSqr();
  11921. var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
  11922. var jxd4 = jx.redAdd(jx);
  11923. jxd4 = jxd4.redIAdd(jxd4);
  11924. var t1 = jxd4.redMul(jy2);
  11925. var nx = c.redSqr().redISub(t1.redAdd(t1));
  11926. var t2 = t1.redISub(nx);
  11927. var jyd8 = jy2.redSqr();
  11928. jyd8 = jyd8.redIAdd(jyd8);
  11929. jyd8 = jyd8.redIAdd(jyd8);
  11930. jyd8 = jyd8.redIAdd(jyd8);
  11931. var ny = c.redMul(t2).redISub(jyd8);
  11932. var nz = jy.redAdd(jy).redMul(jz);
  11933. return this.curve.jpoint(nx, ny, nz);
  11934. };
  11935. JPoint.prototype.trpl = function trpl() {
  11936. if (!this.curve.zeroA)
  11937. return this.dbl().add(this);
  11938. // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
  11939. // 5M + 10S + ...
  11940. // XX = X1^2
  11941. var xx = this.x.redSqr();
  11942. // YY = Y1^2
  11943. var yy = this.y.redSqr();
  11944. // ZZ = Z1^2
  11945. var zz = this.z.redSqr();
  11946. // YYYY = YY^2
  11947. var yyyy = yy.redSqr();
  11948. // M = 3 * XX + a * ZZ2; a = 0
  11949. var m = xx.redAdd(xx).redIAdd(xx);
  11950. // MM = M^2
  11951. var mm = m.redSqr();
  11952. // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
  11953. var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
  11954. e = e.redIAdd(e);
  11955. e = e.redAdd(e).redIAdd(e);
  11956. e = e.redISub(mm);
  11957. // EE = E^2
  11958. var ee = e.redSqr();
  11959. // T = 16*YYYY
  11960. var t = yyyy.redIAdd(yyyy);
  11961. t = t.redIAdd(t);
  11962. t = t.redIAdd(t);
  11963. t = t.redIAdd(t);
  11964. // U = (M + E)^2 - MM - EE - T
  11965. var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
  11966. // X3 = 4 * (X1 * EE - 4 * YY * U)
  11967. var yyu4 = yy.redMul(u);
  11968. yyu4 = yyu4.redIAdd(yyu4);
  11969. yyu4 = yyu4.redIAdd(yyu4);
  11970. var nx = this.x.redMul(ee).redISub(yyu4);
  11971. nx = nx.redIAdd(nx);
  11972. nx = nx.redIAdd(nx);
  11973. // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
  11974. var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
  11975. ny = ny.redIAdd(ny);
  11976. ny = ny.redIAdd(ny);
  11977. ny = ny.redIAdd(ny);
  11978. // Z3 = (Z1 + E)^2 - ZZ - EE
  11979. var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
  11980. return this.curve.jpoint(nx, ny, nz);
  11981. };
  11982. JPoint.prototype.mul = function mul(k, kbase) {
  11983. k = new BN(k, kbase);
  11984. return this.curve._wnafMul(this, k);
  11985. };
  11986. JPoint.prototype.eq = function eq(p) {
  11987. if (p.type === 'affine')
  11988. return this.eq(p.toJ());
  11989. if (this === p)
  11990. return true;
  11991. // x1 * z2^2 == x2 * z1^2
  11992. var z2 = this.z.redSqr();
  11993. var pz2 = p.z.redSqr();
  11994. if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
  11995. return false;
  11996. // y1 * z2^3 == y2 * z1^3
  11997. var z3 = z2.redMul(this.z);
  11998. var pz3 = pz2.redMul(p.z);
  11999. return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
  12000. };
  12001. JPoint.prototype.eqXToP = function eqXToP(x) {
  12002. var zs = this.z.redSqr();
  12003. var rx = x.toRed(this.curve.red).redMul(zs);
  12004. if (this.x.cmp(rx) === 0)
  12005. return true;
  12006. var xc = x.clone();
  12007. var t = this.curve.redN.redMul(zs);
  12008. for (;;) {
  12009. xc.iadd(this.curve.n);
  12010. if (xc.cmp(this.curve.p) >= 0)
  12011. return false;
  12012. rx.redIAdd(t);
  12013. if (this.x.cmp(rx) === 0)
  12014. return true;
  12015. }
  12016. return false;
  12017. };
  12018. JPoint.prototype.inspect = function inspect() {
  12019. if (this.isInfinity())
  12020. return '<EC JPoint Infinity>';
  12021. return '<EC JPoint x: ' + this.x.toString(16, 2) +
  12022. ' y: ' + this.y.toString(16, 2) +
  12023. ' z: ' + this.z.toString(16, 2) + '>';
  12024. };
  12025. JPoint.prototype.isInfinity = function isInfinity() {
  12026. // XXX This code assumes that zero is always zero in red
  12027. return this.z.cmpn(0) === 0;
  12028. };
  12029. },{"../../elliptic":70,"../curve":73,"bn.js":17,"inherits":104}],76:[function(require,module,exports){
  12030. 'use strict';
  12031. var curves = exports;
  12032. var hash = require('hash.js');
  12033. var elliptic = require('../elliptic');
  12034. var assert = elliptic.utils.assert;
  12035. function PresetCurve(options) {
  12036. if (options.type === 'short')
  12037. this.curve = new elliptic.curve.short(options);
  12038. else if (options.type === 'edwards')
  12039. this.curve = new elliptic.curve.edwards(options);
  12040. else
  12041. this.curve = new elliptic.curve.mont(options);
  12042. this.g = this.curve.g;
  12043. this.n = this.curve.n;
  12044. this.hash = options.hash;
  12045. assert(this.g.validate(), 'Invalid curve');
  12046. assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');
  12047. }
  12048. curves.PresetCurve = PresetCurve;
  12049. function defineCurve(name, options) {
  12050. Object.defineProperty(curves, name, {
  12051. configurable: true,
  12052. enumerable: true,
  12053. get: function() {
  12054. var curve = new PresetCurve(options);
  12055. Object.defineProperty(curves, name, {
  12056. configurable: true,
  12057. enumerable: true,
  12058. value: curve
  12059. });
  12060. return curve;
  12061. }
  12062. });
  12063. }
  12064. defineCurve('p192', {
  12065. type: 'short',
  12066. prime: 'p192',
  12067. p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
  12068. a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
  12069. b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
  12070. n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
  12071. hash: hash.sha256,
  12072. gRed: false,
  12073. g: [
  12074. '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
  12075. '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'
  12076. ]
  12077. });
  12078. defineCurve('p224', {
  12079. type: 'short',
  12080. prime: 'p224',
  12081. p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
  12082. a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
  12083. b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
  12084. n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
  12085. hash: hash.sha256,
  12086. gRed: false,
  12087. g: [
  12088. 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
  12089. 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'
  12090. ]
  12091. });
  12092. defineCurve('p256', {
  12093. type: 'short',
  12094. prime: null,
  12095. p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
  12096. a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
  12097. b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
  12098. n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
  12099. hash: hash.sha256,
  12100. gRed: false,
  12101. g: [
  12102. '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
  12103. '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'
  12104. ]
  12105. });
  12106. defineCurve('p384', {
  12107. type: 'short',
  12108. prime: null,
  12109. p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
  12110. 'fffffffe ffffffff 00000000 00000000 ffffffff',
  12111. a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
  12112. 'fffffffe ffffffff 00000000 00000000 fffffffc',
  12113. b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
  12114. '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
  12115. n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
  12116. 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
  12117. hash: hash.sha384,
  12118. gRed: false,
  12119. g: [
  12120. 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
  12121. '5502f25d bf55296c 3a545e38 72760ab7',
  12122. '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
  12123. '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'
  12124. ]
  12125. });
  12126. defineCurve('p521', {
  12127. type: 'short',
  12128. prime: null,
  12129. p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
  12130. 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
  12131. 'ffffffff ffffffff ffffffff ffffffff ffffffff',
  12132. a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
  12133. 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
  12134. 'ffffffff ffffffff ffffffff ffffffff fffffffc',
  12135. b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
  12136. '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
  12137. '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
  12138. n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
  12139. 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
  12140. 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
  12141. hash: hash.sha512,
  12142. gRed: false,
  12143. g: [
  12144. '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
  12145. '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
  12146. 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
  12147. '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
  12148. '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
  12149. '3fad0761 353c7086 a272c240 88be9476 9fd16650'
  12150. ]
  12151. });
  12152. defineCurve('curve25519', {
  12153. type: 'mont',
  12154. prime: 'p25519',
  12155. p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
  12156. a: '76d06',
  12157. b: '1',
  12158. n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
  12159. hash: hash.sha256,
  12160. gRed: false,
  12161. g: [
  12162. '9'
  12163. ]
  12164. });
  12165. defineCurve('ed25519', {
  12166. type: 'edwards',
  12167. prime: 'p25519',
  12168. p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
  12169. a: '-1',
  12170. c: '1',
  12171. // -121665 * (121666^(-1)) (mod P)
  12172. d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
  12173. n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
  12174. hash: hash.sha256,
  12175. gRed: false,
  12176. g: [
  12177. '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
  12178. // 4/5
  12179. '6666666666666666666666666666666666666666666666666666666666666658'
  12180. ]
  12181. });
  12182. var pre;
  12183. try {
  12184. pre = require('./precomputed/secp256k1');
  12185. } catch (e) {
  12186. pre = undefined;
  12187. }
  12188. defineCurve('secp256k1', {
  12189. type: 'short',
  12190. prime: 'k256',
  12191. p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
  12192. a: '0',
  12193. b: '7',
  12194. n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
  12195. h: '1',
  12196. hash: hash.sha256,
  12197. // Precomputed endomorphism
  12198. beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
  12199. lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
  12200. basis: [
  12201. {
  12202. a: '3086d221a7d46bcde86c90e49284eb15',
  12203. b: '-e4437ed6010e88286f547fa90abfe4c3'
  12204. },
  12205. {
  12206. a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
  12207. b: '3086d221a7d46bcde86c90e49284eb15'
  12208. }
  12209. ],
  12210. gRed: false,
  12211. g: [
  12212. '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
  12213. '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
  12214. pre
  12215. ]
  12216. });
  12217. },{"../elliptic":70,"./precomputed/secp256k1":83,"hash.js":89}],77:[function(require,module,exports){
  12218. 'use strict';
  12219. var BN = require('bn.js');
  12220. var HmacDRBG = require('hmac-drbg');
  12221. var elliptic = require('../../elliptic');
  12222. var utils = elliptic.utils;
  12223. var assert = utils.assert;
  12224. var KeyPair = require('./key');
  12225. var Signature = require('./signature');
  12226. function EC(options) {
  12227. if (!(this instanceof EC))
  12228. return new EC(options);
  12229. // Shortcut `elliptic.ec(curve-name)`
  12230. if (typeof options === 'string') {
  12231. assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options);
  12232. options = elliptic.curves[options];
  12233. }
  12234. // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
  12235. if (options instanceof elliptic.curves.PresetCurve)
  12236. options = { curve: options };
  12237. this.curve = options.curve.curve;
  12238. this.n = this.curve.n;
  12239. this.nh = this.n.ushrn(1);
  12240. this.g = this.curve.g;
  12241. // Point on curve
  12242. this.g = options.curve.g;
  12243. this.g.precompute(options.curve.n.bitLength() + 1);
  12244. // Hash for function for DRBG
  12245. this.hash = options.hash || options.curve.hash;
  12246. }
  12247. module.exports = EC;
  12248. EC.prototype.keyPair = function keyPair(options) {
  12249. return new KeyPair(this, options);
  12250. };
  12251. EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
  12252. return KeyPair.fromPrivate(this, priv, enc);
  12253. };
  12254. EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
  12255. return KeyPair.fromPublic(this, pub, enc);
  12256. };
  12257. EC.prototype.genKeyPair = function genKeyPair(options) {
  12258. if (!options)
  12259. options = {};
  12260. // Instantiate Hmac_DRBG
  12261. var drbg = new HmacDRBG({
  12262. hash: this.hash,
  12263. pers: options.pers,
  12264. persEnc: options.persEnc || 'utf8',
  12265. entropy: options.entropy || elliptic.rand(this.hash.hmacStrength),
  12266. entropyEnc: options.entropy && options.entropyEnc || 'utf8',
  12267. nonce: this.n.toArray()
  12268. });
  12269. var bytes = this.n.byteLength();
  12270. var ns2 = this.n.sub(new BN(2));
  12271. do {
  12272. var priv = new BN(drbg.generate(bytes));
  12273. if (priv.cmp(ns2) > 0)
  12274. continue;
  12275. priv.iaddn(1);
  12276. return this.keyFromPrivate(priv);
  12277. } while (true);
  12278. };
  12279. EC.prototype._truncateToN = function truncateToN(msg, truncOnly) {
  12280. var delta = msg.byteLength() * 8 - this.n.bitLength();
  12281. if (delta > 0)
  12282. msg = msg.ushrn(delta);
  12283. if (!truncOnly && msg.cmp(this.n) >= 0)
  12284. return msg.sub(this.n);
  12285. else
  12286. return msg;
  12287. };
  12288. EC.prototype.sign = function sign(msg, key, enc, options) {
  12289. if (typeof enc === 'object') {
  12290. options = enc;
  12291. enc = null;
  12292. }
  12293. if (!options)
  12294. options = {};
  12295. key = this.keyFromPrivate(key, enc);
  12296. msg = this._truncateToN(new BN(msg, 16));
  12297. // Zero-extend key to provide enough entropy
  12298. var bytes = this.n.byteLength();
  12299. var bkey = key.getPrivate().toArray('be', bytes);
  12300. // Zero-extend nonce to have the same byte size as N
  12301. var nonce = msg.toArray('be', bytes);
  12302. // Instantiate Hmac_DRBG
  12303. var drbg = new HmacDRBG({
  12304. hash: this.hash,
  12305. entropy: bkey,
  12306. nonce: nonce,
  12307. pers: options.pers,
  12308. persEnc: options.persEnc || 'utf8'
  12309. });
  12310. // Number of bytes to generate
  12311. var ns1 = this.n.sub(new BN(1));
  12312. for (var iter = 0; true; iter++) {
  12313. var k = options.k ?
  12314. options.k(iter) :
  12315. new BN(drbg.generate(this.n.byteLength()));
  12316. k = this._truncateToN(k, true);
  12317. if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
  12318. continue;
  12319. var kp = this.g.mul(k);
  12320. if (kp.isInfinity())
  12321. continue;
  12322. var kpX = kp.getX();
  12323. var r = kpX.umod(this.n);
  12324. if (r.cmpn(0) === 0)
  12325. continue;
  12326. var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
  12327. s = s.umod(this.n);
  12328. if (s.cmpn(0) === 0)
  12329. continue;
  12330. var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
  12331. (kpX.cmp(r) !== 0 ? 2 : 0);
  12332. // Use complement of `s`, if it is > `n / 2`
  12333. if (options.canonical && s.cmp(this.nh) > 0) {
  12334. s = this.n.sub(s);
  12335. recoveryParam ^= 1;
  12336. }
  12337. return new Signature({ r: r, s: s, recoveryParam: recoveryParam });
  12338. }
  12339. };
  12340. EC.prototype.verify = function verify(msg, signature, key, enc) {
  12341. msg = this._truncateToN(new BN(msg, 16));
  12342. key = this.keyFromPublic(key, enc);
  12343. signature = new Signature(signature, 'hex');
  12344. // Perform primitive values validation
  12345. var r = signature.r;
  12346. var s = signature.s;
  12347. if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
  12348. return false;
  12349. if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
  12350. return false;
  12351. // Validate signature
  12352. var sinv = s.invm(this.n);
  12353. var u1 = sinv.mul(msg).umod(this.n);
  12354. var u2 = sinv.mul(r).umod(this.n);
  12355. if (!this.curve._maxwellTrick) {
  12356. var p = this.g.mulAdd(u1, key.getPublic(), u2);
  12357. if (p.isInfinity())
  12358. return false;
  12359. return p.getX().umod(this.n).cmp(r) === 0;
  12360. }
  12361. // NOTE: Greg Maxwell's trick, inspired by:
  12362. // https://git.io/vad3K
  12363. var p = this.g.jmulAdd(u1, key.getPublic(), u2);
  12364. if (p.isInfinity())
  12365. return false;
  12366. // Compare `p.x` of Jacobian point with `r`,
  12367. // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
  12368. // inverse of `p.z^2`
  12369. return p.eqXToP(r);
  12370. };
  12371. EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
  12372. assert((3 & j) === j, 'The recovery param is more than two bits');
  12373. signature = new Signature(signature, enc);
  12374. var n = this.n;
  12375. var e = new BN(msg);
  12376. var r = signature.r;
  12377. var s = signature.s;
  12378. // A set LSB signifies that the y-coordinate is odd
  12379. var isYOdd = j & 1;
  12380. var isSecondKey = j >> 1;
  12381. if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
  12382. throw new Error('Unable to find sencond key candinate');
  12383. // 1.1. Let x = r + jn.
  12384. if (isSecondKey)
  12385. r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
  12386. else
  12387. r = this.curve.pointFromX(r, isYOdd);
  12388. var rInv = signature.r.invm(n);
  12389. var s1 = n.sub(e).mul(rInv).umod(n);
  12390. var s2 = s.mul(rInv).umod(n);
  12391. // 1.6.1 Compute Q = r^-1 (sR - eG)
  12392. // Q = r^-1 (sR + -eG)
  12393. return this.g.mulAdd(s1, r, s2);
  12394. };
  12395. EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
  12396. signature = new Signature(signature, enc);
  12397. if (signature.recoveryParam !== null)
  12398. return signature.recoveryParam;
  12399. for (var i = 0; i < 4; i++) {
  12400. var Qprime;
  12401. try {
  12402. Qprime = this.recoverPubKey(e, signature, i);
  12403. } catch (e) {
  12404. continue;
  12405. }
  12406. if (Qprime.eq(Q))
  12407. return i;
  12408. }
  12409. throw new Error('Unable to find valid recovery factor');
  12410. };
  12411. },{"../../elliptic":70,"./key":78,"./signature":79,"bn.js":17,"hmac-drbg":101}],78:[function(require,module,exports){
  12412. 'use strict';
  12413. var BN = require('bn.js');
  12414. var elliptic = require('../../elliptic');
  12415. var utils = elliptic.utils;
  12416. var assert = utils.assert;
  12417. function KeyPair(ec, options) {
  12418. this.ec = ec;
  12419. this.priv = null;
  12420. this.pub = null;
  12421. // KeyPair(ec, { priv: ..., pub: ... })
  12422. if (options.priv)
  12423. this._importPrivate(options.priv, options.privEnc);
  12424. if (options.pub)
  12425. this._importPublic(options.pub, options.pubEnc);
  12426. }
  12427. module.exports = KeyPair;
  12428. KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
  12429. if (pub instanceof KeyPair)
  12430. return pub;
  12431. return new KeyPair(ec, {
  12432. pub: pub,
  12433. pubEnc: enc
  12434. });
  12435. };
  12436. KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
  12437. if (priv instanceof KeyPair)
  12438. return priv;
  12439. return new KeyPair(ec, {
  12440. priv: priv,
  12441. privEnc: enc
  12442. });
  12443. };
  12444. KeyPair.prototype.validate = function validate() {
  12445. var pub = this.getPublic();
  12446. if (pub.isInfinity())
  12447. return { result: false, reason: 'Invalid public key' };
  12448. if (!pub.validate())
  12449. return { result: false, reason: 'Public key is not a point' };
  12450. if (!pub.mul(this.ec.curve.n).isInfinity())
  12451. return { result: false, reason: 'Public key * N != O' };
  12452. return { result: true, reason: null };
  12453. };
  12454. KeyPair.prototype.getPublic = function getPublic(compact, enc) {
  12455. // compact is optional argument
  12456. if (typeof compact === 'string') {
  12457. enc = compact;
  12458. compact = null;
  12459. }
  12460. if (!this.pub)
  12461. this.pub = this.ec.g.mul(this.priv);
  12462. if (!enc)
  12463. return this.pub;
  12464. return this.pub.encode(enc, compact);
  12465. };
  12466. KeyPair.prototype.getPrivate = function getPrivate(enc) {
  12467. if (enc === 'hex')
  12468. return this.priv.toString(16, 2);
  12469. else
  12470. return this.priv;
  12471. };
  12472. KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
  12473. this.priv = new BN(key, enc || 16);
  12474. // Ensure that the priv won't be bigger than n, otherwise we may fail
  12475. // in fixed multiplication method
  12476. this.priv = this.priv.umod(this.ec.curve.n);
  12477. };
  12478. KeyPair.prototype._importPublic = function _importPublic(key, enc) {
  12479. if (key.x || key.y) {
  12480. // Montgomery points only have an `x` coordinate.
  12481. // Weierstrass/Edwards points on the other hand have both `x` and
  12482. // `y` coordinates.
  12483. if (this.ec.curve.type === 'mont') {
  12484. assert(key.x, 'Need x coordinate');
  12485. } else if (this.ec.curve.type === 'short' ||
  12486. this.ec.curve.type === 'edwards') {
  12487. assert(key.x && key.y, 'Need both x and y coordinate');
  12488. }
  12489. this.pub = this.ec.curve.point(key.x, key.y);
  12490. return;
  12491. }
  12492. this.pub = this.ec.curve.decodePoint(key, enc);
  12493. };
  12494. // ECDH
  12495. KeyPair.prototype.derive = function derive(pub) {
  12496. return pub.mul(this.priv).getX();
  12497. };
  12498. // ECDSA
  12499. KeyPair.prototype.sign = function sign(msg, enc, options) {
  12500. return this.ec.sign(msg, this, enc, options);
  12501. };
  12502. KeyPair.prototype.verify = function verify(msg, signature) {
  12503. return this.ec.verify(msg, signature, this);
  12504. };
  12505. KeyPair.prototype.inspect = function inspect() {
  12506. return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
  12507. ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
  12508. };
  12509. },{"../../elliptic":70,"bn.js":17}],79:[function(require,module,exports){
  12510. 'use strict';
  12511. var BN = require('bn.js');
  12512. var elliptic = require('../../elliptic');
  12513. var utils = elliptic.utils;
  12514. var assert = utils.assert;
  12515. function Signature(options, enc) {
  12516. if (options instanceof Signature)
  12517. return options;
  12518. if (this._importDER(options, enc))
  12519. return;
  12520. assert(options.r && options.s, 'Signature without r or s');
  12521. this.r = new BN(options.r, 16);
  12522. this.s = new BN(options.s, 16);
  12523. if (options.recoveryParam === undefined)
  12524. this.recoveryParam = null;
  12525. else
  12526. this.recoveryParam = options.recoveryParam;
  12527. }
  12528. module.exports = Signature;
  12529. function Position() {
  12530. this.place = 0;
  12531. }
  12532. function getLength(buf, p) {
  12533. var initial = buf[p.place++];
  12534. if (!(initial & 0x80)) {
  12535. return initial;
  12536. }
  12537. var octetLen = initial & 0xf;
  12538. var val = 0;
  12539. for (var i = 0, off = p.place; i < octetLen; i++, off++) {
  12540. val <<= 8;
  12541. val |= buf[off];
  12542. }
  12543. p.place = off;
  12544. return val;
  12545. }
  12546. function rmPadding(buf) {
  12547. var i = 0;
  12548. var len = buf.length - 1;
  12549. while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
  12550. i++;
  12551. }
  12552. if (i === 0) {
  12553. return buf;
  12554. }
  12555. return buf.slice(i);
  12556. }
  12557. Signature.prototype._importDER = function _importDER(data, enc) {
  12558. data = utils.toArray(data, enc);
  12559. var p = new Position();
  12560. if (data[p.place++] !== 0x30) {
  12561. return false;
  12562. }
  12563. var len = getLength(data, p);
  12564. if ((len + p.place) !== data.length) {
  12565. return false;
  12566. }
  12567. if (data[p.place++] !== 0x02) {
  12568. return false;
  12569. }
  12570. var rlen = getLength(data, p);
  12571. var r = data.slice(p.place, rlen + p.place);
  12572. p.place += rlen;
  12573. if (data[p.place++] !== 0x02) {
  12574. return false;
  12575. }
  12576. var slen = getLength(data, p);
  12577. if (data.length !== slen + p.place) {
  12578. return false;
  12579. }
  12580. var s = data.slice(p.place, slen + p.place);
  12581. if (r[0] === 0 && (r[1] & 0x80)) {
  12582. r = r.slice(1);
  12583. }
  12584. if (s[0] === 0 && (s[1] & 0x80)) {
  12585. s = s.slice(1);
  12586. }
  12587. this.r = new BN(r);
  12588. this.s = new BN(s);
  12589. this.recoveryParam = null;
  12590. return true;
  12591. };
  12592. function constructLength(arr, len) {
  12593. if (len < 0x80) {
  12594. arr.push(len);
  12595. return;
  12596. }
  12597. var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
  12598. arr.push(octets | 0x80);
  12599. while (--octets) {
  12600. arr.push((len >>> (octets << 3)) & 0xff);
  12601. }
  12602. arr.push(len);
  12603. }
  12604. Signature.prototype.toDER = function toDER(enc) {
  12605. var r = this.r.toArray();
  12606. var s = this.s.toArray();
  12607. // Pad values
  12608. if (r[0] & 0x80)
  12609. r = [ 0 ].concat(r);
  12610. // Pad values
  12611. if (s[0] & 0x80)
  12612. s = [ 0 ].concat(s);
  12613. r = rmPadding(r);
  12614. s = rmPadding(s);
  12615. while (!s[0] && !(s[1] & 0x80)) {
  12616. s = s.slice(1);
  12617. }
  12618. var arr = [ 0x02 ];
  12619. constructLength(arr, r.length);
  12620. arr = arr.concat(r);
  12621. arr.push(0x02);
  12622. constructLength(arr, s.length);
  12623. var backHalf = arr.concat(s);
  12624. var res = [ 0x30 ];
  12625. constructLength(res, backHalf.length);
  12626. res = res.concat(backHalf);
  12627. return utils.encode(res, enc);
  12628. };
  12629. },{"../../elliptic":70,"bn.js":17}],80:[function(require,module,exports){
  12630. 'use strict';
  12631. var hash = require('hash.js');
  12632. var elliptic = require('../../elliptic');
  12633. var utils = elliptic.utils;
  12634. var assert = utils.assert;
  12635. var parseBytes = utils.parseBytes;
  12636. var KeyPair = require('./key');
  12637. var Signature = require('./signature');
  12638. function EDDSA(curve) {
  12639. assert(curve === 'ed25519', 'only tested with ed25519 so far');
  12640. if (!(this instanceof EDDSA))
  12641. return new EDDSA(curve);
  12642. var curve = elliptic.curves[curve].curve;
  12643. this.curve = curve;
  12644. this.g = curve.g;
  12645. this.g.precompute(curve.n.bitLength() + 1);
  12646. this.pointClass = curve.point().constructor;
  12647. this.encodingLength = Math.ceil(curve.n.bitLength() / 8);
  12648. this.hash = hash.sha512;
  12649. }
  12650. module.exports = EDDSA;
  12651. /**
  12652. * @param {Array|String} message - message bytes
  12653. * @param {Array|String|KeyPair} secret - secret bytes or a keypair
  12654. * @returns {Signature} - signature
  12655. */
  12656. EDDSA.prototype.sign = function sign(message, secret) {
  12657. message = parseBytes(message);
  12658. var key = this.keyFromSecret(secret);
  12659. var r = this.hashInt(key.messagePrefix(), message);
  12660. var R = this.g.mul(r);
  12661. var Rencoded = this.encodePoint(R);
  12662. var s_ = this.hashInt(Rencoded, key.pubBytes(), message)
  12663. .mul(key.priv());
  12664. var S = r.add(s_).umod(this.curve.n);
  12665. return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });
  12666. };
  12667. /**
  12668. * @param {Array} message - message bytes
  12669. * @param {Array|String|Signature} sig - sig bytes
  12670. * @param {Array|String|Point|KeyPair} pub - public key
  12671. * @returns {Boolean} - true if public key matches sig of message
  12672. */
  12673. EDDSA.prototype.verify = function verify(message, sig, pub) {
  12674. message = parseBytes(message);
  12675. sig = this.makeSignature(sig);
  12676. var key = this.keyFromPublic(pub);
  12677. var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);
  12678. var SG = this.g.mul(sig.S());
  12679. var RplusAh = sig.R().add(key.pub().mul(h));
  12680. return RplusAh.eq(SG);
  12681. };
  12682. EDDSA.prototype.hashInt = function hashInt() {
  12683. var hash = this.hash();
  12684. for (var i = 0; i < arguments.length; i++)
  12685. hash.update(arguments[i]);
  12686. return utils.intFromLE(hash.digest()).umod(this.curve.n);
  12687. };
  12688. EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {
  12689. return KeyPair.fromPublic(this, pub);
  12690. };
  12691. EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {
  12692. return KeyPair.fromSecret(this, secret);
  12693. };
  12694. EDDSA.prototype.makeSignature = function makeSignature(sig) {
  12695. if (sig instanceof Signature)
  12696. return sig;
  12697. return new Signature(this, sig);
  12698. };
  12699. /**
  12700. * * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2
  12701. *
  12702. * EDDSA defines methods for encoding and decoding points and integers. These are
  12703. * helper convenience methods, that pass along to utility functions implied
  12704. * parameters.
  12705. *
  12706. */
  12707. EDDSA.prototype.encodePoint = function encodePoint(point) {
  12708. var enc = point.getY().toArray('le', this.encodingLength);
  12709. enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;
  12710. return enc;
  12711. };
  12712. EDDSA.prototype.decodePoint = function decodePoint(bytes) {
  12713. bytes = utils.parseBytes(bytes);
  12714. var lastIx = bytes.length - 1;
  12715. var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);
  12716. var xIsOdd = (bytes[lastIx] & 0x80) !== 0;
  12717. var y = utils.intFromLE(normed);
  12718. return this.curve.pointFromY(y, xIsOdd);
  12719. };
  12720. EDDSA.prototype.encodeInt = function encodeInt(num) {
  12721. return num.toArray('le', this.encodingLength);
  12722. };
  12723. EDDSA.prototype.decodeInt = function decodeInt(bytes) {
  12724. return utils.intFromLE(bytes);
  12725. };
  12726. EDDSA.prototype.isPoint = function isPoint(val) {
  12727. return val instanceof this.pointClass;
  12728. };
  12729. },{"../../elliptic":70,"./key":81,"./signature":82,"hash.js":89}],81:[function(require,module,exports){
  12730. 'use strict';
  12731. var elliptic = require('../../elliptic');
  12732. var utils = elliptic.utils;
  12733. var assert = utils.assert;
  12734. var parseBytes = utils.parseBytes;
  12735. var cachedProperty = utils.cachedProperty;
  12736. /**
  12737. * @param {EDDSA} eddsa - instance
  12738. * @param {Object} params - public/private key parameters
  12739. *
  12740. * @param {Array<Byte>} [params.secret] - secret seed bytes
  12741. * @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)
  12742. * @param {Array<Byte>} [params.pub] - public key point encoded as bytes
  12743. *
  12744. */
  12745. function KeyPair(eddsa, params) {
  12746. this.eddsa = eddsa;
  12747. this._secret = parseBytes(params.secret);
  12748. if (eddsa.isPoint(params.pub))
  12749. this._pub = params.pub;
  12750. else
  12751. this._pubBytes = parseBytes(params.pub);
  12752. }
  12753. KeyPair.fromPublic = function fromPublic(eddsa, pub) {
  12754. if (pub instanceof KeyPair)
  12755. return pub;
  12756. return new KeyPair(eddsa, { pub: pub });
  12757. };
  12758. KeyPair.fromSecret = function fromSecret(eddsa, secret) {
  12759. if (secret instanceof KeyPair)
  12760. return secret;
  12761. return new KeyPair(eddsa, { secret: secret });
  12762. };
  12763. KeyPair.prototype.secret = function secret() {
  12764. return this._secret;
  12765. };
  12766. cachedProperty(KeyPair, 'pubBytes', function pubBytes() {
  12767. return this.eddsa.encodePoint(this.pub());
  12768. });
  12769. cachedProperty(KeyPair, 'pub', function pub() {
  12770. if (this._pubBytes)
  12771. return this.eddsa.decodePoint(this._pubBytes);
  12772. return this.eddsa.g.mul(this.priv());
  12773. });
  12774. cachedProperty(KeyPair, 'privBytes', function privBytes() {
  12775. var eddsa = this.eddsa;
  12776. var hash = this.hash();
  12777. var lastIx = eddsa.encodingLength - 1;
  12778. var a = hash.slice(0, eddsa.encodingLength);
  12779. a[0] &= 248;
  12780. a[lastIx] &= 127;
  12781. a[lastIx] |= 64;
  12782. return a;
  12783. });
  12784. cachedProperty(KeyPair, 'priv', function priv() {
  12785. return this.eddsa.decodeInt(this.privBytes());
  12786. });
  12787. cachedProperty(KeyPair, 'hash', function hash() {
  12788. return this.eddsa.hash().update(this.secret()).digest();
  12789. });
  12790. cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {
  12791. return this.hash().slice(this.eddsa.encodingLength);
  12792. });
  12793. KeyPair.prototype.sign = function sign(message) {
  12794. assert(this._secret, 'KeyPair can only verify');
  12795. return this.eddsa.sign(message, this);
  12796. };
  12797. KeyPair.prototype.verify = function verify(message, sig) {
  12798. return this.eddsa.verify(message, sig, this);
  12799. };
  12800. KeyPair.prototype.getSecret = function getSecret(enc) {
  12801. assert(this._secret, 'KeyPair is public only');
  12802. return utils.encode(this.secret(), enc);
  12803. };
  12804. KeyPair.prototype.getPublic = function getPublic(enc) {
  12805. return utils.encode(this.pubBytes(), enc);
  12806. };
  12807. module.exports = KeyPair;
  12808. },{"../../elliptic":70}],82:[function(require,module,exports){
  12809. 'use strict';
  12810. var BN = require('bn.js');
  12811. var elliptic = require('../../elliptic');
  12812. var utils = elliptic.utils;
  12813. var assert = utils.assert;
  12814. var cachedProperty = utils.cachedProperty;
  12815. var parseBytes = utils.parseBytes;
  12816. /**
  12817. * @param {EDDSA} eddsa - eddsa instance
  12818. * @param {Array<Bytes>|Object} sig -
  12819. * @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
  12820. * @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
  12821. * @param {Array<Bytes>} [sig.Rencoded] - R point encoded
  12822. * @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
  12823. */
  12824. function Signature(eddsa, sig) {
  12825. this.eddsa = eddsa;
  12826. if (typeof sig !== 'object')
  12827. sig = parseBytes(sig);
  12828. if (Array.isArray(sig)) {
  12829. sig = {
  12830. R: sig.slice(0, eddsa.encodingLength),
  12831. S: sig.slice(eddsa.encodingLength)
  12832. };
  12833. }
  12834. assert(sig.R && sig.S, 'Signature without R or S');
  12835. if (eddsa.isPoint(sig.R))
  12836. this._R = sig.R;
  12837. if (sig.S instanceof BN)
  12838. this._S = sig.S;
  12839. this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
  12840. this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
  12841. }
  12842. cachedProperty(Signature, 'S', function S() {
  12843. return this.eddsa.decodeInt(this.Sencoded());
  12844. });
  12845. cachedProperty(Signature, 'R', function R() {
  12846. return this.eddsa.decodePoint(this.Rencoded());
  12847. });
  12848. cachedProperty(Signature, 'Rencoded', function Rencoded() {
  12849. return this.eddsa.encodePoint(this.R());
  12850. });
  12851. cachedProperty(Signature, 'Sencoded', function Sencoded() {
  12852. return this.eddsa.encodeInt(this.S());
  12853. });
  12854. Signature.prototype.toBytes = function toBytes() {
  12855. return this.Rencoded().concat(this.Sencoded());
  12856. };
  12857. Signature.prototype.toHex = function toHex() {
  12858. return utils.encode(this.toBytes(), 'hex').toUpperCase();
  12859. };
  12860. module.exports = Signature;
  12861. },{"../../elliptic":70,"bn.js":17}],83:[function(require,module,exports){
  12862. module.exports = {
  12863. doubles: {
  12864. step: 4,
  12865. points: [
  12866. [
  12867. 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
  12868. 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'
  12869. ],
  12870. [
  12871. '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
  12872. '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'
  12873. ],
  12874. [
  12875. '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
  12876. 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'
  12877. ],
  12878. [
  12879. '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
  12880. '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'
  12881. ],
  12882. [
  12883. '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
  12884. '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'
  12885. ],
  12886. [
  12887. '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
  12888. '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'
  12889. ],
  12890. [
  12891. 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
  12892. '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'
  12893. ],
  12894. [
  12895. '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
  12896. 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'
  12897. ],
  12898. [
  12899. 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
  12900. '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'
  12901. ],
  12902. [
  12903. 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
  12904. 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'
  12905. ],
  12906. [
  12907. 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
  12908. '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'
  12909. ],
  12910. [
  12911. '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
  12912. '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'
  12913. ],
  12914. [
  12915. '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
  12916. '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'
  12917. ],
  12918. [
  12919. '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
  12920. '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'
  12921. ],
  12922. [
  12923. '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
  12924. '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'
  12925. ],
  12926. [
  12927. '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
  12928. '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'
  12929. ],
  12930. [
  12931. '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
  12932. '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'
  12933. ],
  12934. [
  12935. '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
  12936. '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'
  12937. ],
  12938. [
  12939. '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
  12940. 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'
  12941. ],
  12942. [
  12943. 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
  12944. '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'
  12945. ],
  12946. [
  12947. 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
  12948. '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'
  12949. ],
  12950. [
  12951. '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
  12952. '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'
  12953. ],
  12954. [
  12955. '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
  12956. '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'
  12957. ],
  12958. [
  12959. 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
  12960. '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'
  12961. ],
  12962. [
  12963. '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
  12964. 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'
  12965. ],
  12966. [
  12967. 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
  12968. '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'
  12969. ],
  12970. [
  12971. 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
  12972. 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'
  12973. ],
  12974. [
  12975. 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
  12976. '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'
  12977. ],
  12978. [
  12979. 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
  12980. 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'
  12981. ],
  12982. [
  12983. 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
  12984. '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'
  12985. ],
  12986. [
  12987. '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
  12988. 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'
  12989. ],
  12990. [
  12991. '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
  12992. '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'
  12993. ],
  12994. [
  12995. 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
  12996. '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'
  12997. ],
  12998. [
  12999. '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
  13000. 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'
  13001. ],
  13002. [
  13003. 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
  13004. '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'
  13005. ],
  13006. [
  13007. 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
  13008. '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'
  13009. ],
  13010. [
  13011. 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
  13012. 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'
  13013. ],
  13014. [
  13015. '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
  13016. '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'
  13017. ],
  13018. [
  13019. '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
  13020. '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'
  13021. ],
  13022. [
  13023. '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
  13024. 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'
  13025. ],
  13026. [
  13027. '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
  13028. '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'
  13029. ],
  13030. [
  13031. 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
  13032. '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'
  13033. ],
  13034. [
  13035. '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
  13036. '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'
  13037. ],
  13038. [
  13039. '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
  13040. 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'
  13041. ],
  13042. [
  13043. '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
  13044. '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'
  13045. ],
  13046. [
  13047. 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
  13048. '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'
  13049. ],
  13050. [
  13051. '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
  13052. 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'
  13053. ],
  13054. [
  13055. 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
  13056. 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'
  13057. ],
  13058. [
  13059. 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
  13060. '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'
  13061. ],
  13062. [
  13063. '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
  13064. 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'
  13065. ],
  13066. [
  13067. '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
  13068. 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'
  13069. ],
  13070. [
  13071. 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
  13072. '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'
  13073. ],
  13074. [
  13075. 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
  13076. '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'
  13077. ],
  13078. [
  13079. 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
  13080. '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'
  13081. ],
  13082. [
  13083. '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
  13084. 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'
  13085. ],
  13086. [
  13087. '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
  13088. '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'
  13089. ],
  13090. [
  13091. 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
  13092. 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'
  13093. ],
  13094. [
  13095. '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
  13096. 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'
  13097. ],
  13098. [
  13099. '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
  13100. '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'
  13101. ],
  13102. [
  13103. '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
  13104. '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'
  13105. ],
  13106. [
  13107. 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
  13108. 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'
  13109. ],
  13110. [
  13111. '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
  13112. '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'
  13113. ],
  13114. [
  13115. '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
  13116. '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'
  13117. ],
  13118. [
  13119. 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
  13120. '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'
  13121. ],
  13122. [
  13123. 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
  13124. 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'
  13125. ]
  13126. ]
  13127. },
  13128. naf: {
  13129. wnd: 7,
  13130. points: [
  13131. [
  13132. 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
  13133. '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'
  13134. ],
  13135. [
  13136. '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
  13137. 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'
  13138. ],
  13139. [
  13140. '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
  13141. '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'
  13142. ],
  13143. [
  13144. 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
  13145. 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'
  13146. ],
  13147. [
  13148. '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
  13149. 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'
  13150. ],
  13151. [
  13152. 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
  13153. 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'
  13154. ],
  13155. [
  13156. 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
  13157. '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'
  13158. ],
  13159. [
  13160. 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
  13161. '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'
  13162. ],
  13163. [
  13164. '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
  13165. '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'
  13166. ],
  13167. [
  13168. '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
  13169. '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'
  13170. ],
  13171. [
  13172. '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
  13173. '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'
  13174. ],
  13175. [
  13176. '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
  13177. '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'
  13178. ],
  13179. [
  13180. 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
  13181. 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'
  13182. ],
  13183. [
  13184. 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
  13185. '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'
  13186. ],
  13187. [
  13188. '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
  13189. 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'
  13190. ],
  13191. [
  13192. '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
  13193. 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'
  13194. ],
  13195. [
  13196. '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
  13197. '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'
  13198. ],
  13199. [
  13200. '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
  13201. '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'
  13202. ],
  13203. [
  13204. '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
  13205. '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'
  13206. ],
  13207. [
  13208. '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
  13209. 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'
  13210. ],
  13211. [
  13212. 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
  13213. 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'
  13214. ],
  13215. [
  13216. '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
  13217. '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'
  13218. ],
  13219. [
  13220. '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
  13221. '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'
  13222. ],
  13223. [
  13224. 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
  13225. 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'
  13226. ],
  13227. [
  13228. '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
  13229. '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'
  13230. ],
  13231. [
  13232. 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
  13233. 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'
  13234. ],
  13235. [
  13236. 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
  13237. 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'
  13238. ],
  13239. [
  13240. '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
  13241. '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'
  13242. ],
  13243. [
  13244. '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
  13245. '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'
  13246. ],
  13247. [
  13248. '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
  13249. '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'
  13250. ],
  13251. [
  13252. 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
  13253. '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'
  13254. ],
  13255. [
  13256. '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
  13257. '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'
  13258. ],
  13259. [
  13260. 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
  13261. '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'
  13262. ],
  13263. [
  13264. '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
  13265. 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'
  13266. ],
  13267. [
  13268. '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
  13269. 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'
  13270. ],
  13271. [
  13272. 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
  13273. 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'
  13274. ],
  13275. [
  13276. '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
  13277. '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'
  13278. ],
  13279. [
  13280. '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
  13281. 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'
  13282. ],
  13283. [
  13284. 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
  13285. 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'
  13286. ],
  13287. [
  13288. '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
  13289. '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'
  13290. ],
  13291. [
  13292. '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
  13293. 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'
  13294. ],
  13295. [
  13296. '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
  13297. '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'
  13298. ],
  13299. [
  13300. '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
  13301. 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'
  13302. ],
  13303. [
  13304. 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
  13305. '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'
  13306. ],
  13307. [
  13308. '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
  13309. '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'
  13310. ],
  13311. [
  13312. '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
  13313. 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'
  13314. ],
  13315. [
  13316. '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
  13317. 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'
  13318. ],
  13319. [
  13320. 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
  13321. 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'
  13322. ],
  13323. [
  13324. 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
  13325. 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'
  13326. ],
  13327. [
  13328. '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
  13329. '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'
  13330. ],
  13331. [
  13332. '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
  13333. '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'
  13334. ],
  13335. [
  13336. 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
  13337. '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'
  13338. ],
  13339. [
  13340. 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
  13341. 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'
  13342. ],
  13343. [
  13344. '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
  13345. '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'
  13346. ],
  13347. [
  13348. '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
  13349. '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'
  13350. ],
  13351. [
  13352. 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
  13353. '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'
  13354. ],
  13355. [
  13356. '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
  13357. '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'
  13358. ],
  13359. [
  13360. 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
  13361. 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'
  13362. ],
  13363. [
  13364. '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
  13365. 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'
  13366. ],
  13367. [
  13368. '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
  13369. '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'
  13370. ],
  13371. [
  13372. 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
  13373. '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'
  13374. ],
  13375. [
  13376. 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
  13377. '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'
  13378. ],
  13379. [
  13380. '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
  13381. '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'
  13382. ],
  13383. [
  13384. '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
  13385. '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'
  13386. ],
  13387. [
  13388. '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
  13389. 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'
  13390. ],
  13391. [
  13392. '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
  13393. 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'
  13394. ],
  13395. [
  13396. '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
  13397. '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'
  13398. ],
  13399. [
  13400. '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
  13401. '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'
  13402. ],
  13403. [
  13404. '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
  13405. '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'
  13406. ],
  13407. [
  13408. '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
  13409. 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'
  13410. ],
  13411. [
  13412. 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
  13413. 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'
  13414. ],
  13415. [
  13416. '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
  13417. 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'
  13418. ],
  13419. [
  13420. 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
  13421. '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'
  13422. ],
  13423. [
  13424. 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
  13425. '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'
  13426. ],
  13427. [
  13428. 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
  13429. '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'
  13430. ],
  13431. [
  13432. 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
  13433. '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'
  13434. ],
  13435. [
  13436. '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
  13437. 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'
  13438. ],
  13439. [
  13440. '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
  13441. '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'
  13442. ],
  13443. [
  13444. '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
  13445. 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'
  13446. ],
  13447. [
  13448. 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
  13449. 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'
  13450. ],
  13451. [
  13452. 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
  13453. '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'
  13454. ],
  13455. [
  13456. 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
  13457. 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'
  13458. ],
  13459. [
  13460. 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
  13461. '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'
  13462. ],
  13463. [
  13464. '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
  13465. '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'
  13466. ],
  13467. [
  13468. 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
  13469. '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'
  13470. ],
  13471. [
  13472. 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
  13473. '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'
  13474. ],
  13475. [
  13476. '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
  13477. '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'
  13478. ],
  13479. [
  13480. '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
  13481. 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'
  13482. ],
  13483. [
  13484. 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
  13485. '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'
  13486. ],
  13487. [
  13488. 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
  13489. '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'
  13490. ],
  13491. [
  13492. 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
  13493. '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'
  13494. ],
  13495. [
  13496. '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
  13497. '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'
  13498. ],
  13499. [
  13500. 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
  13501. 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'
  13502. ],
  13503. [
  13504. '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
  13505. 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'
  13506. ],
  13507. [
  13508. 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
  13509. 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'
  13510. ],
  13511. [
  13512. 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
  13513. '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'
  13514. ],
  13515. [
  13516. '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
  13517. 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'
  13518. ],
  13519. [
  13520. 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
  13521. '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'
  13522. ],
  13523. [
  13524. 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
  13525. '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'
  13526. ],
  13527. [
  13528. 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
  13529. '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'
  13530. ],
  13531. [
  13532. '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
  13533. 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'
  13534. ],
  13535. [
  13536. '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
  13537. 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'
  13538. ],
  13539. [
  13540. 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
  13541. '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'
  13542. ],
  13543. [
  13544. '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
  13545. 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'
  13546. ],
  13547. [
  13548. '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
  13549. '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'
  13550. ],
  13551. [
  13552. '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
  13553. 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'
  13554. ],
  13555. [
  13556. 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
  13557. 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'
  13558. ],
  13559. [
  13560. '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
  13561. 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'
  13562. ],
  13563. [
  13564. '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
  13565. '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'
  13566. ],
  13567. [
  13568. '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
  13569. 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'
  13570. ],
  13571. [
  13572. '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
  13573. '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'
  13574. ],
  13575. [
  13576. 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
  13577. 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'
  13578. ],
  13579. [
  13580. '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
  13581. '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'
  13582. ],
  13583. [
  13584. 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
  13585. '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'
  13586. ],
  13587. [
  13588. '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
  13589. '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'
  13590. ],
  13591. [
  13592. 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
  13593. 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'
  13594. ],
  13595. [
  13596. 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
  13597. '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'
  13598. ],
  13599. [
  13600. 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
  13601. 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'
  13602. ],
  13603. [
  13604. '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
  13605. 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'
  13606. ],
  13607. [
  13608. '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
  13609. '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'
  13610. ],
  13611. [
  13612. '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
  13613. 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'
  13614. ],
  13615. [
  13616. '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
  13617. '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'
  13618. ],
  13619. [
  13620. '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
  13621. '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'
  13622. ],
  13623. [
  13624. '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
  13625. 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'
  13626. ],
  13627. [
  13628. '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
  13629. '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'
  13630. ],
  13631. [
  13632. '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
  13633. '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'
  13634. ],
  13635. [
  13636. '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
  13637. '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'
  13638. ]
  13639. ]
  13640. }
  13641. };
  13642. },{}],84:[function(require,module,exports){
  13643. 'use strict';
  13644. var utils = exports;
  13645. var BN = require('bn.js');
  13646. var minAssert = require('minimalistic-assert');
  13647. var minUtils = require('minimalistic-crypto-utils');
  13648. utils.assert = minAssert;
  13649. utils.toArray = minUtils.toArray;
  13650. utils.zero2 = minUtils.zero2;
  13651. utils.toHex = minUtils.toHex;
  13652. utils.encode = minUtils.encode;
  13653. // Represent num in a w-NAF form
  13654. function getNAF(num, w) {
  13655. var naf = [];
  13656. var ws = 1 << (w + 1);
  13657. var k = num.clone();
  13658. while (k.cmpn(1) >= 0) {
  13659. var z;
  13660. if (k.isOdd()) {
  13661. var mod = k.andln(ws - 1);
  13662. if (mod > (ws >> 1) - 1)
  13663. z = (ws >> 1) - mod;
  13664. else
  13665. z = mod;
  13666. k.isubn(z);
  13667. } else {
  13668. z = 0;
  13669. }
  13670. naf.push(z);
  13671. // Optimization, shift by word if possible
  13672. var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;
  13673. for (var i = 1; i < shift; i++)
  13674. naf.push(0);
  13675. k.iushrn(shift);
  13676. }
  13677. return naf;
  13678. }
  13679. utils.getNAF = getNAF;
  13680. // Represent k1, k2 in a Joint Sparse Form
  13681. function getJSF(k1, k2) {
  13682. var jsf = [
  13683. [],
  13684. []
  13685. ];
  13686. k1 = k1.clone();
  13687. k2 = k2.clone();
  13688. var d1 = 0;
  13689. var d2 = 0;
  13690. while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
  13691. // First phase
  13692. var m14 = (k1.andln(3) + d1) & 3;
  13693. var m24 = (k2.andln(3) + d2) & 3;
  13694. if (m14 === 3)
  13695. m14 = -1;
  13696. if (m24 === 3)
  13697. m24 = -1;
  13698. var u1;
  13699. if ((m14 & 1) === 0) {
  13700. u1 = 0;
  13701. } else {
  13702. var m8 = (k1.andln(7) + d1) & 7;
  13703. if ((m8 === 3 || m8 === 5) && m24 === 2)
  13704. u1 = -m14;
  13705. else
  13706. u1 = m14;
  13707. }
  13708. jsf[0].push(u1);
  13709. var u2;
  13710. if ((m24 & 1) === 0) {
  13711. u2 = 0;
  13712. } else {
  13713. var m8 = (k2.andln(7) + d2) & 7;
  13714. if ((m8 === 3 || m8 === 5) && m14 === 2)
  13715. u2 = -m24;
  13716. else
  13717. u2 = m24;
  13718. }
  13719. jsf[1].push(u2);
  13720. // Second phase
  13721. if (2 * d1 === u1 + 1)
  13722. d1 = 1 - d1;
  13723. if (2 * d2 === u2 + 1)
  13724. d2 = 1 - d2;
  13725. k1.iushrn(1);
  13726. k2.iushrn(1);
  13727. }
  13728. return jsf;
  13729. }
  13730. utils.getJSF = getJSF;
  13731. function cachedProperty(obj, name, computer) {
  13732. var key = '_' + name;
  13733. obj.prototype[name] = function cachedProperty() {
  13734. return this[key] !== undefined ? this[key] :
  13735. this[key] = computer.call(this);
  13736. };
  13737. }
  13738. utils.cachedProperty = cachedProperty;
  13739. function parseBytes(bytes) {
  13740. return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
  13741. bytes;
  13742. }
  13743. utils.parseBytes = parseBytes;
  13744. function intFromLE(bytes) {
  13745. return new BN(bytes, 'hex', 'le');
  13746. }
  13747. utils.intFromLE = intFromLE;
  13748. },{"bn.js":17,"minimalistic-assert":110,"minimalistic-crypto-utils":111}],85:[function(require,module,exports){
  13749. module.exports={
  13750. "_from": "elliptic@^6.0.0",
  13751. "_id": "elliptic@6.4.0",
  13752. "_inBundle": false,
  13753. "_integrity": "sha1-ysmvh2LIWDYYcAPI3+GT5eLq5d8=",
  13754. "_location": "/browserify/elliptic",
  13755. "_phantomChildren": {},
  13756. "_requested": {
  13757. "type": "range",
  13758. "registry": true,
  13759. "raw": "elliptic@^6.0.0",
  13760. "name": "elliptic",
  13761. "escapedName": "elliptic",
  13762. "rawSpec": "^6.0.0",
  13763. "saveSpec": null,
  13764. "fetchSpec": "^6.0.0"
  13765. },
  13766. "_requiredBy": [
  13767. "/browserify/browserify-sign",
  13768. "/browserify/create-ecdh"
  13769. ],
  13770. "_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.4.0.tgz",
  13771. "_shasum": "cac9af8762c85836187003c8dfe193e5e2eae5df",
  13772. "_spec": "elliptic@^6.0.0",
  13773. "_where": "/home/jb/.nvm/versions/node/v8.9.3/lib/node_modules/browserify/node_modules/browserify-sign",
  13774. "author": {
  13775. "name": "Fedor Indutny",
  13776. "email": "fedor@indutny.com"
  13777. },
  13778. "bugs": {
  13779. "url": "https://github.com/indutny/elliptic/issues"
  13780. },
  13781. "bundleDependencies": false,
  13782. "dependencies": {
  13783. "bn.js": "^4.4.0",
  13784. "brorand": "^1.0.1",
  13785. "hash.js": "^1.0.0",
  13786. "hmac-drbg": "^1.0.0",
  13787. "inherits": "^2.0.1",
  13788. "minimalistic-assert": "^1.0.0",
  13789. "minimalistic-crypto-utils": "^1.0.0"
  13790. },
  13791. "deprecated": false,
  13792. "description": "EC cryptography",
  13793. "devDependencies": {
  13794. "brfs": "^1.4.3",
  13795. "coveralls": "^2.11.3",
  13796. "grunt": "^0.4.5",
  13797. "grunt-browserify": "^5.0.0",
  13798. "grunt-cli": "^1.2.0",
  13799. "grunt-contrib-connect": "^1.0.0",
  13800. "grunt-contrib-copy": "^1.0.0",
  13801. "grunt-contrib-uglify": "^1.0.1",
  13802. "grunt-mocha-istanbul": "^3.0.1",
  13803. "grunt-saucelabs": "^8.6.2",
  13804. "istanbul": "^0.4.2",
  13805. "jscs": "^2.9.0",
  13806. "jshint": "^2.6.0",
  13807. "mocha": "^2.1.0"
  13808. },
  13809. "files": [
  13810. "lib"
  13811. ],
  13812. "homepage": "https://github.com/indutny/elliptic",
  13813. "keywords": [
  13814. "EC",
  13815. "Elliptic",
  13816. "curve",
  13817. "Cryptography"
  13818. ],
  13819. "license": "MIT",
  13820. "main": "lib/elliptic.js",
  13821. "name": "elliptic",
  13822. "repository": {
  13823. "type": "git",
  13824. "url": "git+ssh://git@github.com/indutny/elliptic.git"
  13825. },
  13826. "scripts": {
  13827. "jscs": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",
  13828. "jshint": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",
  13829. "lint": "npm run jscs && npm run jshint",
  13830. "test": "npm run lint && npm run unit",
  13831. "unit": "istanbul test _mocha --reporter=spec test/index.js",
  13832. "version": "grunt dist && git add dist/"
  13833. },
  13834. "version": "6.4.0"
  13835. }
  13836. },{}],86:[function(require,module,exports){
  13837. // Copyright Joyent, Inc. and other Node contributors.
  13838. //
  13839. // Permission is hereby granted, free of charge, to any person obtaining a
  13840. // copy of this software and associated documentation files (the
  13841. // "Software"), to deal in the Software without restriction, including
  13842. // without limitation the rights to use, copy, modify, merge, publish,
  13843. // distribute, sublicense, and/or sell copies of the Software, and to permit
  13844. // persons to whom the Software is furnished to do so, subject to the
  13845. // following conditions:
  13846. //
  13847. // The above copyright notice and this permission notice shall be included
  13848. // in all copies or substantial portions of the Software.
  13849. //
  13850. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  13851. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  13852. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  13853. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  13854. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  13855. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  13856. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  13857. function EventEmitter() {
  13858. this._events = this._events || {};
  13859. this._maxListeners = this._maxListeners || undefined;
  13860. }
  13861. module.exports = EventEmitter;
  13862. // Backwards-compat with node 0.10.x
  13863. EventEmitter.EventEmitter = EventEmitter;
  13864. EventEmitter.prototype._events = undefined;
  13865. EventEmitter.prototype._maxListeners = undefined;
  13866. // By default EventEmitters will print a warning if more than 10 listeners are
  13867. // added to it. This is a useful default which helps finding memory leaks.
  13868. EventEmitter.defaultMaxListeners = 10;
  13869. // Obviously not all Emitters should be limited to 10. This function allows
  13870. // that to be increased. Set to zero for unlimited.
  13871. EventEmitter.prototype.setMaxListeners = function(n) {
  13872. if (!isNumber(n) || n < 0 || isNaN(n))
  13873. throw TypeError('n must be a positive number');
  13874. this._maxListeners = n;
  13875. return this;
  13876. };
  13877. EventEmitter.prototype.emit = function(type) {
  13878. var er, handler, len, args, i, listeners;
  13879. if (!this._events)
  13880. this._events = {};
  13881. // If there is no 'error' event listener then throw.
  13882. if (type === 'error') {
  13883. if (!this._events.error ||
  13884. (isObject(this._events.error) && !this._events.error.length)) {
  13885. er = arguments[1];
  13886. if (er instanceof Error) {
  13887. throw er; // Unhandled 'error' event
  13888. } else {
  13889. // At least give some kind of context to the user
  13890. var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
  13891. err.context = er;
  13892. throw err;
  13893. }
  13894. }
  13895. }
  13896. handler = this._events[type];
  13897. if (isUndefined(handler))
  13898. return false;
  13899. if (isFunction(handler)) {
  13900. switch (arguments.length) {
  13901. // fast cases
  13902. case 1:
  13903. handler.call(this);
  13904. break;
  13905. case 2:
  13906. handler.call(this, arguments[1]);
  13907. break;
  13908. case 3:
  13909. handler.call(this, arguments[1], arguments[2]);
  13910. break;
  13911. // slower
  13912. default:
  13913. args = Array.prototype.slice.call(arguments, 1);
  13914. handler.apply(this, args);
  13915. }
  13916. } else if (isObject(handler)) {
  13917. args = Array.prototype.slice.call(arguments, 1);
  13918. listeners = handler.slice();
  13919. len = listeners.length;
  13920. for (i = 0; i < len; i++)
  13921. listeners[i].apply(this, args);
  13922. }
  13923. return true;
  13924. };
  13925. EventEmitter.prototype.addListener = function(type, listener) {
  13926. var m;
  13927. if (!isFunction(listener))
  13928. throw TypeError('listener must be a function');
  13929. if (!this._events)
  13930. this._events = {};
  13931. // To avoid recursion in the case that type === "newListener"! Before
  13932. // adding it to the listeners, first emit "newListener".
  13933. if (this._events.newListener)
  13934. this.emit('newListener', type,
  13935. isFunction(listener.listener) ?
  13936. listener.listener : listener);
  13937. if (!this._events[type])
  13938. // Optimize the case of one listener. Don't need the extra array object.
  13939. this._events[type] = listener;
  13940. else if (isObject(this._events[type]))
  13941. // If we've already got an array, just append.
  13942. this._events[type].push(listener);
  13943. else
  13944. // Adding the second element, need to change to array.
  13945. this._events[type] = [this._events[type], listener];
  13946. // Check for listener leak
  13947. if (isObject(this._events[type]) && !this._events[type].warned) {
  13948. if (!isUndefined(this._maxListeners)) {
  13949. m = this._maxListeners;
  13950. } else {
  13951. m = EventEmitter.defaultMaxListeners;
  13952. }
  13953. if (m && m > 0 && this._events[type].length > m) {
  13954. this._events[type].warned = true;
  13955. console.error('(node) warning: possible EventEmitter memory ' +
  13956. 'leak detected. %d listeners added. ' +
  13957. 'Use emitter.setMaxListeners() to increase limit.',
  13958. this._events[type].length);
  13959. if (typeof console.trace === 'function') {
  13960. // not supported in IE 10
  13961. console.trace();
  13962. }
  13963. }
  13964. }
  13965. return this;
  13966. };
  13967. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  13968. EventEmitter.prototype.once = function(type, listener) {
  13969. if (!isFunction(listener))
  13970. throw TypeError('listener must be a function');
  13971. var fired = false;
  13972. function g() {
  13973. this.removeListener(type, g);
  13974. if (!fired) {
  13975. fired = true;
  13976. listener.apply(this, arguments);
  13977. }
  13978. }
  13979. g.listener = listener;
  13980. this.on(type, g);
  13981. return this;
  13982. };
  13983. // emits a 'removeListener' event iff the listener was removed
  13984. EventEmitter.prototype.removeListener = function(type, listener) {
  13985. var list, position, length, i;
  13986. if (!isFunction(listener))
  13987. throw TypeError('listener must be a function');
  13988. if (!this._events || !this._events[type])
  13989. return this;
  13990. list = this._events[type];
  13991. length = list.length;
  13992. position = -1;
  13993. if (list === listener ||
  13994. (isFunction(list.listener) && list.listener === listener)) {
  13995. delete this._events[type];
  13996. if (this._events.removeListener)
  13997. this.emit('removeListener', type, listener);
  13998. } else if (isObject(list)) {
  13999. for (i = length; i-- > 0;) {
  14000. if (list[i] === listener ||
  14001. (list[i].listener && list[i].listener === listener)) {
  14002. position = i;
  14003. break;
  14004. }
  14005. }
  14006. if (position < 0)
  14007. return this;
  14008. if (list.length === 1) {
  14009. list.length = 0;
  14010. delete this._events[type];
  14011. } else {
  14012. list.splice(position, 1);
  14013. }
  14014. if (this._events.removeListener)
  14015. this.emit('removeListener', type, listener);
  14016. }
  14017. return this;
  14018. };
  14019. EventEmitter.prototype.removeAllListeners = function(type) {
  14020. var key, listeners;
  14021. if (!this._events)
  14022. return this;
  14023. // not listening for removeListener, no need to emit
  14024. if (!this._events.removeListener) {
  14025. if (arguments.length === 0)
  14026. this._events = {};
  14027. else if (this._events[type])
  14028. delete this._events[type];
  14029. return this;
  14030. }
  14031. // emit removeListener for all listeners on all events
  14032. if (arguments.length === 0) {
  14033. for (key in this._events) {
  14034. if (key === 'removeListener') continue;
  14035. this.removeAllListeners(key);
  14036. }
  14037. this.removeAllListeners('removeListener');
  14038. this._events = {};
  14039. return this;
  14040. }
  14041. listeners = this._events[type];
  14042. if (isFunction(listeners)) {
  14043. this.removeListener(type, listeners);
  14044. } else if (listeners) {
  14045. // LIFO order
  14046. while (listeners.length)
  14047. this.removeListener(type, listeners[listeners.length - 1]);
  14048. }
  14049. delete this._events[type];
  14050. return this;
  14051. };
  14052. EventEmitter.prototype.listeners = function(type) {
  14053. var ret;
  14054. if (!this._events || !this._events[type])
  14055. ret = [];
  14056. else if (isFunction(this._events[type]))
  14057. ret = [this._events[type]];
  14058. else
  14059. ret = this._events[type].slice();
  14060. return ret;
  14061. };
  14062. EventEmitter.prototype.listenerCount = function(type) {
  14063. if (this._events) {
  14064. var evlistener = this._events[type];
  14065. if (isFunction(evlistener))
  14066. return 1;
  14067. else if (evlistener)
  14068. return evlistener.length;
  14069. }
  14070. return 0;
  14071. };
  14072. EventEmitter.listenerCount = function(emitter, type) {
  14073. return emitter.listenerCount(type);
  14074. };
  14075. function isFunction(arg) {
  14076. return typeof arg === 'function';
  14077. }
  14078. function isNumber(arg) {
  14079. return typeof arg === 'number';
  14080. }
  14081. function isObject(arg) {
  14082. return typeof arg === 'object' && arg !== null;
  14083. }
  14084. function isUndefined(arg) {
  14085. return arg === void 0;
  14086. }
  14087. },{}],87:[function(require,module,exports){
  14088. var Buffer = require('safe-buffer').Buffer
  14089. var MD5 = require('md5.js')
  14090. /* eslint-disable camelcase */
  14091. function EVP_BytesToKey (password, salt, keyBits, ivLen) {
  14092. if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary')
  14093. if (salt) {
  14094. if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary')
  14095. if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length')
  14096. }
  14097. var keyLen = keyBits / 8
  14098. var key = Buffer.alloc(keyLen)
  14099. var iv = Buffer.alloc(ivLen || 0)
  14100. var tmp = Buffer.alloc(0)
  14101. while (keyLen > 0 || ivLen > 0) {
  14102. var hash = new MD5()
  14103. hash.update(tmp)
  14104. hash.update(password)
  14105. if (salt) hash.update(salt)
  14106. tmp = hash.digest()
  14107. var used = 0
  14108. if (keyLen > 0) {
  14109. var keyStart = key.length - keyLen
  14110. used = Math.min(keyLen, tmp.length)
  14111. tmp.copy(key, keyStart, 0, used)
  14112. keyLen -= used
  14113. }
  14114. if (used < tmp.length && ivLen > 0) {
  14115. var ivStart = iv.length - ivLen
  14116. var length = Math.min(ivLen, tmp.length - used)
  14117. tmp.copy(iv, ivStart, used, used + length)
  14118. ivLen -= length
  14119. }
  14120. }
  14121. tmp.fill(0)
  14122. return { key: key, iv: iv }
  14123. }
  14124. module.exports = EVP_BytesToKey
  14125. },{"md5.js":107,"safe-buffer":157}],88:[function(require,module,exports){
  14126. (function (Buffer){
  14127. 'use strict'
  14128. var Transform = require('stream').Transform
  14129. var inherits = require('inherits')
  14130. function HashBase (blockSize) {
  14131. Transform.call(this)
  14132. this._block = new Buffer(blockSize)
  14133. this._blockSize = blockSize
  14134. this._blockOffset = 0
  14135. this._length = [0, 0, 0, 0]
  14136. this._finalized = false
  14137. }
  14138. inherits(HashBase, Transform)
  14139. HashBase.prototype._transform = function (chunk, encoding, callback) {
  14140. var error = null
  14141. try {
  14142. if (encoding !== 'buffer') chunk = new Buffer(chunk, encoding)
  14143. this.update(chunk)
  14144. } catch (err) {
  14145. error = err
  14146. }
  14147. callback(error)
  14148. }
  14149. HashBase.prototype._flush = function (callback) {
  14150. var error = null
  14151. try {
  14152. this.push(this._digest())
  14153. } catch (err) {
  14154. error = err
  14155. }
  14156. callback(error)
  14157. }
  14158. HashBase.prototype.update = function (data, encoding) {
  14159. if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')
  14160. if (this._finalized) throw new Error('Digest already called')
  14161. if (!Buffer.isBuffer(data)) data = new Buffer(data, encoding || 'binary')
  14162. // consume data
  14163. var block = this._block
  14164. var offset = 0
  14165. while (this._blockOffset + data.length - offset >= this._blockSize) {
  14166. for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
  14167. this._update()
  14168. this._blockOffset = 0
  14169. }
  14170. while (offset < data.length) block[this._blockOffset++] = data[offset++]
  14171. // update length
  14172. for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
  14173. this._length[j] += carry
  14174. carry = (this._length[j] / 0x0100000000) | 0
  14175. if (carry > 0) this._length[j] -= 0x0100000000 * carry
  14176. }
  14177. return this
  14178. }
  14179. HashBase.prototype._update = function (data) {
  14180. throw new Error('_update is not implemented')
  14181. }
  14182. HashBase.prototype.digest = function (encoding) {
  14183. if (this._finalized) throw new Error('Digest already called')
  14184. this._finalized = true
  14185. var digest = this._digest()
  14186. if (encoding !== undefined) digest = digest.toString(encoding)
  14187. return digest
  14188. }
  14189. HashBase.prototype._digest = function () {
  14190. throw new Error('_digest is not implemented')
  14191. }
  14192. module.exports = HashBase
  14193. }).call(this,require("buffer").Buffer)
  14194. },{"buffer":50,"inherits":104,"stream":166}],89:[function(require,module,exports){
  14195. var hash = exports;
  14196. hash.utils = require('./hash/utils');
  14197. hash.common = require('./hash/common');
  14198. hash.sha = require('./hash/sha');
  14199. hash.ripemd = require('./hash/ripemd');
  14200. hash.hmac = require('./hash/hmac');
  14201. // Proxy hash functions to the main object
  14202. hash.sha1 = hash.sha.sha1;
  14203. hash.sha256 = hash.sha.sha256;
  14204. hash.sha224 = hash.sha.sha224;
  14205. hash.sha384 = hash.sha.sha384;
  14206. hash.sha512 = hash.sha.sha512;
  14207. hash.ripemd160 = hash.ripemd.ripemd160;
  14208. },{"./hash/common":90,"./hash/hmac":91,"./hash/ripemd":92,"./hash/sha":93,"./hash/utils":100}],90:[function(require,module,exports){
  14209. 'use strict';
  14210. var utils = require('./utils');
  14211. var assert = require('minimalistic-assert');
  14212. function BlockHash() {
  14213. this.pending = null;
  14214. this.pendingTotal = 0;
  14215. this.blockSize = this.constructor.blockSize;
  14216. this.outSize = this.constructor.outSize;
  14217. this.hmacStrength = this.constructor.hmacStrength;
  14218. this.padLength = this.constructor.padLength / 8;
  14219. this.endian = 'big';
  14220. this._delta8 = this.blockSize / 8;
  14221. this._delta32 = this.blockSize / 32;
  14222. }
  14223. exports.BlockHash = BlockHash;
  14224. BlockHash.prototype.update = function update(msg, enc) {
  14225. // Convert message to array, pad it, and join into 32bit blocks
  14226. msg = utils.toArray(msg, enc);
  14227. if (!this.pending)
  14228. this.pending = msg;
  14229. else
  14230. this.pending = this.pending.concat(msg);
  14231. this.pendingTotal += msg.length;
  14232. // Enough data, try updating
  14233. if (this.pending.length >= this._delta8) {
  14234. msg = this.pending;
  14235. // Process pending data in blocks
  14236. var r = msg.length % this._delta8;
  14237. this.pending = msg.slice(msg.length - r, msg.length);
  14238. if (this.pending.length === 0)
  14239. this.pending = null;
  14240. msg = utils.join32(msg, 0, msg.length - r, this.endian);
  14241. for (var i = 0; i < msg.length; i += this._delta32)
  14242. this._update(msg, i, i + this._delta32);
  14243. }
  14244. return this;
  14245. };
  14246. BlockHash.prototype.digest = function digest(enc) {
  14247. this.update(this._pad());
  14248. assert(this.pending === null);
  14249. return this._digest(enc);
  14250. };
  14251. BlockHash.prototype._pad = function pad() {
  14252. var len = this.pendingTotal;
  14253. var bytes = this._delta8;
  14254. var k = bytes - ((len + this.padLength) % bytes);
  14255. var res = new Array(k + this.padLength);
  14256. res[0] = 0x80;
  14257. for (var i = 1; i < k; i++)
  14258. res[i] = 0;
  14259. // Append length
  14260. len <<= 3;
  14261. if (this.endian === 'big') {
  14262. for (var t = 8; t < this.padLength; t++)
  14263. res[i++] = 0;
  14264. res[i++] = 0;
  14265. res[i++] = 0;
  14266. res[i++] = 0;
  14267. res[i++] = 0;
  14268. res[i++] = (len >>> 24) & 0xff;
  14269. res[i++] = (len >>> 16) & 0xff;
  14270. res[i++] = (len >>> 8) & 0xff;
  14271. res[i++] = len & 0xff;
  14272. } else {
  14273. res[i++] = len & 0xff;
  14274. res[i++] = (len >>> 8) & 0xff;
  14275. res[i++] = (len >>> 16) & 0xff;
  14276. res[i++] = (len >>> 24) & 0xff;
  14277. res[i++] = 0;
  14278. res[i++] = 0;
  14279. res[i++] = 0;
  14280. res[i++] = 0;
  14281. for (t = 8; t < this.padLength; t++)
  14282. res[i++] = 0;
  14283. }
  14284. return res;
  14285. };
  14286. },{"./utils":100,"minimalistic-assert":110}],91:[function(require,module,exports){
  14287. 'use strict';
  14288. var utils = require('./utils');
  14289. var assert = require('minimalistic-assert');
  14290. function Hmac(hash, key, enc) {
  14291. if (!(this instanceof Hmac))
  14292. return new Hmac(hash, key, enc);
  14293. this.Hash = hash;
  14294. this.blockSize = hash.blockSize / 8;
  14295. this.outSize = hash.outSize / 8;
  14296. this.inner = null;
  14297. this.outer = null;
  14298. this._init(utils.toArray(key, enc));
  14299. }
  14300. module.exports = Hmac;
  14301. Hmac.prototype._init = function init(key) {
  14302. // Shorten key, if needed
  14303. if (key.length > this.blockSize)
  14304. key = new this.Hash().update(key).digest();
  14305. assert(key.length <= this.blockSize);
  14306. // Add padding to key
  14307. for (var i = key.length; i < this.blockSize; i++)
  14308. key.push(0);
  14309. for (i = 0; i < key.length; i++)
  14310. key[i] ^= 0x36;
  14311. this.inner = new this.Hash().update(key);
  14312. // 0x36 ^ 0x5c = 0x6a
  14313. for (i = 0; i < key.length; i++)
  14314. key[i] ^= 0x6a;
  14315. this.outer = new this.Hash().update(key);
  14316. };
  14317. Hmac.prototype.update = function update(msg, enc) {
  14318. this.inner.update(msg, enc);
  14319. return this;
  14320. };
  14321. Hmac.prototype.digest = function digest(enc) {
  14322. this.outer.update(this.inner.digest());
  14323. return this.outer.digest(enc);
  14324. };
  14325. },{"./utils":100,"minimalistic-assert":110}],92:[function(require,module,exports){
  14326. 'use strict';
  14327. var utils = require('./utils');
  14328. var common = require('./common');
  14329. var rotl32 = utils.rotl32;
  14330. var sum32 = utils.sum32;
  14331. var sum32_3 = utils.sum32_3;
  14332. var sum32_4 = utils.sum32_4;
  14333. var BlockHash = common.BlockHash;
  14334. function RIPEMD160() {
  14335. if (!(this instanceof RIPEMD160))
  14336. return new RIPEMD160();
  14337. BlockHash.call(this);
  14338. this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
  14339. this.endian = 'little';
  14340. }
  14341. utils.inherits(RIPEMD160, BlockHash);
  14342. exports.ripemd160 = RIPEMD160;
  14343. RIPEMD160.blockSize = 512;
  14344. RIPEMD160.outSize = 160;
  14345. RIPEMD160.hmacStrength = 192;
  14346. RIPEMD160.padLength = 64;
  14347. RIPEMD160.prototype._update = function update(msg, start) {
  14348. var A = this.h[0];
  14349. var B = this.h[1];
  14350. var C = this.h[2];
  14351. var D = this.h[3];
  14352. var E = this.h[4];
  14353. var Ah = A;
  14354. var Bh = B;
  14355. var Ch = C;
  14356. var Dh = D;
  14357. var Eh = E;
  14358. for (var j = 0; j < 80; j++) {
  14359. var T = sum32(
  14360. rotl32(
  14361. sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),
  14362. s[j]),
  14363. E);
  14364. A = E;
  14365. E = D;
  14366. D = rotl32(C, 10);
  14367. C = B;
  14368. B = T;
  14369. T = sum32(
  14370. rotl32(
  14371. sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
  14372. sh[j]),
  14373. Eh);
  14374. Ah = Eh;
  14375. Eh = Dh;
  14376. Dh = rotl32(Ch, 10);
  14377. Ch = Bh;
  14378. Bh = T;
  14379. }
  14380. T = sum32_3(this.h[1], C, Dh);
  14381. this.h[1] = sum32_3(this.h[2], D, Eh);
  14382. this.h[2] = sum32_3(this.h[3], E, Ah);
  14383. this.h[3] = sum32_3(this.h[4], A, Bh);
  14384. this.h[4] = sum32_3(this.h[0], B, Ch);
  14385. this.h[0] = T;
  14386. };
  14387. RIPEMD160.prototype._digest = function digest(enc) {
  14388. if (enc === 'hex')
  14389. return utils.toHex32(this.h, 'little');
  14390. else
  14391. return utils.split32(this.h, 'little');
  14392. };
  14393. function f(j, x, y, z) {
  14394. if (j <= 15)
  14395. return x ^ y ^ z;
  14396. else if (j <= 31)
  14397. return (x & y) | ((~x) & z);
  14398. else if (j <= 47)
  14399. return (x | (~y)) ^ z;
  14400. else if (j <= 63)
  14401. return (x & z) | (y & (~z));
  14402. else
  14403. return x ^ (y | (~z));
  14404. }
  14405. function K(j) {
  14406. if (j <= 15)
  14407. return 0x00000000;
  14408. else if (j <= 31)
  14409. return 0x5a827999;
  14410. else if (j <= 47)
  14411. return 0x6ed9eba1;
  14412. else if (j <= 63)
  14413. return 0x8f1bbcdc;
  14414. else
  14415. return 0xa953fd4e;
  14416. }
  14417. function Kh(j) {
  14418. if (j <= 15)
  14419. return 0x50a28be6;
  14420. else if (j <= 31)
  14421. return 0x5c4dd124;
  14422. else if (j <= 47)
  14423. return 0x6d703ef3;
  14424. else if (j <= 63)
  14425. return 0x7a6d76e9;
  14426. else
  14427. return 0x00000000;
  14428. }
  14429. var r = [
  14430. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
  14431. 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
  14432. 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
  14433. 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
  14434. 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
  14435. ];
  14436. var rh = [
  14437. 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
  14438. 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
  14439. 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
  14440. 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
  14441. 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
  14442. ];
  14443. var s = [
  14444. 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
  14445. 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
  14446. 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
  14447. 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
  14448. 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
  14449. ];
  14450. var sh = [
  14451. 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
  14452. 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
  14453. 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
  14454. 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
  14455. 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
  14456. ];
  14457. },{"./common":90,"./utils":100}],93:[function(require,module,exports){
  14458. 'use strict';
  14459. exports.sha1 = require('./sha/1');
  14460. exports.sha224 = require('./sha/224');
  14461. exports.sha256 = require('./sha/256');
  14462. exports.sha384 = require('./sha/384');
  14463. exports.sha512 = require('./sha/512');
  14464. },{"./sha/1":94,"./sha/224":95,"./sha/256":96,"./sha/384":97,"./sha/512":98}],94:[function(require,module,exports){
  14465. 'use strict';
  14466. var utils = require('../utils');
  14467. var common = require('../common');
  14468. var shaCommon = require('./common');
  14469. var rotl32 = utils.rotl32;
  14470. var sum32 = utils.sum32;
  14471. var sum32_5 = utils.sum32_5;
  14472. var ft_1 = shaCommon.ft_1;
  14473. var BlockHash = common.BlockHash;
  14474. var sha1_K = [
  14475. 0x5A827999, 0x6ED9EBA1,
  14476. 0x8F1BBCDC, 0xCA62C1D6
  14477. ];
  14478. function SHA1() {
  14479. if (!(this instanceof SHA1))
  14480. return new SHA1();
  14481. BlockHash.call(this);
  14482. this.h = [
  14483. 0x67452301, 0xefcdab89, 0x98badcfe,
  14484. 0x10325476, 0xc3d2e1f0 ];
  14485. this.W = new Array(80);
  14486. }
  14487. utils.inherits(SHA1, BlockHash);
  14488. module.exports = SHA1;
  14489. SHA1.blockSize = 512;
  14490. SHA1.outSize = 160;
  14491. SHA1.hmacStrength = 80;
  14492. SHA1.padLength = 64;
  14493. SHA1.prototype._update = function _update(msg, start) {
  14494. var W = this.W;
  14495. for (var i = 0; i < 16; i++)
  14496. W[i] = msg[start + i];
  14497. for(; i < W.length; i++)
  14498. W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
  14499. var a = this.h[0];
  14500. var b = this.h[1];
  14501. var c = this.h[2];
  14502. var d = this.h[3];
  14503. var e = this.h[4];
  14504. for (i = 0; i < W.length; i++) {
  14505. var s = ~~(i / 20);
  14506. var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);
  14507. e = d;
  14508. d = c;
  14509. c = rotl32(b, 30);
  14510. b = a;
  14511. a = t;
  14512. }
  14513. this.h[0] = sum32(this.h[0], a);
  14514. this.h[1] = sum32(this.h[1], b);
  14515. this.h[2] = sum32(this.h[2], c);
  14516. this.h[3] = sum32(this.h[3], d);
  14517. this.h[4] = sum32(this.h[4], e);
  14518. };
  14519. SHA1.prototype._digest = function digest(enc) {
  14520. if (enc === 'hex')
  14521. return utils.toHex32(this.h, 'big');
  14522. else
  14523. return utils.split32(this.h, 'big');
  14524. };
  14525. },{"../common":90,"../utils":100,"./common":99}],95:[function(require,module,exports){
  14526. 'use strict';
  14527. var utils = require('../utils');
  14528. var SHA256 = require('./256');
  14529. function SHA224() {
  14530. if (!(this instanceof SHA224))
  14531. return new SHA224();
  14532. SHA256.call(this);
  14533. this.h = [
  14534. 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
  14535. 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
  14536. }
  14537. utils.inherits(SHA224, SHA256);
  14538. module.exports = SHA224;
  14539. SHA224.blockSize = 512;
  14540. SHA224.outSize = 224;
  14541. SHA224.hmacStrength = 192;
  14542. SHA224.padLength = 64;
  14543. SHA224.prototype._digest = function digest(enc) {
  14544. // Just truncate output
  14545. if (enc === 'hex')
  14546. return utils.toHex32(this.h.slice(0, 7), 'big');
  14547. else
  14548. return utils.split32(this.h.slice(0, 7), 'big');
  14549. };
  14550. },{"../utils":100,"./256":96}],96:[function(require,module,exports){
  14551. 'use strict';
  14552. var utils = require('../utils');
  14553. var common = require('../common');
  14554. var shaCommon = require('./common');
  14555. var assert = require('minimalistic-assert');
  14556. var sum32 = utils.sum32;
  14557. var sum32_4 = utils.sum32_4;
  14558. var sum32_5 = utils.sum32_5;
  14559. var ch32 = shaCommon.ch32;
  14560. var maj32 = shaCommon.maj32;
  14561. var s0_256 = shaCommon.s0_256;
  14562. var s1_256 = shaCommon.s1_256;
  14563. var g0_256 = shaCommon.g0_256;
  14564. var g1_256 = shaCommon.g1_256;
  14565. var BlockHash = common.BlockHash;
  14566. var sha256_K = [
  14567. 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
  14568. 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
  14569. 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
  14570. 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
  14571. 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
  14572. 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  14573. 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
  14574. 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
  14575. 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
  14576. 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
  14577. 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
  14578. 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  14579. 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
  14580. 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
  14581. 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
  14582. 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
  14583. ];
  14584. function SHA256() {
  14585. if (!(this instanceof SHA256))
  14586. return new SHA256();
  14587. BlockHash.call(this);
  14588. this.h = [
  14589. 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
  14590. 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
  14591. ];
  14592. this.k = sha256_K;
  14593. this.W = new Array(64);
  14594. }
  14595. utils.inherits(SHA256, BlockHash);
  14596. module.exports = SHA256;
  14597. SHA256.blockSize = 512;
  14598. SHA256.outSize = 256;
  14599. SHA256.hmacStrength = 192;
  14600. SHA256.padLength = 64;
  14601. SHA256.prototype._update = function _update(msg, start) {
  14602. var W = this.W;
  14603. for (var i = 0; i < 16; i++)
  14604. W[i] = msg[start + i];
  14605. for (; i < W.length; i++)
  14606. W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);
  14607. var a = this.h[0];
  14608. var b = this.h[1];
  14609. var c = this.h[2];
  14610. var d = this.h[3];
  14611. var e = this.h[4];
  14612. var f = this.h[5];
  14613. var g = this.h[6];
  14614. var h = this.h[7];
  14615. assert(this.k.length === W.length);
  14616. for (i = 0; i < W.length; i++) {
  14617. var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);
  14618. var T2 = sum32(s0_256(a), maj32(a, b, c));
  14619. h = g;
  14620. g = f;
  14621. f = e;
  14622. e = sum32(d, T1);
  14623. d = c;
  14624. c = b;
  14625. b = a;
  14626. a = sum32(T1, T2);
  14627. }
  14628. this.h[0] = sum32(this.h[0], a);
  14629. this.h[1] = sum32(this.h[1], b);
  14630. this.h[2] = sum32(this.h[2], c);
  14631. this.h[3] = sum32(this.h[3], d);
  14632. this.h[4] = sum32(this.h[4], e);
  14633. this.h[5] = sum32(this.h[5], f);
  14634. this.h[6] = sum32(this.h[6], g);
  14635. this.h[7] = sum32(this.h[7], h);
  14636. };
  14637. SHA256.prototype._digest = function digest(enc) {
  14638. if (enc === 'hex')
  14639. return utils.toHex32(this.h, 'big');
  14640. else
  14641. return utils.split32(this.h, 'big');
  14642. };
  14643. },{"../common":90,"../utils":100,"./common":99,"minimalistic-assert":110}],97:[function(require,module,exports){
  14644. 'use strict';
  14645. var utils = require('../utils');
  14646. var SHA512 = require('./512');
  14647. function SHA384() {
  14648. if (!(this instanceof SHA384))
  14649. return new SHA384();
  14650. SHA512.call(this);
  14651. this.h = [
  14652. 0xcbbb9d5d, 0xc1059ed8,
  14653. 0x629a292a, 0x367cd507,
  14654. 0x9159015a, 0x3070dd17,
  14655. 0x152fecd8, 0xf70e5939,
  14656. 0x67332667, 0xffc00b31,
  14657. 0x8eb44a87, 0x68581511,
  14658. 0xdb0c2e0d, 0x64f98fa7,
  14659. 0x47b5481d, 0xbefa4fa4 ];
  14660. }
  14661. utils.inherits(SHA384, SHA512);
  14662. module.exports = SHA384;
  14663. SHA384.blockSize = 1024;
  14664. SHA384.outSize = 384;
  14665. SHA384.hmacStrength = 192;
  14666. SHA384.padLength = 128;
  14667. SHA384.prototype._digest = function digest(enc) {
  14668. if (enc === 'hex')
  14669. return utils.toHex32(this.h.slice(0, 12), 'big');
  14670. else
  14671. return utils.split32(this.h.slice(0, 12), 'big');
  14672. };
  14673. },{"../utils":100,"./512":98}],98:[function(require,module,exports){
  14674. 'use strict';
  14675. var utils = require('../utils');
  14676. var common = require('../common');
  14677. var assert = require('minimalistic-assert');
  14678. var rotr64_hi = utils.rotr64_hi;
  14679. var rotr64_lo = utils.rotr64_lo;
  14680. var shr64_hi = utils.shr64_hi;
  14681. var shr64_lo = utils.shr64_lo;
  14682. var sum64 = utils.sum64;
  14683. var sum64_hi = utils.sum64_hi;
  14684. var sum64_lo = utils.sum64_lo;
  14685. var sum64_4_hi = utils.sum64_4_hi;
  14686. var sum64_4_lo = utils.sum64_4_lo;
  14687. var sum64_5_hi = utils.sum64_5_hi;
  14688. var sum64_5_lo = utils.sum64_5_lo;
  14689. var BlockHash = common.BlockHash;
  14690. var sha512_K = [
  14691. 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
  14692. 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
  14693. 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
  14694. 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
  14695. 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
  14696. 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
  14697. 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
  14698. 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
  14699. 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
  14700. 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
  14701. 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
  14702. 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
  14703. 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
  14704. 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
  14705. 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
  14706. 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
  14707. 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
  14708. 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
  14709. 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
  14710. 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
  14711. 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
  14712. 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
  14713. 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
  14714. 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
  14715. 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
  14716. 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
  14717. 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
  14718. 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
  14719. 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
  14720. 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
  14721. 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
  14722. 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
  14723. 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
  14724. 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
  14725. 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
  14726. 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
  14727. 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
  14728. 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
  14729. 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
  14730. 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
  14731. ];
  14732. function SHA512() {
  14733. if (!(this instanceof SHA512))
  14734. return new SHA512();
  14735. BlockHash.call(this);
  14736. this.h = [
  14737. 0x6a09e667, 0xf3bcc908,
  14738. 0xbb67ae85, 0x84caa73b,
  14739. 0x3c6ef372, 0xfe94f82b,
  14740. 0xa54ff53a, 0x5f1d36f1,
  14741. 0x510e527f, 0xade682d1,
  14742. 0x9b05688c, 0x2b3e6c1f,
  14743. 0x1f83d9ab, 0xfb41bd6b,
  14744. 0x5be0cd19, 0x137e2179 ];
  14745. this.k = sha512_K;
  14746. this.W = new Array(160);
  14747. }
  14748. utils.inherits(SHA512, BlockHash);
  14749. module.exports = SHA512;
  14750. SHA512.blockSize = 1024;
  14751. SHA512.outSize = 512;
  14752. SHA512.hmacStrength = 192;
  14753. SHA512.padLength = 128;
  14754. SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
  14755. var W = this.W;
  14756. // 32 x 32bit words
  14757. for (var i = 0; i < 32; i++)
  14758. W[i] = msg[start + i];
  14759. for (; i < W.length; i += 2) {
  14760. var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
  14761. var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
  14762. var c1_hi = W[i - 14]; // i - 7
  14763. var c1_lo = W[i - 13];
  14764. var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
  14765. var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
  14766. var c3_hi = W[i - 32]; // i - 16
  14767. var c3_lo = W[i - 31];
  14768. W[i] = sum64_4_hi(
  14769. c0_hi, c0_lo,
  14770. c1_hi, c1_lo,
  14771. c2_hi, c2_lo,
  14772. c3_hi, c3_lo);
  14773. W[i + 1] = sum64_4_lo(
  14774. c0_hi, c0_lo,
  14775. c1_hi, c1_lo,
  14776. c2_hi, c2_lo,
  14777. c3_hi, c3_lo);
  14778. }
  14779. };
  14780. SHA512.prototype._update = function _update(msg, start) {
  14781. this._prepareBlock(msg, start);
  14782. var W = this.W;
  14783. var ah = this.h[0];
  14784. var al = this.h[1];
  14785. var bh = this.h[2];
  14786. var bl = this.h[3];
  14787. var ch = this.h[4];
  14788. var cl = this.h[5];
  14789. var dh = this.h[6];
  14790. var dl = this.h[7];
  14791. var eh = this.h[8];
  14792. var el = this.h[9];
  14793. var fh = this.h[10];
  14794. var fl = this.h[11];
  14795. var gh = this.h[12];
  14796. var gl = this.h[13];
  14797. var hh = this.h[14];
  14798. var hl = this.h[15];
  14799. assert(this.k.length === W.length);
  14800. for (var i = 0; i < W.length; i += 2) {
  14801. var c0_hi = hh;
  14802. var c0_lo = hl;
  14803. var c1_hi = s1_512_hi(eh, el);
  14804. var c1_lo = s1_512_lo(eh, el);
  14805. var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
  14806. var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
  14807. var c3_hi = this.k[i];
  14808. var c3_lo = this.k[i + 1];
  14809. var c4_hi = W[i];
  14810. var c4_lo = W[i + 1];
  14811. var T1_hi = sum64_5_hi(
  14812. c0_hi, c0_lo,
  14813. c1_hi, c1_lo,
  14814. c2_hi, c2_lo,
  14815. c3_hi, c3_lo,
  14816. c4_hi, c4_lo);
  14817. var T1_lo = sum64_5_lo(
  14818. c0_hi, c0_lo,
  14819. c1_hi, c1_lo,
  14820. c2_hi, c2_lo,
  14821. c3_hi, c3_lo,
  14822. c4_hi, c4_lo);
  14823. c0_hi = s0_512_hi(ah, al);
  14824. c0_lo = s0_512_lo(ah, al);
  14825. c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
  14826. c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
  14827. var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);
  14828. var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);
  14829. hh = gh;
  14830. hl = gl;
  14831. gh = fh;
  14832. gl = fl;
  14833. fh = eh;
  14834. fl = el;
  14835. eh = sum64_hi(dh, dl, T1_hi, T1_lo);
  14836. el = sum64_lo(dl, dl, T1_hi, T1_lo);
  14837. dh = ch;
  14838. dl = cl;
  14839. ch = bh;
  14840. cl = bl;
  14841. bh = ah;
  14842. bl = al;
  14843. ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);
  14844. al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
  14845. }
  14846. sum64(this.h, 0, ah, al);
  14847. sum64(this.h, 2, bh, bl);
  14848. sum64(this.h, 4, ch, cl);
  14849. sum64(this.h, 6, dh, dl);
  14850. sum64(this.h, 8, eh, el);
  14851. sum64(this.h, 10, fh, fl);
  14852. sum64(this.h, 12, gh, gl);
  14853. sum64(this.h, 14, hh, hl);
  14854. };
  14855. SHA512.prototype._digest = function digest(enc) {
  14856. if (enc === 'hex')
  14857. return utils.toHex32(this.h, 'big');
  14858. else
  14859. return utils.split32(this.h, 'big');
  14860. };
  14861. function ch64_hi(xh, xl, yh, yl, zh) {
  14862. var r = (xh & yh) ^ ((~xh) & zh);
  14863. if (r < 0)
  14864. r += 0x100000000;
  14865. return r;
  14866. }
  14867. function ch64_lo(xh, xl, yh, yl, zh, zl) {
  14868. var r = (xl & yl) ^ ((~xl) & zl);
  14869. if (r < 0)
  14870. r += 0x100000000;
  14871. return r;
  14872. }
  14873. function maj64_hi(xh, xl, yh, yl, zh) {
  14874. var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
  14875. if (r < 0)
  14876. r += 0x100000000;
  14877. return r;
  14878. }
  14879. function maj64_lo(xh, xl, yh, yl, zh, zl) {
  14880. var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
  14881. if (r < 0)
  14882. r += 0x100000000;
  14883. return r;
  14884. }
  14885. function s0_512_hi(xh, xl) {
  14886. var c0_hi = rotr64_hi(xh, xl, 28);
  14887. var c1_hi = rotr64_hi(xl, xh, 2); // 34
  14888. var c2_hi = rotr64_hi(xl, xh, 7); // 39
  14889. var r = c0_hi ^ c1_hi ^ c2_hi;
  14890. if (r < 0)
  14891. r += 0x100000000;
  14892. return r;
  14893. }
  14894. function s0_512_lo(xh, xl) {
  14895. var c0_lo = rotr64_lo(xh, xl, 28);
  14896. var c1_lo = rotr64_lo(xl, xh, 2); // 34
  14897. var c2_lo = rotr64_lo(xl, xh, 7); // 39
  14898. var r = c0_lo ^ c1_lo ^ c2_lo;
  14899. if (r < 0)
  14900. r += 0x100000000;
  14901. return r;
  14902. }
  14903. function s1_512_hi(xh, xl) {
  14904. var c0_hi = rotr64_hi(xh, xl, 14);
  14905. var c1_hi = rotr64_hi(xh, xl, 18);
  14906. var c2_hi = rotr64_hi(xl, xh, 9); // 41
  14907. var r = c0_hi ^ c1_hi ^ c2_hi;
  14908. if (r < 0)
  14909. r += 0x100000000;
  14910. return r;
  14911. }
  14912. function s1_512_lo(xh, xl) {
  14913. var c0_lo = rotr64_lo(xh, xl, 14);
  14914. var c1_lo = rotr64_lo(xh, xl, 18);
  14915. var c2_lo = rotr64_lo(xl, xh, 9); // 41
  14916. var r = c0_lo ^ c1_lo ^ c2_lo;
  14917. if (r < 0)
  14918. r += 0x100000000;
  14919. return r;
  14920. }
  14921. function g0_512_hi(xh, xl) {
  14922. var c0_hi = rotr64_hi(xh, xl, 1);
  14923. var c1_hi = rotr64_hi(xh, xl, 8);
  14924. var c2_hi = shr64_hi(xh, xl, 7);
  14925. var r = c0_hi ^ c1_hi ^ c2_hi;
  14926. if (r < 0)
  14927. r += 0x100000000;
  14928. return r;
  14929. }
  14930. function g0_512_lo(xh, xl) {
  14931. var c0_lo = rotr64_lo(xh, xl, 1);
  14932. var c1_lo = rotr64_lo(xh, xl, 8);
  14933. var c2_lo = shr64_lo(xh, xl, 7);
  14934. var r = c0_lo ^ c1_lo ^ c2_lo;
  14935. if (r < 0)
  14936. r += 0x100000000;
  14937. return r;
  14938. }
  14939. function g1_512_hi(xh, xl) {
  14940. var c0_hi = rotr64_hi(xh, xl, 19);
  14941. var c1_hi = rotr64_hi(xl, xh, 29); // 61
  14942. var c2_hi = shr64_hi(xh, xl, 6);
  14943. var r = c0_hi ^ c1_hi ^ c2_hi;
  14944. if (r < 0)
  14945. r += 0x100000000;
  14946. return r;
  14947. }
  14948. function g1_512_lo(xh, xl) {
  14949. var c0_lo = rotr64_lo(xh, xl, 19);
  14950. var c1_lo = rotr64_lo(xl, xh, 29); // 61
  14951. var c2_lo = shr64_lo(xh, xl, 6);
  14952. var r = c0_lo ^ c1_lo ^ c2_lo;
  14953. if (r < 0)
  14954. r += 0x100000000;
  14955. return r;
  14956. }
  14957. },{"../common":90,"../utils":100,"minimalistic-assert":110}],99:[function(require,module,exports){
  14958. 'use strict';
  14959. var utils = require('../utils');
  14960. var rotr32 = utils.rotr32;
  14961. function ft_1(s, x, y, z) {
  14962. if (s === 0)
  14963. return ch32(x, y, z);
  14964. if (s === 1 || s === 3)
  14965. return p32(x, y, z);
  14966. if (s === 2)
  14967. return maj32(x, y, z);
  14968. }
  14969. exports.ft_1 = ft_1;
  14970. function ch32(x, y, z) {
  14971. return (x & y) ^ ((~x) & z);
  14972. }
  14973. exports.ch32 = ch32;
  14974. function maj32(x, y, z) {
  14975. return (x & y) ^ (x & z) ^ (y & z);
  14976. }
  14977. exports.maj32 = maj32;
  14978. function p32(x, y, z) {
  14979. return x ^ y ^ z;
  14980. }
  14981. exports.p32 = p32;
  14982. function s0_256(x) {
  14983. return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);
  14984. }
  14985. exports.s0_256 = s0_256;
  14986. function s1_256(x) {
  14987. return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);
  14988. }
  14989. exports.s1_256 = s1_256;
  14990. function g0_256(x) {
  14991. return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);
  14992. }
  14993. exports.g0_256 = g0_256;
  14994. function g1_256(x) {
  14995. return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);
  14996. }
  14997. exports.g1_256 = g1_256;
  14998. },{"../utils":100}],100:[function(require,module,exports){
  14999. 'use strict';
  15000. var assert = require('minimalistic-assert');
  15001. var inherits = require('inherits');
  15002. exports.inherits = inherits;
  15003. function toArray(msg, enc) {
  15004. if (Array.isArray(msg))
  15005. return msg.slice();
  15006. if (!msg)
  15007. return [];
  15008. var res = [];
  15009. if (typeof msg === 'string') {
  15010. if (!enc) {
  15011. for (var i = 0; i < msg.length; i++) {
  15012. var c = msg.charCodeAt(i);
  15013. var hi = c >> 8;
  15014. var lo = c & 0xff;
  15015. if (hi)
  15016. res.push(hi, lo);
  15017. else
  15018. res.push(lo);
  15019. }
  15020. } else if (enc === 'hex') {
  15021. msg = msg.replace(/[^a-z0-9]+/ig, '');
  15022. if (msg.length % 2 !== 0)
  15023. msg = '0' + msg;
  15024. for (i = 0; i < msg.length; i += 2)
  15025. res.push(parseInt(msg[i] + msg[i + 1], 16));
  15026. }
  15027. } else {
  15028. for (i = 0; i < msg.length; i++)
  15029. res[i] = msg[i] | 0;
  15030. }
  15031. return res;
  15032. }
  15033. exports.toArray = toArray;
  15034. function toHex(msg) {
  15035. var res = '';
  15036. for (var i = 0; i < msg.length; i++)
  15037. res += zero2(msg[i].toString(16));
  15038. return res;
  15039. }
  15040. exports.toHex = toHex;
  15041. function htonl(w) {
  15042. var res = (w >>> 24) |
  15043. ((w >>> 8) & 0xff00) |
  15044. ((w << 8) & 0xff0000) |
  15045. ((w & 0xff) << 24);
  15046. return res >>> 0;
  15047. }
  15048. exports.htonl = htonl;
  15049. function toHex32(msg, endian) {
  15050. var res = '';
  15051. for (var i = 0; i < msg.length; i++) {
  15052. var w = msg[i];
  15053. if (endian === 'little')
  15054. w = htonl(w);
  15055. res += zero8(w.toString(16));
  15056. }
  15057. return res;
  15058. }
  15059. exports.toHex32 = toHex32;
  15060. function zero2(word) {
  15061. if (word.length === 1)
  15062. return '0' + word;
  15063. else
  15064. return word;
  15065. }
  15066. exports.zero2 = zero2;
  15067. function zero8(word) {
  15068. if (word.length === 7)
  15069. return '0' + word;
  15070. else if (word.length === 6)
  15071. return '00' + word;
  15072. else if (word.length === 5)
  15073. return '000' + word;
  15074. else if (word.length === 4)
  15075. return '0000' + word;
  15076. else if (word.length === 3)
  15077. return '00000' + word;
  15078. else if (word.length === 2)
  15079. return '000000' + word;
  15080. else if (word.length === 1)
  15081. return '0000000' + word;
  15082. else
  15083. return word;
  15084. }
  15085. exports.zero8 = zero8;
  15086. function join32(msg, start, end, endian) {
  15087. var len = end - start;
  15088. assert(len % 4 === 0);
  15089. var res = new Array(len / 4);
  15090. for (var i = 0, k = start; i < res.length; i++, k += 4) {
  15091. var w;
  15092. if (endian === 'big')
  15093. w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
  15094. else
  15095. w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
  15096. res[i] = w >>> 0;
  15097. }
  15098. return res;
  15099. }
  15100. exports.join32 = join32;
  15101. function split32(msg, endian) {
  15102. var res = new Array(msg.length * 4);
  15103. for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
  15104. var m = msg[i];
  15105. if (endian === 'big') {
  15106. res[k] = m >>> 24;
  15107. res[k + 1] = (m >>> 16) & 0xff;
  15108. res[k + 2] = (m >>> 8) & 0xff;
  15109. res[k + 3] = m & 0xff;
  15110. } else {
  15111. res[k + 3] = m >>> 24;
  15112. res[k + 2] = (m >>> 16) & 0xff;
  15113. res[k + 1] = (m >>> 8) & 0xff;
  15114. res[k] = m & 0xff;
  15115. }
  15116. }
  15117. return res;
  15118. }
  15119. exports.split32 = split32;
  15120. function rotr32(w, b) {
  15121. return (w >>> b) | (w << (32 - b));
  15122. }
  15123. exports.rotr32 = rotr32;
  15124. function rotl32(w, b) {
  15125. return (w << b) | (w >>> (32 - b));
  15126. }
  15127. exports.rotl32 = rotl32;
  15128. function sum32(a, b) {
  15129. return (a + b) >>> 0;
  15130. }
  15131. exports.sum32 = sum32;
  15132. function sum32_3(a, b, c) {
  15133. return (a + b + c) >>> 0;
  15134. }
  15135. exports.sum32_3 = sum32_3;
  15136. function sum32_4(a, b, c, d) {
  15137. return (a + b + c + d) >>> 0;
  15138. }
  15139. exports.sum32_4 = sum32_4;
  15140. function sum32_5(a, b, c, d, e) {
  15141. return (a + b + c + d + e) >>> 0;
  15142. }
  15143. exports.sum32_5 = sum32_5;
  15144. function sum64(buf, pos, ah, al) {
  15145. var bh = buf[pos];
  15146. var bl = buf[pos + 1];
  15147. var lo = (al + bl) >>> 0;
  15148. var hi = (lo < al ? 1 : 0) + ah + bh;
  15149. buf[pos] = hi >>> 0;
  15150. buf[pos + 1] = lo;
  15151. }
  15152. exports.sum64 = sum64;
  15153. function sum64_hi(ah, al, bh, bl) {
  15154. var lo = (al + bl) >>> 0;
  15155. var hi = (lo < al ? 1 : 0) + ah + bh;
  15156. return hi >>> 0;
  15157. }
  15158. exports.sum64_hi = sum64_hi;
  15159. function sum64_lo(ah, al, bh, bl) {
  15160. var lo = al + bl;
  15161. return lo >>> 0;
  15162. }
  15163. exports.sum64_lo = sum64_lo;
  15164. function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
  15165. var carry = 0;
  15166. var lo = al;
  15167. lo = (lo + bl) >>> 0;
  15168. carry += lo < al ? 1 : 0;
  15169. lo = (lo + cl) >>> 0;
  15170. carry += lo < cl ? 1 : 0;
  15171. lo = (lo + dl) >>> 0;
  15172. carry += lo < dl ? 1 : 0;
  15173. var hi = ah + bh + ch + dh + carry;
  15174. return hi >>> 0;
  15175. }
  15176. exports.sum64_4_hi = sum64_4_hi;
  15177. function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
  15178. var lo = al + bl + cl + dl;
  15179. return lo >>> 0;
  15180. }
  15181. exports.sum64_4_lo = sum64_4_lo;
  15182. function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
  15183. var carry = 0;
  15184. var lo = al;
  15185. lo = (lo + bl) >>> 0;
  15186. carry += lo < al ? 1 : 0;
  15187. lo = (lo + cl) >>> 0;
  15188. carry += lo < cl ? 1 : 0;
  15189. lo = (lo + dl) >>> 0;
  15190. carry += lo < dl ? 1 : 0;
  15191. lo = (lo + el) >>> 0;
  15192. carry += lo < el ? 1 : 0;
  15193. var hi = ah + bh + ch + dh + eh + carry;
  15194. return hi >>> 0;
  15195. }
  15196. exports.sum64_5_hi = sum64_5_hi;
  15197. function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
  15198. var lo = al + bl + cl + dl + el;
  15199. return lo >>> 0;
  15200. }
  15201. exports.sum64_5_lo = sum64_5_lo;
  15202. function rotr64_hi(ah, al, num) {
  15203. var r = (al << (32 - num)) | (ah >>> num);
  15204. return r >>> 0;
  15205. }
  15206. exports.rotr64_hi = rotr64_hi;
  15207. function rotr64_lo(ah, al, num) {
  15208. var r = (ah << (32 - num)) | (al >>> num);
  15209. return r >>> 0;
  15210. }
  15211. exports.rotr64_lo = rotr64_lo;
  15212. function shr64_hi(ah, al, num) {
  15213. return ah >>> num;
  15214. }
  15215. exports.shr64_hi = shr64_hi;
  15216. function shr64_lo(ah, al, num) {
  15217. var r = (ah << (32 - num)) | (al >>> num);
  15218. return r >>> 0;
  15219. }
  15220. exports.shr64_lo = shr64_lo;
  15221. },{"inherits":104,"minimalistic-assert":110}],101:[function(require,module,exports){
  15222. 'use strict';
  15223. var hash = require('hash.js');
  15224. var utils = require('minimalistic-crypto-utils');
  15225. var assert = require('minimalistic-assert');
  15226. function HmacDRBG(options) {
  15227. if (!(this instanceof HmacDRBG))
  15228. return new HmacDRBG(options);
  15229. this.hash = options.hash;
  15230. this.predResist = !!options.predResist;
  15231. this.outLen = this.hash.outSize;
  15232. this.minEntropy = options.minEntropy || this.hash.hmacStrength;
  15233. this._reseed = null;
  15234. this.reseedInterval = null;
  15235. this.K = null;
  15236. this.V = null;
  15237. var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');
  15238. var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');
  15239. var pers = utils.toArray(options.pers, options.persEnc || 'hex');
  15240. assert(entropy.length >= (this.minEntropy / 8),
  15241. 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
  15242. this._init(entropy, nonce, pers);
  15243. }
  15244. module.exports = HmacDRBG;
  15245. HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
  15246. var seed = entropy.concat(nonce).concat(pers);
  15247. this.K = new Array(this.outLen / 8);
  15248. this.V = new Array(this.outLen / 8);
  15249. for (var i = 0; i < this.V.length; i++) {
  15250. this.K[i] = 0x00;
  15251. this.V[i] = 0x01;
  15252. }
  15253. this._update(seed);
  15254. this._reseed = 1;
  15255. this.reseedInterval = 0x1000000000000; // 2^48
  15256. };
  15257. HmacDRBG.prototype._hmac = function hmac() {
  15258. return new hash.hmac(this.hash, this.K);
  15259. };
  15260. HmacDRBG.prototype._update = function update(seed) {
  15261. var kmac = this._hmac()
  15262. .update(this.V)
  15263. .update([ 0x00 ]);
  15264. if (seed)
  15265. kmac = kmac.update(seed);
  15266. this.K = kmac.digest();
  15267. this.V = this._hmac().update(this.V).digest();
  15268. if (!seed)
  15269. return;
  15270. this.K = this._hmac()
  15271. .update(this.V)
  15272. .update([ 0x01 ])
  15273. .update(seed)
  15274. .digest();
  15275. this.V = this._hmac().update(this.V).digest();
  15276. };
  15277. HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
  15278. // Optional entropy enc
  15279. if (typeof entropyEnc !== 'string') {
  15280. addEnc = add;
  15281. add = entropyEnc;
  15282. entropyEnc = null;
  15283. }
  15284. entropy = utils.toArray(entropy, entropyEnc);
  15285. add = utils.toArray(add, addEnc);
  15286. assert(entropy.length >= (this.minEntropy / 8),
  15287. 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
  15288. this._update(entropy.concat(add || []));
  15289. this._reseed = 1;
  15290. };
  15291. HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
  15292. if (this._reseed > this.reseedInterval)
  15293. throw new Error('Reseed is required');
  15294. // Optional encoding
  15295. if (typeof enc !== 'string') {
  15296. addEnc = add;
  15297. add = enc;
  15298. enc = null;
  15299. }
  15300. // Optional additional data
  15301. if (add) {
  15302. add = utils.toArray(add, addEnc || 'hex');
  15303. this._update(add);
  15304. }
  15305. var temp = [];
  15306. while (temp.length < len) {
  15307. this.V = this._hmac().update(this.V).digest();
  15308. temp = temp.concat(this.V);
  15309. }
  15310. var res = temp.slice(0, len);
  15311. this._update(add);
  15312. this._reseed++;
  15313. return utils.encode(res, enc);
  15314. };
  15315. },{"hash.js":89,"minimalistic-assert":110,"minimalistic-crypto-utils":111}],102:[function(require,module,exports){
  15316. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  15317. var e, m
  15318. var eLen = nBytes * 8 - mLen - 1
  15319. var eMax = (1 << eLen) - 1
  15320. var eBias = eMax >> 1
  15321. var nBits = -7
  15322. var i = isLE ? (nBytes - 1) : 0
  15323. var d = isLE ? -1 : 1
  15324. var s = buffer[offset + i]
  15325. i += d
  15326. e = s & ((1 << (-nBits)) - 1)
  15327. s >>= (-nBits)
  15328. nBits += eLen
  15329. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  15330. m = e & ((1 << (-nBits)) - 1)
  15331. e >>= (-nBits)
  15332. nBits += mLen
  15333. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  15334. if (e === 0) {
  15335. e = 1 - eBias
  15336. } else if (e === eMax) {
  15337. return m ? NaN : ((s ? -1 : 1) * Infinity)
  15338. } else {
  15339. m = m + Math.pow(2, mLen)
  15340. e = e - eBias
  15341. }
  15342. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  15343. }
  15344. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  15345. var e, m, c
  15346. var eLen = nBytes * 8 - mLen - 1
  15347. var eMax = (1 << eLen) - 1
  15348. var eBias = eMax >> 1
  15349. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  15350. var i = isLE ? 0 : (nBytes - 1)
  15351. var d = isLE ? 1 : -1
  15352. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  15353. value = Math.abs(value)
  15354. if (isNaN(value) || value === Infinity) {
  15355. m = isNaN(value) ? 1 : 0
  15356. e = eMax
  15357. } else {
  15358. e = Math.floor(Math.log(value) / Math.LN2)
  15359. if (value * (c = Math.pow(2, -e)) < 1) {
  15360. e--
  15361. c *= 2
  15362. }
  15363. if (e + eBias >= 1) {
  15364. value += rt / c
  15365. } else {
  15366. value += rt * Math.pow(2, 1 - eBias)
  15367. }
  15368. if (value * c >= 2) {
  15369. e++
  15370. c /= 2
  15371. }
  15372. if (e + eBias >= eMax) {
  15373. m = 0
  15374. e = eMax
  15375. } else if (e + eBias >= 1) {
  15376. m = (value * c - 1) * Math.pow(2, mLen)
  15377. e = e + eBias
  15378. } else {
  15379. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  15380. e = 0
  15381. }
  15382. }
  15383. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  15384. e = (e << mLen) | m
  15385. eLen += mLen
  15386. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  15387. buffer[offset + i - d] |= s * 128
  15388. }
  15389. },{}],103:[function(require,module,exports){
  15390. var indexOf = [].indexOf;
  15391. module.exports = function(arr, obj){
  15392. if (indexOf) return arr.indexOf(obj);
  15393. for (var i = 0; i < arr.length; ++i) {
  15394. if (arr[i] === obj) return i;
  15395. }
  15396. return -1;
  15397. };
  15398. },{}],104:[function(require,module,exports){
  15399. if (typeof Object.create === 'function') {
  15400. // implementation from standard node.js 'util' module
  15401. module.exports = function inherits(ctor, superCtor) {
  15402. ctor.super_ = superCtor
  15403. ctor.prototype = Object.create(superCtor.prototype, {
  15404. constructor: {
  15405. value: ctor,
  15406. enumerable: false,
  15407. writable: true,
  15408. configurable: true
  15409. }
  15410. });
  15411. };
  15412. } else {
  15413. // old school shim for old browsers
  15414. module.exports = function inherits(ctor, superCtor) {
  15415. ctor.super_ = superCtor
  15416. var TempCtor = function () {}
  15417. TempCtor.prototype = superCtor.prototype
  15418. ctor.prototype = new TempCtor()
  15419. ctor.prototype.constructor = ctor
  15420. }
  15421. }
  15422. },{}],105:[function(require,module,exports){
  15423. /*!
  15424. * Determine if an object is a Buffer
  15425. *
  15426. * @author Feross Aboukhadijeh <https://feross.org>
  15427. * @license MIT
  15428. */
  15429. // The _isBuffer check is for Safari 5-7 support, because it's missing
  15430. // Object.prototype.constructor. Remove this eventually
  15431. module.exports = function (obj) {
  15432. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  15433. }
  15434. function isBuffer (obj) {
  15435. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  15436. }
  15437. // For Node v0.10 support. Remove this eventually.
  15438. function isSlowBuffer (obj) {
  15439. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  15440. }
  15441. },{}],106:[function(require,module,exports){
  15442. var toString = {}.toString;
  15443. module.exports = Array.isArray || function (arr) {
  15444. return toString.call(arr) == '[object Array]';
  15445. };
  15446. },{}],107:[function(require,module,exports){
  15447. (function (Buffer){
  15448. 'use strict'
  15449. var inherits = require('inherits')
  15450. var HashBase = require('hash-base')
  15451. var ARRAY16 = new Array(16)
  15452. function MD5 () {
  15453. HashBase.call(this, 64)
  15454. // state
  15455. this._a = 0x67452301
  15456. this._b = 0xefcdab89
  15457. this._c = 0x98badcfe
  15458. this._d = 0x10325476
  15459. }
  15460. inherits(MD5, HashBase)
  15461. MD5.prototype._update = function () {
  15462. var M = ARRAY16
  15463. for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4)
  15464. var a = this._a
  15465. var b = this._b
  15466. var c = this._c
  15467. var d = this._d
  15468. a = fnF(a, b, c, d, M[0], 0xd76aa478, 7)
  15469. d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12)
  15470. c = fnF(c, d, a, b, M[2], 0x242070db, 17)
  15471. b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22)
  15472. a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7)
  15473. d = fnF(d, a, b, c, M[5], 0x4787c62a, 12)
  15474. c = fnF(c, d, a, b, M[6], 0xa8304613, 17)
  15475. b = fnF(b, c, d, a, M[7], 0xfd469501, 22)
  15476. a = fnF(a, b, c, d, M[8], 0x698098d8, 7)
  15477. d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12)
  15478. c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17)
  15479. b = fnF(b, c, d, a, M[11], 0x895cd7be, 22)
  15480. a = fnF(a, b, c, d, M[12], 0x6b901122, 7)
  15481. d = fnF(d, a, b, c, M[13], 0xfd987193, 12)
  15482. c = fnF(c, d, a, b, M[14], 0xa679438e, 17)
  15483. b = fnF(b, c, d, a, M[15], 0x49b40821, 22)
  15484. a = fnG(a, b, c, d, M[1], 0xf61e2562, 5)
  15485. d = fnG(d, a, b, c, M[6], 0xc040b340, 9)
  15486. c = fnG(c, d, a, b, M[11], 0x265e5a51, 14)
  15487. b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20)
  15488. a = fnG(a, b, c, d, M[5], 0xd62f105d, 5)
  15489. d = fnG(d, a, b, c, M[10], 0x02441453, 9)
  15490. c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14)
  15491. b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20)
  15492. a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5)
  15493. d = fnG(d, a, b, c, M[14], 0xc33707d6, 9)
  15494. c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14)
  15495. b = fnG(b, c, d, a, M[8], 0x455a14ed, 20)
  15496. a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5)
  15497. d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9)
  15498. c = fnG(c, d, a, b, M[7], 0x676f02d9, 14)
  15499. b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20)
  15500. a = fnH(a, b, c, d, M[5], 0xfffa3942, 4)
  15501. d = fnH(d, a, b, c, M[8], 0x8771f681, 11)
  15502. c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16)
  15503. b = fnH(b, c, d, a, M[14], 0xfde5380c, 23)
  15504. a = fnH(a, b, c, d, M[1], 0xa4beea44, 4)
  15505. d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11)
  15506. c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16)
  15507. b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23)
  15508. a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4)
  15509. d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11)
  15510. c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16)
  15511. b = fnH(b, c, d, a, M[6], 0x04881d05, 23)
  15512. a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4)
  15513. d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11)
  15514. c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16)
  15515. b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23)
  15516. a = fnI(a, b, c, d, M[0], 0xf4292244, 6)
  15517. d = fnI(d, a, b, c, M[7], 0x432aff97, 10)
  15518. c = fnI(c, d, a, b, M[14], 0xab9423a7, 15)
  15519. b = fnI(b, c, d, a, M[5], 0xfc93a039, 21)
  15520. a = fnI(a, b, c, d, M[12], 0x655b59c3, 6)
  15521. d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10)
  15522. c = fnI(c, d, a, b, M[10], 0xffeff47d, 15)
  15523. b = fnI(b, c, d, a, M[1], 0x85845dd1, 21)
  15524. a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6)
  15525. d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10)
  15526. c = fnI(c, d, a, b, M[6], 0xa3014314, 15)
  15527. b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21)
  15528. a = fnI(a, b, c, d, M[4], 0xf7537e82, 6)
  15529. d = fnI(d, a, b, c, M[11], 0xbd3af235, 10)
  15530. c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15)
  15531. b = fnI(b, c, d, a, M[9], 0xeb86d391, 21)
  15532. this._a = (this._a + a) | 0
  15533. this._b = (this._b + b) | 0
  15534. this._c = (this._c + c) | 0
  15535. this._d = (this._d + d) | 0
  15536. }
  15537. MD5.prototype._digest = function () {
  15538. // create padding and handle blocks
  15539. this._block[this._blockOffset++] = 0x80
  15540. if (this._blockOffset > 56) {
  15541. this._block.fill(0, this._blockOffset, 64)
  15542. this._update()
  15543. this._blockOffset = 0
  15544. }
  15545. this._block.fill(0, this._blockOffset, 56)
  15546. this._block.writeUInt32LE(this._length[0], 56)
  15547. this._block.writeUInt32LE(this._length[1], 60)
  15548. this._update()
  15549. // produce result
  15550. var buffer = new Buffer(16)
  15551. buffer.writeInt32LE(this._a, 0)
  15552. buffer.writeInt32LE(this._b, 4)
  15553. buffer.writeInt32LE(this._c, 8)
  15554. buffer.writeInt32LE(this._d, 12)
  15555. return buffer
  15556. }
  15557. function rotl (x, n) {
  15558. return (x << n) | (x >>> (32 - n))
  15559. }
  15560. function fnF (a, b, c, d, m, k, s) {
  15561. return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0
  15562. }
  15563. function fnG (a, b, c, d, m, k, s) {
  15564. return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0
  15565. }
  15566. function fnH (a, b, c, d, m, k, s) {
  15567. return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0
  15568. }
  15569. function fnI (a, b, c, d, m, k, s) {
  15570. return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0
  15571. }
  15572. module.exports = MD5
  15573. }).call(this,require("buffer").Buffer)
  15574. },{"buffer":50,"hash-base":108,"inherits":104}],108:[function(require,module,exports){
  15575. 'use strict'
  15576. var Buffer = require('safe-buffer').Buffer
  15577. var Transform = require('stream').Transform
  15578. var inherits = require('inherits')
  15579. function throwIfNotStringOrBuffer (val, prefix) {
  15580. if (!Buffer.isBuffer(val) && typeof val !== 'string') {
  15581. throw new TypeError(prefix + ' must be a string or a buffer')
  15582. }
  15583. }
  15584. function HashBase (blockSize) {
  15585. Transform.call(this)
  15586. this._block = Buffer.allocUnsafe(blockSize)
  15587. this._blockSize = blockSize
  15588. this._blockOffset = 0
  15589. this._length = [0, 0, 0, 0]
  15590. this._finalized = false
  15591. }
  15592. inherits(HashBase, Transform)
  15593. HashBase.prototype._transform = function (chunk, encoding, callback) {
  15594. var error = null
  15595. try {
  15596. this.update(chunk, encoding)
  15597. } catch (err) {
  15598. error = err
  15599. }
  15600. callback(error)
  15601. }
  15602. HashBase.prototype._flush = function (callback) {
  15603. var error = null
  15604. try {
  15605. this.push(this.digest())
  15606. } catch (err) {
  15607. error = err
  15608. }
  15609. callback(error)
  15610. }
  15611. HashBase.prototype.update = function (data, encoding) {
  15612. throwIfNotStringOrBuffer(data, 'Data')
  15613. if (this._finalized) throw new Error('Digest already called')
  15614. if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)
  15615. // consume data
  15616. var block = this._block
  15617. var offset = 0
  15618. while (this._blockOffset + data.length - offset >= this._blockSize) {
  15619. for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
  15620. this._update()
  15621. this._blockOffset = 0
  15622. }
  15623. while (offset < data.length) block[this._blockOffset++] = data[offset++]
  15624. // update length
  15625. for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
  15626. this._length[j] += carry
  15627. carry = (this._length[j] / 0x0100000000) | 0
  15628. if (carry > 0) this._length[j] -= 0x0100000000 * carry
  15629. }
  15630. return this
  15631. }
  15632. HashBase.prototype._update = function () {
  15633. throw new Error('_update is not implemented')
  15634. }
  15635. HashBase.prototype.digest = function (encoding) {
  15636. if (this._finalized) throw new Error('Digest already called')
  15637. this._finalized = true
  15638. var digest = this._digest()
  15639. if (encoding !== undefined) digest = digest.toString(encoding)
  15640. // reset state
  15641. this._block.fill(0)
  15642. this._blockOffset = 0
  15643. for (var i = 0; i < 4; ++i) this._length[i] = 0
  15644. return digest
  15645. }
  15646. HashBase.prototype._digest = function () {
  15647. throw new Error('_digest is not implemented')
  15648. }
  15649. module.exports = HashBase
  15650. },{"inherits":104,"safe-buffer":157,"stream":166}],109:[function(require,module,exports){
  15651. var bn = require('bn.js');
  15652. var brorand = require('brorand');
  15653. function MillerRabin(rand) {
  15654. this.rand = rand || new brorand.Rand();
  15655. }
  15656. module.exports = MillerRabin;
  15657. MillerRabin.create = function create(rand) {
  15658. return new MillerRabin(rand);
  15659. };
  15660. MillerRabin.prototype._randbelow = function _randbelow(n) {
  15661. var len = n.bitLength();
  15662. var min_bytes = Math.ceil(len / 8);
  15663. // Generage random bytes until a number less than n is found.
  15664. // This ensures that 0..n-1 have an equal probability of being selected.
  15665. do
  15666. var a = new bn(this.rand.generate(min_bytes));
  15667. while (a.cmp(n) >= 0);
  15668. return a;
  15669. };
  15670. MillerRabin.prototype._randrange = function _randrange(start, stop) {
  15671. // Generate a random number greater than or equal to start and less than stop.
  15672. var size = stop.sub(start);
  15673. return start.add(this._randbelow(size));
  15674. };
  15675. MillerRabin.prototype.test = function test(n, k, cb) {
  15676. var len = n.bitLength();
  15677. var red = bn.mont(n);
  15678. var rone = new bn(1).toRed(red);
  15679. if (!k)
  15680. k = Math.max(1, (len / 48) | 0);
  15681. // Find d and s, (n - 1) = (2 ^ s) * d;
  15682. var n1 = n.subn(1);
  15683. for (var s = 0; !n1.testn(s); s++) {}
  15684. var d = n.shrn(s);
  15685. var rn1 = n1.toRed(red);
  15686. var prime = true;
  15687. for (; k > 0; k--) {
  15688. var a = this._randrange(new bn(2), n1);
  15689. if (cb)
  15690. cb(a);
  15691. var x = a.toRed(red).redPow(d);
  15692. if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
  15693. continue;
  15694. for (var i = 1; i < s; i++) {
  15695. x = x.redSqr();
  15696. if (x.cmp(rone) === 0)
  15697. return false;
  15698. if (x.cmp(rn1) === 0)
  15699. break;
  15700. }
  15701. if (i === s)
  15702. return false;
  15703. }
  15704. return prime;
  15705. };
  15706. MillerRabin.prototype.getDivisor = function getDivisor(n, k) {
  15707. var len = n.bitLength();
  15708. var red = bn.mont(n);
  15709. var rone = new bn(1).toRed(red);
  15710. if (!k)
  15711. k = Math.max(1, (len / 48) | 0);
  15712. // Find d and s, (n - 1) = (2 ^ s) * d;
  15713. var n1 = n.subn(1);
  15714. for (var s = 0; !n1.testn(s); s++) {}
  15715. var d = n.shrn(s);
  15716. var rn1 = n1.toRed(red);
  15717. for (; k > 0; k--) {
  15718. var a = this._randrange(new bn(2), n1);
  15719. var g = n.gcd(a);
  15720. if (g.cmpn(1) !== 0)
  15721. return g;
  15722. var x = a.toRed(red).redPow(d);
  15723. if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
  15724. continue;
  15725. for (var i = 1; i < s; i++) {
  15726. x = x.redSqr();
  15727. if (x.cmp(rone) === 0)
  15728. return x.fromRed().subn(1).gcd(n);
  15729. if (x.cmp(rn1) === 0)
  15730. break;
  15731. }
  15732. if (i === s) {
  15733. x = x.redSqr();
  15734. return x.fromRed().subn(1).gcd(n);
  15735. }
  15736. }
  15737. return false;
  15738. };
  15739. },{"bn.js":17,"brorand":18}],110:[function(require,module,exports){
  15740. module.exports = assert;
  15741. function assert(val, msg) {
  15742. if (!val)
  15743. throw new Error(msg || 'Assertion failed');
  15744. }
  15745. assert.equal = function assertEqual(l, r, msg) {
  15746. if (l != r)
  15747. throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
  15748. };
  15749. },{}],111:[function(require,module,exports){
  15750. 'use strict';
  15751. var utils = exports;
  15752. function toArray(msg, enc) {
  15753. if (Array.isArray(msg))
  15754. return msg.slice();
  15755. if (!msg)
  15756. return [];
  15757. var res = [];
  15758. if (typeof msg !== 'string') {
  15759. for (var i = 0; i < msg.length; i++)
  15760. res[i] = msg[i] | 0;
  15761. return res;
  15762. }
  15763. if (enc === 'hex') {
  15764. msg = msg.replace(/[^a-z0-9]+/ig, '');
  15765. if (msg.length % 2 !== 0)
  15766. msg = '0' + msg;
  15767. for (var i = 0; i < msg.length; i += 2)
  15768. res.push(parseInt(msg[i] + msg[i + 1], 16));
  15769. } else {
  15770. for (var i = 0; i < msg.length; i++) {
  15771. var c = msg.charCodeAt(i);
  15772. var hi = c >> 8;
  15773. var lo = c & 0xff;
  15774. if (hi)
  15775. res.push(hi, lo);
  15776. else
  15777. res.push(lo);
  15778. }
  15779. }
  15780. return res;
  15781. }
  15782. utils.toArray = toArray;
  15783. function zero2(word) {
  15784. if (word.length === 1)
  15785. return '0' + word;
  15786. else
  15787. return word;
  15788. }
  15789. utils.zero2 = zero2;
  15790. function toHex(msg) {
  15791. var res = '';
  15792. for (var i = 0; i < msg.length; i++)
  15793. res += zero2(msg[i].toString(16));
  15794. return res;
  15795. }
  15796. utils.toHex = toHex;
  15797. utils.encode = function encode(arr, enc) {
  15798. if (enc === 'hex')
  15799. return toHex(arr);
  15800. else
  15801. return arr;
  15802. };
  15803. },{}],112:[function(require,module,exports){
  15804. 'use strict';
  15805. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  15806. (typeof Uint16Array !== 'undefined') &&
  15807. (typeof Int32Array !== 'undefined');
  15808. function _has(obj, key) {
  15809. return Object.prototype.hasOwnProperty.call(obj, key);
  15810. }
  15811. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  15812. var sources = Array.prototype.slice.call(arguments, 1);
  15813. while (sources.length) {
  15814. var source = sources.shift();
  15815. if (!source) { continue; }
  15816. if (typeof source !== 'object') {
  15817. throw new TypeError(source + 'must be non-object');
  15818. }
  15819. for (var p in source) {
  15820. if (_has(source, p)) {
  15821. obj[p] = source[p];
  15822. }
  15823. }
  15824. }
  15825. return obj;
  15826. };
  15827. // reduce buffer size, avoiding mem copy
  15828. exports.shrinkBuf = function (buf, size) {
  15829. if (buf.length === size) { return buf; }
  15830. if (buf.subarray) { return buf.subarray(0, size); }
  15831. buf.length = size;
  15832. return buf;
  15833. };
  15834. var fnTyped = {
  15835. arraySet: function (dest, src, src_offs, len, dest_offs) {
  15836. if (src.subarray && dest.subarray) {
  15837. dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
  15838. return;
  15839. }
  15840. // Fallback to ordinary array
  15841. for (var i = 0; i < len; i++) {
  15842. dest[dest_offs + i] = src[src_offs + i];
  15843. }
  15844. },
  15845. // Join array of chunks to single array.
  15846. flattenChunks: function (chunks) {
  15847. var i, l, len, pos, chunk, result;
  15848. // calculate data length
  15849. len = 0;
  15850. for (i = 0, l = chunks.length; i < l; i++) {
  15851. len += chunks[i].length;
  15852. }
  15853. // join chunks
  15854. result = new Uint8Array(len);
  15855. pos = 0;
  15856. for (i = 0, l = chunks.length; i < l; i++) {
  15857. chunk = chunks[i];
  15858. result.set(chunk, pos);
  15859. pos += chunk.length;
  15860. }
  15861. return result;
  15862. }
  15863. };
  15864. var fnUntyped = {
  15865. arraySet: function (dest, src, src_offs, len, dest_offs) {
  15866. for (var i = 0; i < len; i++) {
  15867. dest[dest_offs + i] = src[src_offs + i];
  15868. }
  15869. },
  15870. // Join array of chunks to single array.
  15871. flattenChunks: function (chunks) {
  15872. return [].concat.apply([], chunks);
  15873. }
  15874. };
  15875. // Enable/Disable typed arrays use, for testing
  15876. //
  15877. exports.setTyped = function (on) {
  15878. if (on) {
  15879. exports.Buf8 = Uint8Array;
  15880. exports.Buf16 = Uint16Array;
  15881. exports.Buf32 = Int32Array;
  15882. exports.assign(exports, fnTyped);
  15883. } else {
  15884. exports.Buf8 = Array;
  15885. exports.Buf16 = Array;
  15886. exports.Buf32 = Array;
  15887. exports.assign(exports, fnUntyped);
  15888. }
  15889. };
  15890. exports.setTyped(TYPED_OK);
  15891. },{}],113:[function(require,module,exports){
  15892. 'use strict';
  15893. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  15894. // It isn't worth it to make additional optimizations as in original.
  15895. // Small size is preferable.
  15896. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  15897. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  15898. //
  15899. // This software is provided 'as-is', without any express or implied
  15900. // warranty. In no event will the authors be held liable for any damages
  15901. // arising from the use of this software.
  15902. //
  15903. // Permission is granted to anyone to use this software for any purpose,
  15904. // including commercial applications, and to alter it and redistribute it
  15905. // freely, subject to the following restrictions:
  15906. //
  15907. // 1. The origin of this software must not be misrepresented; you must not
  15908. // claim that you wrote the original software. If you use this software
  15909. // in a product, an acknowledgment in the product documentation would be
  15910. // appreciated but is not required.
  15911. // 2. Altered source versions must be plainly marked as such, and must not be
  15912. // misrepresented as being the original software.
  15913. // 3. This notice may not be removed or altered from any source distribution.
  15914. function adler32(adler, buf, len, pos) {
  15915. var s1 = (adler & 0xffff) |0,
  15916. s2 = ((adler >>> 16) & 0xffff) |0,
  15917. n = 0;
  15918. while (len !== 0) {
  15919. // Set limit ~ twice less than 5552, to keep
  15920. // s2 in 31-bits, because we force signed ints.
  15921. // in other case %= will fail.
  15922. n = len > 2000 ? 2000 : len;
  15923. len -= n;
  15924. do {
  15925. s1 = (s1 + buf[pos++]) |0;
  15926. s2 = (s2 + s1) |0;
  15927. } while (--n);
  15928. s1 %= 65521;
  15929. s2 %= 65521;
  15930. }
  15931. return (s1 | (s2 << 16)) |0;
  15932. }
  15933. module.exports = adler32;
  15934. },{}],114:[function(require,module,exports){
  15935. 'use strict';
  15936. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  15937. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  15938. //
  15939. // This software is provided 'as-is', without any express or implied
  15940. // warranty. In no event will the authors be held liable for any damages
  15941. // arising from the use of this software.
  15942. //
  15943. // Permission is granted to anyone to use this software for any purpose,
  15944. // including commercial applications, and to alter it and redistribute it
  15945. // freely, subject to the following restrictions:
  15946. //
  15947. // 1. The origin of this software must not be misrepresented; you must not
  15948. // claim that you wrote the original software. If you use this software
  15949. // in a product, an acknowledgment in the product documentation would be
  15950. // appreciated but is not required.
  15951. // 2. Altered source versions must be plainly marked as such, and must not be
  15952. // misrepresented as being the original software.
  15953. // 3. This notice may not be removed or altered from any source distribution.
  15954. module.exports = {
  15955. /* Allowed flush values; see deflate() and inflate() below for details */
  15956. Z_NO_FLUSH: 0,
  15957. Z_PARTIAL_FLUSH: 1,
  15958. Z_SYNC_FLUSH: 2,
  15959. Z_FULL_FLUSH: 3,
  15960. Z_FINISH: 4,
  15961. Z_BLOCK: 5,
  15962. Z_TREES: 6,
  15963. /* Return codes for the compression/decompression functions. Negative values
  15964. * are errors, positive values are used for special but normal events.
  15965. */
  15966. Z_OK: 0,
  15967. Z_STREAM_END: 1,
  15968. Z_NEED_DICT: 2,
  15969. Z_ERRNO: -1,
  15970. Z_STREAM_ERROR: -2,
  15971. Z_DATA_ERROR: -3,
  15972. //Z_MEM_ERROR: -4,
  15973. Z_BUF_ERROR: -5,
  15974. //Z_VERSION_ERROR: -6,
  15975. /* compression levels */
  15976. Z_NO_COMPRESSION: 0,
  15977. Z_BEST_SPEED: 1,
  15978. Z_BEST_COMPRESSION: 9,
  15979. Z_DEFAULT_COMPRESSION: -1,
  15980. Z_FILTERED: 1,
  15981. Z_HUFFMAN_ONLY: 2,
  15982. Z_RLE: 3,
  15983. Z_FIXED: 4,
  15984. Z_DEFAULT_STRATEGY: 0,
  15985. /* Possible values of the data_type field (though see inflate()) */
  15986. Z_BINARY: 0,
  15987. Z_TEXT: 1,
  15988. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  15989. Z_UNKNOWN: 2,
  15990. /* The deflate compression method */
  15991. Z_DEFLATED: 8
  15992. //Z_NULL: null // Use -1 or null inline, depending on var type
  15993. };
  15994. },{}],115:[function(require,module,exports){
  15995. 'use strict';
  15996. // Note: we can't get significant speed boost here.
  15997. // So write code to minimize size - no pregenerated tables
  15998. // and array tools dependencies.
  15999. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  16000. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  16001. //
  16002. // This software is provided 'as-is', without any express or implied
  16003. // warranty. In no event will the authors be held liable for any damages
  16004. // arising from the use of this software.
  16005. //
  16006. // Permission is granted to anyone to use this software for any purpose,
  16007. // including commercial applications, and to alter it and redistribute it
  16008. // freely, subject to the following restrictions:
  16009. //
  16010. // 1. The origin of this software must not be misrepresented; you must not
  16011. // claim that you wrote the original software. If you use this software
  16012. // in a product, an acknowledgment in the product documentation would be
  16013. // appreciated but is not required.
  16014. // 2. Altered source versions must be plainly marked as such, and must not be
  16015. // misrepresented as being the original software.
  16016. // 3. This notice may not be removed or altered from any source distribution.
  16017. // Use ordinary array, since untyped makes no boost here
  16018. function makeTable() {
  16019. var c, table = [];
  16020. for (var n = 0; n < 256; n++) {
  16021. c = n;
  16022. for (var k = 0; k < 8; k++) {
  16023. c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  16024. }
  16025. table[n] = c;
  16026. }
  16027. return table;
  16028. }
  16029. // Create table on load. Just 255 signed longs. Not a problem.
  16030. var crcTable = makeTable();
  16031. function crc32(crc, buf, len, pos) {
  16032. var t = crcTable,
  16033. end = pos + len;
  16034. crc ^= -1;
  16035. for (var i = pos; i < end; i++) {
  16036. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  16037. }
  16038. return (crc ^ (-1)); // >>> 0;
  16039. }
  16040. module.exports = crc32;
  16041. },{}],116:[function(require,module,exports){
  16042. 'use strict';
  16043. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  16044. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  16045. //
  16046. // This software is provided 'as-is', without any express or implied
  16047. // warranty. In no event will the authors be held liable for any damages
  16048. // arising from the use of this software.
  16049. //
  16050. // Permission is granted to anyone to use this software for any purpose,
  16051. // including commercial applications, and to alter it and redistribute it
  16052. // freely, subject to the following restrictions:
  16053. //
  16054. // 1. The origin of this software must not be misrepresented; you must not
  16055. // claim that you wrote the original software. If you use this software
  16056. // in a product, an acknowledgment in the product documentation would be
  16057. // appreciated but is not required.
  16058. // 2. Altered source versions must be plainly marked as such, and must not be
  16059. // misrepresented as being the original software.
  16060. // 3. This notice may not be removed or altered from any source distribution.
  16061. var utils = require('../utils/common');
  16062. var trees = require('./trees');
  16063. var adler32 = require('./adler32');
  16064. var crc32 = require('./crc32');
  16065. var msg = require('./messages');
  16066. /* Public constants ==========================================================*/
  16067. /* ===========================================================================*/
  16068. /* Allowed flush values; see deflate() and inflate() below for details */
  16069. var Z_NO_FLUSH = 0;
  16070. var Z_PARTIAL_FLUSH = 1;
  16071. //var Z_SYNC_FLUSH = 2;
  16072. var Z_FULL_FLUSH = 3;
  16073. var Z_FINISH = 4;
  16074. var Z_BLOCK = 5;
  16075. //var Z_TREES = 6;
  16076. /* Return codes for the compression/decompression functions. Negative values
  16077. * are errors, positive values are used for special but normal events.
  16078. */
  16079. var Z_OK = 0;
  16080. var Z_STREAM_END = 1;
  16081. //var Z_NEED_DICT = 2;
  16082. //var Z_ERRNO = -1;
  16083. var Z_STREAM_ERROR = -2;
  16084. var Z_DATA_ERROR = -3;
  16085. //var Z_MEM_ERROR = -4;
  16086. var Z_BUF_ERROR = -5;
  16087. //var Z_VERSION_ERROR = -6;
  16088. /* compression levels */
  16089. //var Z_NO_COMPRESSION = 0;
  16090. //var Z_BEST_SPEED = 1;
  16091. //var Z_BEST_COMPRESSION = 9;
  16092. var Z_DEFAULT_COMPRESSION = -1;
  16093. var Z_FILTERED = 1;
  16094. var Z_HUFFMAN_ONLY = 2;
  16095. var Z_RLE = 3;
  16096. var Z_FIXED = 4;
  16097. var Z_DEFAULT_STRATEGY = 0;
  16098. /* Possible values of the data_type field (though see inflate()) */
  16099. //var Z_BINARY = 0;
  16100. //var Z_TEXT = 1;
  16101. //var Z_ASCII = 1; // = Z_TEXT
  16102. var Z_UNKNOWN = 2;
  16103. /* The deflate compression method */
  16104. var Z_DEFLATED = 8;
  16105. /*============================================================================*/
  16106. var MAX_MEM_LEVEL = 9;
  16107. /* Maximum value for memLevel in deflateInit2 */
  16108. var MAX_WBITS = 15;
  16109. /* 32K LZ77 window */
  16110. var DEF_MEM_LEVEL = 8;
  16111. var LENGTH_CODES = 29;
  16112. /* number of length codes, not counting the special END_BLOCK code */
  16113. var LITERALS = 256;
  16114. /* number of literal bytes 0..255 */
  16115. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  16116. /* number of Literal or Length codes, including the END_BLOCK code */
  16117. var D_CODES = 30;
  16118. /* number of distance codes */
  16119. var BL_CODES = 19;
  16120. /* number of codes used to transfer the bit lengths */
  16121. var HEAP_SIZE = 2 * L_CODES + 1;
  16122. /* maximum heap size */
  16123. var MAX_BITS = 15;
  16124. /* All codes must not exceed MAX_BITS bits */
  16125. var MIN_MATCH = 3;
  16126. var MAX_MATCH = 258;
  16127. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  16128. var PRESET_DICT = 0x20;
  16129. var INIT_STATE = 42;
  16130. var EXTRA_STATE = 69;
  16131. var NAME_STATE = 73;
  16132. var COMMENT_STATE = 91;
  16133. var HCRC_STATE = 103;
  16134. var BUSY_STATE = 113;
  16135. var FINISH_STATE = 666;
  16136. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  16137. var BS_BLOCK_DONE = 2; /* block flush performed */
  16138. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  16139. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  16140. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  16141. function err(strm, errorCode) {
  16142. strm.msg = msg[errorCode];
  16143. return errorCode;
  16144. }
  16145. function rank(f) {
  16146. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  16147. }
  16148. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  16149. /* =========================================================================
  16150. * Flush as much pending output as possible. All deflate() output goes
  16151. * through this function so some applications may wish to modify it
  16152. * to avoid allocating a large strm->output buffer and copying into it.
  16153. * (See also read_buf()).
  16154. */
  16155. function flush_pending(strm) {
  16156. var s = strm.state;
  16157. //_tr_flush_bits(s);
  16158. var len = s.pending;
  16159. if (len > strm.avail_out) {
  16160. len = strm.avail_out;
  16161. }
  16162. if (len === 0) { return; }
  16163. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  16164. strm.next_out += len;
  16165. s.pending_out += len;
  16166. strm.total_out += len;
  16167. strm.avail_out -= len;
  16168. s.pending -= len;
  16169. if (s.pending === 0) {
  16170. s.pending_out = 0;
  16171. }
  16172. }
  16173. function flush_block_only(s, last) {
  16174. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  16175. s.block_start = s.strstart;
  16176. flush_pending(s.strm);
  16177. }
  16178. function put_byte(s, b) {
  16179. s.pending_buf[s.pending++] = b;
  16180. }
  16181. /* =========================================================================
  16182. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  16183. * IN assertion: the stream state is correct and there is enough room in
  16184. * pending_buf.
  16185. */
  16186. function putShortMSB(s, b) {
  16187. // put_byte(s, (Byte)(b >> 8));
  16188. // put_byte(s, (Byte)(b & 0xff));
  16189. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  16190. s.pending_buf[s.pending++] = b & 0xff;
  16191. }
  16192. /* ===========================================================================
  16193. * Read a new buffer from the current input stream, update the adler32
  16194. * and total number of bytes read. All deflate() input goes through
  16195. * this function so some applications may wish to modify it to avoid
  16196. * allocating a large strm->input buffer and copying from it.
  16197. * (See also flush_pending()).
  16198. */
  16199. function read_buf(strm, buf, start, size) {
  16200. var len = strm.avail_in;
  16201. if (len > size) { len = size; }
  16202. if (len === 0) { return 0; }
  16203. strm.avail_in -= len;
  16204. // zmemcpy(buf, strm->next_in, len);
  16205. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  16206. if (strm.state.wrap === 1) {
  16207. strm.adler = adler32(strm.adler, buf, len, start);
  16208. }
  16209. else if (strm.state.wrap === 2) {
  16210. strm.adler = crc32(strm.adler, buf, len, start);
  16211. }
  16212. strm.next_in += len;
  16213. strm.total_in += len;
  16214. return len;
  16215. }
  16216. /* ===========================================================================
  16217. * Set match_start to the longest match starting at the given string and
  16218. * return its length. Matches shorter or equal to prev_length are discarded,
  16219. * in which case the result is equal to prev_length and match_start is
  16220. * garbage.
  16221. * IN assertions: cur_match is the head of the hash chain for the current
  16222. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  16223. * OUT assertion: the match length is not greater than s->lookahead.
  16224. */
  16225. function longest_match(s, cur_match) {
  16226. var chain_length = s.max_chain_length; /* max hash chain length */
  16227. var scan = s.strstart; /* current string */
  16228. var match; /* matched string */
  16229. var len; /* length of current match */
  16230. var best_len = s.prev_length; /* best match length so far */
  16231. var nice_match = s.nice_match; /* stop if match long enough */
  16232. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  16233. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  16234. var _win = s.window; // shortcut
  16235. var wmask = s.w_mask;
  16236. var prev = s.prev;
  16237. /* Stop when cur_match becomes <= limit. To simplify the code,
  16238. * we prevent matches with the string of window index 0.
  16239. */
  16240. var strend = s.strstart + MAX_MATCH;
  16241. var scan_end1 = _win[scan + best_len - 1];
  16242. var scan_end = _win[scan + best_len];
  16243. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  16244. * It is easy to get rid of this optimization if necessary.
  16245. */
  16246. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  16247. /* Do not waste too much time if we already have a good match: */
  16248. if (s.prev_length >= s.good_match) {
  16249. chain_length >>= 2;
  16250. }
  16251. /* Do not look for matches beyond the end of the input. This is necessary
  16252. * to make deflate deterministic.
  16253. */
  16254. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  16255. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  16256. do {
  16257. // Assert(cur_match < s->strstart, "no future");
  16258. match = cur_match;
  16259. /* Skip to next match if the match length cannot increase
  16260. * or if the match length is less than 2. Note that the checks below
  16261. * for insufficient lookahead only occur occasionally for performance
  16262. * reasons. Therefore uninitialized memory will be accessed, and
  16263. * conditional jumps will be made that depend on those values.
  16264. * However the length of the match is limited to the lookahead, so
  16265. * the output of deflate is not affected by the uninitialized values.
  16266. */
  16267. if (_win[match + best_len] !== scan_end ||
  16268. _win[match + best_len - 1] !== scan_end1 ||
  16269. _win[match] !== _win[scan] ||
  16270. _win[++match] !== _win[scan + 1]) {
  16271. continue;
  16272. }
  16273. /* The check at best_len-1 can be removed because it will be made
  16274. * again later. (This heuristic is not always a win.)
  16275. * It is not necessary to compare scan[2] and match[2] since they
  16276. * are always equal when the other bytes match, given that
  16277. * the hash keys are equal and that HASH_BITS >= 8.
  16278. */
  16279. scan += 2;
  16280. match++;
  16281. // Assert(*scan == *match, "match[2]?");
  16282. /* We check for insufficient lookahead only every 8th comparison;
  16283. * the 256th check will be made at strstart+258.
  16284. */
  16285. do {
  16286. /*jshint noempty:false*/
  16287. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  16288. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  16289. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  16290. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  16291. scan < strend);
  16292. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  16293. len = MAX_MATCH - (strend - scan);
  16294. scan = strend - MAX_MATCH;
  16295. if (len > best_len) {
  16296. s.match_start = cur_match;
  16297. best_len = len;
  16298. if (len >= nice_match) {
  16299. break;
  16300. }
  16301. scan_end1 = _win[scan + best_len - 1];
  16302. scan_end = _win[scan + best_len];
  16303. }
  16304. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  16305. if (best_len <= s.lookahead) {
  16306. return best_len;
  16307. }
  16308. return s.lookahead;
  16309. }
  16310. /* ===========================================================================
  16311. * Fill the window when the lookahead becomes insufficient.
  16312. * Updates strstart and lookahead.
  16313. *
  16314. * IN assertion: lookahead < MIN_LOOKAHEAD
  16315. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  16316. * At least one byte has been read, or avail_in == 0; reads are
  16317. * performed for at least two bytes (required for the zip translate_eol
  16318. * option -- not supported here).
  16319. */
  16320. function fill_window(s) {
  16321. var _w_size = s.w_size;
  16322. var p, n, m, more, str;
  16323. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  16324. do {
  16325. more = s.window_size - s.lookahead - s.strstart;
  16326. // JS ints have 32 bit, block below not needed
  16327. /* Deal with !@#$% 64K limit: */
  16328. //if (sizeof(int) <= 2) {
  16329. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  16330. // more = wsize;
  16331. //
  16332. // } else if (more == (unsigned)(-1)) {
  16333. // /* Very unlikely, but possible on 16 bit machine if
  16334. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  16335. // */
  16336. // more--;
  16337. // }
  16338. //}
  16339. /* If the window is almost full and there is insufficient lookahead,
  16340. * move the upper half to the lower one to make room in the upper half.
  16341. */
  16342. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  16343. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  16344. s.match_start -= _w_size;
  16345. s.strstart -= _w_size;
  16346. /* we now have strstart >= MAX_DIST */
  16347. s.block_start -= _w_size;
  16348. /* Slide the hash table (could be avoided with 32 bit values
  16349. at the expense of memory usage). We slide even when level == 0
  16350. to keep the hash table consistent if we switch back to level > 0
  16351. later. (Using level 0 permanently is not an optimal usage of
  16352. zlib, so we don't care about this pathological case.)
  16353. */
  16354. n = s.hash_size;
  16355. p = n;
  16356. do {
  16357. m = s.head[--p];
  16358. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  16359. } while (--n);
  16360. n = _w_size;
  16361. p = n;
  16362. do {
  16363. m = s.prev[--p];
  16364. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  16365. /* If n is not on any hash chain, prev[n] is garbage but
  16366. * its value will never be used.
  16367. */
  16368. } while (--n);
  16369. more += _w_size;
  16370. }
  16371. if (s.strm.avail_in === 0) {
  16372. break;
  16373. }
  16374. /* If there was no sliding:
  16375. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  16376. * more == window_size - lookahead - strstart
  16377. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  16378. * => more >= window_size - 2*WSIZE + 2
  16379. * In the BIG_MEM or MMAP case (not yet supported),
  16380. * window_size == input_size + MIN_LOOKAHEAD &&
  16381. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  16382. * Otherwise, window_size == 2*WSIZE so more >= 2.
  16383. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  16384. */
  16385. //Assert(more >= 2, "more < 2");
  16386. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  16387. s.lookahead += n;
  16388. /* Initialize the hash value now that we have some input: */
  16389. if (s.lookahead + s.insert >= MIN_MATCH) {
  16390. str = s.strstart - s.insert;
  16391. s.ins_h = s.window[str];
  16392. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  16393. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  16394. //#if MIN_MATCH != 3
  16395. // Call update_hash() MIN_MATCH-3 more times
  16396. //#endif
  16397. while (s.insert) {
  16398. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  16399. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  16400. s.prev[str & s.w_mask] = s.head[s.ins_h];
  16401. s.head[s.ins_h] = str;
  16402. str++;
  16403. s.insert--;
  16404. if (s.lookahead + s.insert < MIN_MATCH) {
  16405. break;
  16406. }
  16407. }
  16408. }
  16409. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  16410. * but this is not important since only literal bytes will be emitted.
  16411. */
  16412. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  16413. /* If the WIN_INIT bytes after the end of the current data have never been
  16414. * written, then zero those bytes in order to avoid memory check reports of
  16415. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  16416. * the longest match routines. Update the high water mark for the next
  16417. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  16418. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  16419. */
  16420. // if (s.high_water < s.window_size) {
  16421. // var curr = s.strstart + s.lookahead;
  16422. // var init = 0;
  16423. //
  16424. // if (s.high_water < curr) {
  16425. // /* Previous high water mark below current data -- zero WIN_INIT
  16426. // * bytes or up to end of window, whichever is less.
  16427. // */
  16428. // init = s.window_size - curr;
  16429. // if (init > WIN_INIT)
  16430. // init = WIN_INIT;
  16431. // zmemzero(s->window + curr, (unsigned)init);
  16432. // s->high_water = curr + init;
  16433. // }
  16434. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  16435. // /* High water mark at or above current data, but below current data
  16436. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  16437. // * to end of window, whichever is less.
  16438. // */
  16439. // init = (ulg)curr + WIN_INIT - s->high_water;
  16440. // if (init > s->window_size - s->high_water)
  16441. // init = s->window_size - s->high_water;
  16442. // zmemzero(s->window + s->high_water, (unsigned)init);
  16443. // s->high_water += init;
  16444. // }
  16445. // }
  16446. //
  16447. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  16448. // "not enough room for search");
  16449. }
  16450. /* ===========================================================================
  16451. * Copy without compression as much as possible from the input stream, return
  16452. * the current block state.
  16453. * This function does not insert new strings in the dictionary since
  16454. * uncompressible data is probably not useful. This function is used
  16455. * only for the level=0 compression option.
  16456. * NOTE: this function should be optimized to avoid extra copying from
  16457. * window to pending_buf.
  16458. */
  16459. function deflate_stored(s, flush) {
  16460. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  16461. * to pending_buf_size, and each stored block has a 5 byte header:
  16462. */
  16463. var max_block_size = 0xffff;
  16464. if (max_block_size > s.pending_buf_size - 5) {
  16465. max_block_size = s.pending_buf_size - 5;
  16466. }
  16467. /* Copy as much as possible from input to output: */
  16468. for (;;) {
  16469. /* Fill the window as much as possible: */
  16470. if (s.lookahead <= 1) {
  16471. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  16472. // s->block_start >= (long)s->w_size, "slide too late");
  16473. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  16474. // s.block_start >= s.w_size)) {
  16475. // throw new Error("slide too late");
  16476. // }
  16477. fill_window(s);
  16478. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  16479. return BS_NEED_MORE;
  16480. }
  16481. if (s.lookahead === 0) {
  16482. break;
  16483. }
  16484. /* flush the current block */
  16485. }
  16486. //Assert(s->block_start >= 0L, "block gone");
  16487. // if (s.block_start < 0) throw new Error("block gone");
  16488. s.strstart += s.lookahead;
  16489. s.lookahead = 0;
  16490. /* Emit a stored block if pending_buf will be full: */
  16491. var max_start = s.block_start + max_block_size;
  16492. if (s.strstart === 0 || s.strstart >= max_start) {
  16493. /* strstart == 0 is possible when wraparound on 16-bit machine */
  16494. s.lookahead = s.strstart - max_start;
  16495. s.strstart = max_start;
  16496. /*** FLUSH_BLOCK(s, 0); ***/
  16497. flush_block_only(s, false);
  16498. if (s.strm.avail_out === 0) {
  16499. return BS_NEED_MORE;
  16500. }
  16501. /***/
  16502. }
  16503. /* Flush if we may have to slide, otherwise block_start may become
  16504. * negative and the data will be gone:
  16505. */
  16506. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  16507. /*** FLUSH_BLOCK(s, 0); ***/
  16508. flush_block_only(s, false);
  16509. if (s.strm.avail_out === 0) {
  16510. return BS_NEED_MORE;
  16511. }
  16512. /***/
  16513. }
  16514. }
  16515. s.insert = 0;
  16516. if (flush === Z_FINISH) {
  16517. /*** FLUSH_BLOCK(s, 1); ***/
  16518. flush_block_only(s, true);
  16519. if (s.strm.avail_out === 0) {
  16520. return BS_FINISH_STARTED;
  16521. }
  16522. /***/
  16523. return BS_FINISH_DONE;
  16524. }
  16525. if (s.strstart > s.block_start) {
  16526. /*** FLUSH_BLOCK(s, 0); ***/
  16527. flush_block_only(s, false);
  16528. if (s.strm.avail_out === 0) {
  16529. return BS_NEED_MORE;
  16530. }
  16531. /***/
  16532. }
  16533. return BS_NEED_MORE;
  16534. }
  16535. /* ===========================================================================
  16536. * Compress as much as possible from the input stream, return the current
  16537. * block state.
  16538. * This function does not perform lazy evaluation of matches and inserts
  16539. * new strings in the dictionary only for unmatched strings or for short
  16540. * matches. It is used only for the fast compression options.
  16541. */
  16542. function deflate_fast(s, flush) {
  16543. var hash_head; /* head of the hash chain */
  16544. var bflush; /* set if current block must be flushed */
  16545. for (;;) {
  16546. /* Make sure that we always have enough lookahead, except
  16547. * at the end of the input file. We need MAX_MATCH bytes
  16548. * for the next match, plus MIN_MATCH bytes to insert the
  16549. * string following the next match.
  16550. */
  16551. if (s.lookahead < MIN_LOOKAHEAD) {
  16552. fill_window(s);
  16553. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  16554. return BS_NEED_MORE;
  16555. }
  16556. if (s.lookahead === 0) {
  16557. break; /* flush the current block */
  16558. }
  16559. }
  16560. /* Insert the string window[strstart .. strstart+2] in the
  16561. * dictionary, and set hash_head to the head of the hash chain:
  16562. */
  16563. hash_head = 0/*NIL*/;
  16564. if (s.lookahead >= MIN_MATCH) {
  16565. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16566. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16567. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16568. s.head[s.ins_h] = s.strstart;
  16569. /***/
  16570. }
  16571. /* Find the longest match, discarding those <= prev_length.
  16572. * At this point we have always match_length < MIN_MATCH
  16573. */
  16574. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  16575. /* To simplify the code, we prevent matches with the string
  16576. * of window index 0 (in particular we have to avoid a match
  16577. * of the string with itself at the start of the input file).
  16578. */
  16579. s.match_length = longest_match(s, hash_head);
  16580. /* longest_match() sets match_start */
  16581. }
  16582. if (s.match_length >= MIN_MATCH) {
  16583. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  16584. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  16585. s.match_length - MIN_MATCH, bflush); ***/
  16586. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  16587. s.lookahead -= s.match_length;
  16588. /* Insert new strings in the hash table only if the match length
  16589. * is not too large. This saves time but degrades compression.
  16590. */
  16591. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  16592. s.match_length--; /* string at strstart already in table */
  16593. do {
  16594. s.strstart++;
  16595. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16596. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16597. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16598. s.head[s.ins_h] = s.strstart;
  16599. /***/
  16600. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  16601. * always MIN_MATCH bytes ahead.
  16602. */
  16603. } while (--s.match_length !== 0);
  16604. s.strstart++;
  16605. } else
  16606. {
  16607. s.strstart += s.match_length;
  16608. s.match_length = 0;
  16609. s.ins_h = s.window[s.strstart];
  16610. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  16611. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  16612. //#if MIN_MATCH != 3
  16613. // Call UPDATE_HASH() MIN_MATCH-3 more times
  16614. //#endif
  16615. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  16616. * matter since it will be recomputed at next deflate call.
  16617. */
  16618. }
  16619. } else {
  16620. /* No match, output a literal byte */
  16621. //Tracevv((stderr,"%c", s.window[s.strstart]));
  16622. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16623. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16624. s.lookahead--;
  16625. s.strstart++;
  16626. }
  16627. if (bflush) {
  16628. /*** FLUSH_BLOCK(s, 0); ***/
  16629. flush_block_only(s, false);
  16630. if (s.strm.avail_out === 0) {
  16631. return BS_NEED_MORE;
  16632. }
  16633. /***/
  16634. }
  16635. }
  16636. s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  16637. if (flush === Z_FINISH) {
  16638. /*** FLUSH_BLOCK(s, 1); ***/
  16639. flush_block_only(s, true);
  16640. if (s.strm.avail_out === 0) {
  16641. return BS_FINISH_STARTED;
  16642. }
  16643. /***/
  16644. return BS_FINISH_DONE;
  16645. }
  16646. if (s.last_lit) {
  16647. /*** FLUSH_BLOCK(s, 0); ***/
  16648. flush_block_only(s, false);
  16649. if (s.strm.avail_out === 0) {
  16650. return BS_NEED_MORE;
  16651. }
  16652. /***/
  16653. }
  16654. return BS_BLOCK_DONE;
  16655. }
  16656. /* ===========================================================================
  16657. * Same as above, but achieves better compression. We use a lazy
  16658. * evaluation for matches: a match is finally adopted only if there is
  16659. * no better match at the next window position.
  16660. */
  16661. function deflate_slow(s, flush) {
  16662. var hash_head; /* head of hash chain */
  16663. var bflush; /* set if current block must be flushed */
  16664. var max_insert;
  16665. /* Process the input block. */
  16666. for (;;) {
  16667. /* Make sure that we always have enough lookahead, except
  16668. * at the end of the input file. We need MAX_MATCH bytes
  16669. * for the next match, plus MIN_MATCH bytes to insert the
  16670. * string following the next match.
  16671. */
  16672. if (s.lookahead < MIN_LOOKAHEAD) {
  16673. fill_window(s);
  16674. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  16675. return BS_NEED_MORE;
  16676. }
  16677. if (s.lookahead === 0) { break; } /* flush the current block */
  16678. }
  16679. /* Insert the string window[strstart .. strstart+2] in the
  16680. * dictionary, and set hash_head to the head of the hash chain:
  16681. */
  16682. hash_head = 0/*NIL*/;
  16683. if (s.lookahead >= MIN_MATCH) {
  16684. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16685. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16686. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16687. s.head[s.ins_h] = s.strstart;
  16688. /***/
  16689. }
  16690. /* Find the longest match, discarding those <= prev_length.
  16691. */
  16692. s.prev_length = s.match_length;
  16693. s.prev_match = s.match_start;
  16694. s.match_length = MIN_MATCH - 1;
  16695. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  16696. s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  16697. /* To simplify the code, we prevent matches with the string
  16698. * of window index 0 (in particular we have to avoid a match
  16699. * of the string with itself at the start of the input file).
  16700. */
  16701. s.match_length = longest_match(s, hash_head);
  16702. /* longest_match() sets match_start */
  16703. if (s.match_length <= 5 &&
  16704. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  16705. /* If prev_match is also MIN_MATCH, match_start is garbage
  16706. * but we will ignore the current match anyway.
  16707. */
  16708. s.match_length = MIN_MATCH - 1;
  16709. }
  16710. }
  16711. /* If there was a match at the previous step and the current
  16712. * match is not better, output the previous match:
  16713. */
  16714. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  16715. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  16716. /* Do not insert strings in hash table beyond this. */
  16717. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  16718. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  16719. s.prev_length - MIN_MATCH, bflush);***/
  16720. bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  16721. /* Insert in hash table all strings up to the end of the match.
  16722. * strstart-1 and strstart are already inserted. If there is not
  16723. * enough lookahead, the last two strings are not inserted in
  16724. * the hash table.
  16725. */
  16726. s.lookahead -= s.prev_length - 1;
  16727. s.prev_length -= 2;
  16728. do {
  16729. if (++s.strstart <= max_insert) {
  16730. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16731. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16732. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16733. s.head[s.ins_h] = s.strstart;
  16734. /***/
  16735. }
  16736. } while (--s.prev_length !== 0);
  16737. s.match_available = 0;
  16738. s.match_length = MIN_MATCH - 1;
  16739. s.strstart++;
  16740. if (bflush) {
  16741. /*** FLUSH_BLOCK(s, 0); ***/
  16742. flush_block_only(s, false);
  16743. if (s.strm.avail_out === 0) {
  16744. return BS_NEED_MORE;
  16745. }
  16746. /***/
  16747. }
  16748. } else if (s.match_available) {
  16749. /* If there was no match at the previous position, output a
  16750. * single literal. If there was a match but the current match
  16751. * is longer, truncate the previous match to a single literal.
  16752. */
  16753. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  16754. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  16755. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  16756. if (bflush) {
  16757. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  16758. flush_block_only(s, false);
  16759. /***/
  16760. }
  16761. s.strstart++;
  16762. s.lookahead--;
  16763. if (s.strm.avail_out === 0) {
  16764. return BS_NEED_MORE;
  16765. }
  16766. } else {
  16767. /* There is no previous match to compare with, wait for
  16768. * the next step to decide.
  16769. */
  16770. s.match_available = 1;
  16771. s.strstart++;
  16772. s.lookahead--;
  16773. }
  16774. }
  16775. //Assert (flush != Z_NO_FLUSH, "no flush?");
  16776. if (s.match_available) {
  16777. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  16778. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  16779. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  16780. s.match_available = 0;
  16781. }
  16782. s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  16783. if (flush === Z_FINISH) {
  16784. /*** FLUSH_BLOCK(s, 1); ***/
  16785. flush_block_only(s, true);
  16786. if (s.strm.avail_out === 0) {
  16787. return BS_FINISH_STARTED;
  16788. }
  16789. /***/
  16790. return BS_FINISH_DONE;
  16791. }
  16792. if (s.last_lit) {
  16793. /*** FLUSH_BLOCK(s, 0); ***/
  16794. flush_block_only(s, false);
  16795. if (s.strm.avail_out === 0) {
  16796. return BS_NEED_MORE;
  16797. }
  16798. /***/
  16799. }
  16800. return BS_BLOCK_DONE;
  16801. }
  16802. /* ===========================================================================
  16803. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  16804. * one. Do not maintain a hash table. (It will be regenerated if this run of
  16805. * deflate switches away from Z_RLE.)
  16806. */
  16807. function deflate_rle(s, flush) {
  16808. var bflush; /* set if current block must be flushed */
  16809. var prev; /* byte at distance one to match */
  16810. var scan, strend; /* scan goes up to strend for length of run */
  16811. var _win = s.window;
  16812. for (;;) {
  16813. /* Make sure that we always have enough lookahead, except
  16814. * at the end of the input file. We need MAX_MATCH bytes
  16815. * for the longest run, plus one for the unrolled loop.
  16816. */
  16817. if (s.lookahead <= MAX_MATCH) {
  16818. fill_window(s);
  16819. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  16820. return BS_NEED_MORE;
  16821. }
  16822. if (s.lookahead === 0) { break; } /* flush the current block */
  16823. }
  16824. /* See how many times the previous byte repeats */
  16825. s.match_length = 0;
  16826. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  16827. scan = s.strstart - 1;
  16828. prev = _win[scan];
  16829. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  16830. strend = s.strstart + MAX_MATCH;
  16831. do {
  16832. /*jshint noempty:false*/
  16833. } while (prev === _win[++scan] && prev === _win[++scan] &&
  16834. prev === _win[++scan] && prev === _win[++scan] &&
  16835. prev === _win[++scan] && prev === _win[++scan] &&
  16836. prev === _win[++scan] && prev === _win[++scan] &&
  16837. scan < strend);
  16838. s.match_length = MAX_MATCH - (strend - scan);
  16839. if (s.match_length > s.lookahead) {
  16840. s.match_length = s.lookahead;
  16841. }
  16842. }
  16843. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  16844. }
  16845. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  16846. if (s.match_length >= MIN_MATCH) {
  16847. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  16848. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  16849. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  16850. s.lookahead -= s.match_length;
  16851. s.strstart += s.match_length;
  16852. s.match_length = 0;
  16853. } else {
  16854. /* No match, output a literal byte */
  16855. //Tracevv((stderr,"%c", s->window[s->strstart]));
  16856. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16857. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16858. s.lookahead--;
  16859. s.strstart++;
  16860. }
  16861. if (bflush) {
  16862. /*** FLUSH_BLOCK(s, 0); ***/
  16863. flush_block_only(s, false);
  16864. if (s.strm.avail_out === 0) {
  16865. return BS_NEED_MORE;
  16866. }
  16867. /***/
  16868. }
  16869. }
  16870. s.insert = 0;
  16871. if (flush === Z_FINISH) {
  16872. /*** FLUSH_BLOCK(s, 1); ***/
  16873. flush_block_only(s, true);
  16874. if (s.strm.avail_out === 0) {
  16875. return BS_FINISH_STARTED;
  16876. }
  16877. /***/
  16878. return BS_FINISH_DONE;
  16879. }
  16880. if (s.last_lit) {
  16881. /*** FLUSH_BLOCK(s, 0); ***/
  16882. flush_block_only(s, false);
  16883. if (s.strm.avail_out === 0) {
  16884. return BS_NEED_MORE;
  16885. }
  16886. /***/
  16887. }
  16888. return BS_BLOCK_DONE;
  16889. }
  16890. /* ===========================================================================
  16891. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  16892. * (It will be regenerated if this run of deflate switches away from Huffman.)
  16893. */
  16894. function deflate_huff(s, flush) {
  16895. var bflush; /* set if current block must be flushed */
  16896. for (;;) {
  16897. /* Make sure that we have a literal to write. */
  16898. if (s.lookahead === 0) {
  16899. fill_window(s);
  16900. if (s.lookahead === 0) {
  16901. if (flush === Z_NO_FLUSH) {
  16902. return BS_NEED_MORE;
  16903. }
  16904. break; /* flush the current block */
  16905. }
  16906. }
  16907. /* Output a literal byte */
  16908. s.match_length = 0;
  16909. //Tracevv((stderr,"%c", s->window[s->strstart]));
  16910. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16911. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16912. s.lookahead--;
  16913. s.strstart++;
  16914. if (bflush) {
  16915. /*** FLUSH_BLOCK(s, 0); ***/
  16916. flush_block_only(s, false);
  16917. if (s.strm.avail_out === 0) {
  16918. return BS_NEED_MORE;
  16919. }
  16920. /***/
  16921. }
  16922. }
  16923. s.insert = 0;
  16924. if (flush === Z_FINISH) {
  16925. /*** FLUSH_BLOCK(s, 1); ***/
  16926. flush_block_only(s, true);
  16927. if (s.strm.avail_out === 0) {
  16928. return BS_FINISH_STARTED;
  16929. }
  16930. /***/
  16931. return BS_FINISH_DONE;
  16932. }
  16933. if (s.last_lit) {
  16934. /*** FLUSH_BLOCK(s, 0); ***/
  16935. flush_block_only(s, false);
  16936. if (s.strm.avail_out === 0) {
  16937. return BS_NEED_MORE;
  16938. }
  16939. /***/
  16940. }
  16941. return BS_BLOCK_DONE;
  16942. }
  16943. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  16944. * the desired pack level (0..9). The values given below have been tuned to
  16945. * exclude worst case performance for pathological files. Better values may be
  16946. * found for specific files.
  16947. */
  16948. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  16949. this.good_length = good_length;
  16950. this.max_lazy = max_lazy;
  16951. this.nice_length = nice_length;
  16952. this.max_chain = max_chain;
  16953. this.func = func;
  16954. }
  16955. var configuration_table;
  16956. configuration_table = [
  16957. /* good lazy nice chain */
  16958. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  16959. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  16960. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  16961. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  16962. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  16963. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  16964. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  16965. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  16966. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  16967. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  16968. ];
  16969. /* ===========================================================================
  16970. * Initialize the "longest match" routines for a new zlib stream
  16971. */
  16972. function lm_init(s) {
  16973. s.window_size = 2 * s.w_size;
  16974. /*** CLEAR_HASH(s); ***/
  16975. zero(s.head); // Fill with NIL (= 0);
  16976. /* Set the default configuration parameters:
  16977. */
  16978. s.max_lazy_match = configuration_table[s.level].max_lazy;
  16979. s.good_match = configuration_table[s.level].good_length;
  16980. s.nice_match = configuration_table[s.level].nice_length;
  16981. s.max_chain_length = configuration_table[s.level].max_chain;
  16982. s.strstart = 0;
  16983. s.block_start = 0;
  16984. s.lookahead = 0;
  16985. s.insert = 0;
  16986. s.match_length = s.prev_length = MIN_MATCH - 1;
  16987. s.match_available = 0;
  16988. s.ins_h = 0;
  16989. }
  16990. function DeflateState() {
  16991. this.strm = null; /* pointer back to this zlib stream */
  16992. this.status = 0; /* as the name implies */
  16993. this.pending_buf = null; /* output still pending */
  16994. this.pending_buf_size = 0; /* size of pending_buf */
  16995. this.pending_out = 0; /* next pending byte to output to the stream */
  16996. this.pending = 0; /* nb of bytes in the pending buffer */
  16997. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  16998. this.gzhead = null; /* gzip header information to write */
  16999. this.gzindex = 0; /* where in extra, name, or comment */
  17000. this.method = Z_DEFLATED; /* can only be DEFLATED */
  17001. this.last_flush = -1; /* value of flush param for previous deflate call */
  17002. this.w_size = 0; /* LZ77 window size (32K by default) */
  17003. this.w_bits = 0; /* log2(w_size) (8..16) */
  17004. this.w_mask = 0; /* w_size - 1 */
  17005. this.window = null;
  17006. /* Sliding window. Input bytes are read into the second half of the window,
  17007. * and move to the first half later to keep a dictionary of at least wSize
  17008. * bytes. With this organization, matches are limited to a distance of
  17009. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  17010. * performed with a length multiple of the block size.
  17011. */
  17012. this.window_size = 0;
  17013. /* Actual size of window: 2*wSize, except when the user input buffer
  17014. * is directly used as sliding window.
  17015. */
  17016. this.prev = null;
  17017. /* Link to older string with same hash index. To limit the size of this
  17018. * array to 64K, this link is maintained only for the last 32K strings.
  17019. * An index in this array is thus a window index modulo 32K.
  17020. */
  17021. this.head = null; /* Heads of the hash chains or NIL. */
  17022. this.ins_h = 0; /* hash index of string to be inserted */
  17023. this.hash_size = 0; /* number of elements in hash table */
  17024. this.hash_bits = 0; /* log2(hash_size) */
  17025. this.hash_mask = 0; /* hash_size-1 */
  17026. this.hash_shift = 0;
  17027. /* Number of bits by which ins_h must be shifted at each input
  17028. * step. It must be such that after MIN_MATCH steps, the oldest
  17029. * byte no longer takes part in the hash key, that is:
  17030. * hash_shift * MIN_MATCH >= hash_bits
  17031. */
  17032. this.block_start = 0;
  17033. /* Window position at the beginning of the current output block. Gets
  17034. * negative when the window is moved backwards.
  17035. */
  17036. this.match_length = 0; /* length of best match */
  17037. this.prev_match = 0; /* previous match */
  17038. this.match_available = 0; /* set if previous match exists */
  17039. this.strstart = 0; /* start of string to insert */
  17040. this.match_start = 0; /* start of matching string */
  17041. this.lookahead = 0; /* number of valid bytes ahead in window */
  17042. this.prev_length = 0;
  17043. /* Length of the best match at previous step. Matches not greater than this
  17044. * are discarded. This is used in the lazy match evaluation.
  17045. */
  17046. this.max_chain_length = 0;
  17047. /* To speed up deflation, hash chains are never searched beyond this
  17048. * length. A higher limit improves compression ratio but degrades the
  17049. * speed.
  17050. */
  17051. this.max_lazy_match = 0;
  17052. /* Attempt to find a better match only when the current match is strictly
  17053. * smaller than this value. This mechanism is used only for compression
  17054. * levels >= 4.
  17055. */
  17056. // That's alias to max_lazy_match, don't use directly
  17057. //this.max_insert_length = 0;
  17058. /* Insert new strings in the hash table only if the match length is not
  17059. * greater than this length. This saves time but degrades compression.
  17060. * max_insert_length is used only for compression levels <= 3.
  17061. */
  17062. this.level = 0; /* compression level (1..9) */
  17063. this.strategy = 0; /* favor or force Huffman coding*/
  17064. this.good_match = 0;
  17065. /* Use a faster search when the previous match is longer than this */
  17066. this.nice_match = 0; /* Stop searching when current match exceeds this */
  17067. /* used by trees.c: */
  17068. /* Didn't use ct_data typedef below to suppress compiler warning */
  17069. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  17070. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  17071. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  17072. // Use flat array of DOUBLE size, with interleaved fata,
  17073. // because JS does not support effective
  17074. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  17075. this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
  17076. this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
  17077. zero(this.dyn_ltree);
  17078. zero(this.dyn_dtree);
  17079. zero(this.bl_tree);
  17080. this.l_desc = null; /* desc. for literal tree */
  17081. this.d_desc = null; /* desc. for distance tree */
  17082. this.bl_desc = null; /* desc. for bit length tree */
  17083. //ush bl_count[MAX_BITS+1];
  17084. this.bl_count = new utils.Buf16(MAX_BITS + 1);
  17085. /* number of codes at each bit length for an optimal tree */
  17086. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  17087. this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
  17088. zero(this.heap);
  17089. this.heap_len = 0; /* number of elements in the heap */
  17090. this.heap_max = 0; /* element of largest frequency */
  17091. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  17092. * The same heap array is used to build all trees.
  17093. */
  17094. this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  17095. zero(this.depth);
  17096. /* Depth of each subtree used as tie breaker for trees of equal frequency
  17097. */
  17098. this.l_buf = 0; /* buffer index for literals or lengths */
  17099. this.lit_bufsize = 0;
  17100. /* Size of match buffer for literals/lengths. There are 4 reasons for
  17101. * limiting lit_bufsize to 64K:
  17102. * - frequencies can be kept in 16 bit counters
  17103. * - if compression is not successful for the first block, all input
  17104. * data is still in the window so we can still emit a stored block even
  17105. * when input comes from standard input. (This can also be done for
  17106. * all blocks if lit_bufsize is not greater than 32K.)
  17107. * - if compression is not successful for a file smaller than 64K, we can
  17108. * even emit a stored file instead of a stored block (saving 5 bytes).
  17109. * This is applicable only for zip (not gzip or zlib).
  17110. * - creating new Huffman trees less frequently may not provide fast
  17111. * adaptation to changes in the input data statistics. (Take for
  17112. * example a binary file with poorly compressible code followed by
  17113. * a highly compressible string table.) Smaller buffer sizes give
  17114. * fast adaptation but have of course the overhead of transmitting
  17115. * trees more frequently.
  17116. * - I can't count above 4
  17117. */
  17118. this.last_lit = 0; /* running index in l_buf */
  17119. this.d_buf = 0;
  17120. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  17121. * the same number of elements. To use different lengths, an extra flag
  17122. * array would be necessary.
  17123. */
  17124. this.opt_len = 0; /* bit length of current block with optimal trees */
  17125. this.static_len = 0; /* bit length of current block with static trees */
  17126. this.matches = 0; /* number of string matches in current block */
  17127. this.insert = 0; /* bytes at end of window left to insert */
  17128. this.bi_buf = 0;
  17129. /* Output buffer. bits are inserted starting at the bottom (least
  17130. * significant bits).
  17131. */
  17132. this.bi_valid = 0;
  17133. /* Number of valid bits in bi_buf. All bits above the last valid bit
  17134. * are always zero.
  17135. */
  17136. // Used for window memory init. We safely ignore it for JS. That makes
  17137. // sense only for pointers and memory check tools.
  17138. //this.high_water = 0;
  17139. /* High water mark offset in window for initialized bytes -- bytes above
  17140. * this are set to zero in order to avoid memory check warnings when
  17141. * longest match routines access bytes past the input. This is then
  17142. * updated to the new high water mark.
  17143. */
  17144. }
  17145. function deflateResetKeep(strm) {
  17146. var s;
  17147. if (!strm || !strm.state) {
  17148. return err(strm, Z_STREAM_ERROR);
  17149. }
  17150. strm.total_in = strm.total_out = 0;
  17151. strm.data_type = Z_UNKNOWN;
  17152. s = strm.state;
  17153. s.pending = 0;
  17154. s.pending_out = 0;
  17155. if (s.wrap < 0) {
  17156. s.wrap = -s.wrap;
  17157. /* was made negative by deflate(..., Z_FINISH); */
  17158. }
  17159. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  17160. strm.adler = (s.wrap === 2) ?
  17161. 0 // crc32(0, Z_NULL, 0)
  17162. :
  17163. 1; // adler32(0, Z_NULL, 0)
  17164. s.last_flush = Z_NO_FLUSH;
  17165. trees._tr_init(s);
  17166. return Z_OK;
  17167. }
  17168. function deflateReset(strm) {
  17169. var ret = deflateResetKeep(strm);
  17170. if (ret === Z_OK) {
  17171. lm_init(strm.state);
  17172. }
  17173. return ret;
  17174. }
  17175. function deflateSetHeader(strm, head) {
  17176. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17177. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  17178. strm.state.gzhead = head;
  17179. return Z_OK;
  17180. }
  17181. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  17182. if (!strm) { // === Z_NULL
  17183. return Z_STREAM_ERROR;
  17184. }
  17185. var wrap = 1;
  17186. if (level === Z_DEFAULT_COMPRESSION) {
  17187. level = 6;
  17188. }
  17189. if (windowBits < 0) { /* suppress zlib wrapper */
  17190. wrap = 0;
  17191. windowBits = -windowBits;
  17192. }
  17193. else if (windowBits > 15) {
  17194. wrap = 2; /* write gzip wrapper instead */
  17195. windowBits -= 16;
  17196. }
  17197. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  17198. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  17199. strategy < 0 || strategy > Z_FIXED) {
  17200. return err(strm, Z_STREAM_ERROR);
  17201. }
  17202. if (windowBits === 8) {
  17203. windowBits = 9;
  17204. }
  17205. /* until 256-byte window bug fixed */
  17206. var s = new DeflateState();
  17207. strm.state = s;
  17208. s.strm = strm;
  17209. s.wrap = wrap;
  17210. s.gzhead = null;
  17211. s.w_bits = windowBits;
  17212. s.w_size = 1 << s.w_bits;
  17213. s.w_mask = s.w_size - 1;
  17214. s.hash_bits = memLevel + 7;
  17215. s.hash_size = 1 << s.hash_bits;
  17216. s.hash_mask = s.hash_size - 1;
  17217. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  17218. s.window = new utils.Buf8(s.w_size * 2);
  17219. s.head = new utils.Buf16(s.hash_size);
  17220. s.prev = new utils.Buf16(s.w_size);
  17221. // Don't need mem init magic for JS.
  17222. //s.high_water = 0; /* nothing written to s->window yet */
  17223. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  17224. s.pending_buf_size = s.lit_bufsize * 4;
  17225. //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  17226. //s->pending_buf = (uchf *) overlay;
  17227. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  17228. // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  17229. //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  17230. s.d_buf = 1 * s.lit_bufsize;
  17231. //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  17232. s.l_buf = (1 + 2) * s.lit_bufsize;
  17233. s.level = level;
  17234. s.strategy = strategy;
  17235. s.method = method;
  17236. return deflateReset(strm);
  17237. }
  17238. function deflateInit(strm, level) {
  17239. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  17240. }
  17241. function deflate(strm, flush) {
  17242. var old_flush, s;
  17243. var beg, val; // for gzip header write only
  17244. if (!strm || !strm.state ||
  17245. flush > Z_BLOCK || flush < 0) {
  17246. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  17247. }
  17248. s = strm.state;
  17249. if (!strm.output ||
  17250. (!strm.input && strm.avail_in !== 0) ||
  17251. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  17252. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  17253. }
  17254. s.strm = strm; /* just in case */
  17255. old_flush = s.last_flush;
  17256. s.last_flush = flush;
  17257. /* Write the header */
  17258. if (s.status === INIT_STATE) {
  17259. if (s.wrap === 2) { // GZIP header
  17260. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  17261. put_byte(s, 31);
  17262. put_byte(s, 139);
  17263. put_byte(s, 8);
  17264. if (!s.gzhead) { // s->gzhead == Z_NULL
  17265. put_byte(s, 0);
  17266. put_byte(s, 0);
  17267. put_byte(s, 0);
  17268. put_byte(s, 0);
  17269. put_byte(s, 0);
  17270. put_byte(s, s.level === 9 ? 2 :
  17271. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  17272. 4 : 0));
  17273. put_byte(s, OS_CODE);
  17274. s.status = BUSY_STATE;
  17275. }
  17276. else {
  17277. put_byte(s, (s.gzhead.text ? 1 : 0) +
  17278. (s.gzhead.hcrc ? 2 : 0) +
  17279. (!s.gzhead.extra ? 0 : 4) +
  17280. (!s.gzhead.name ? 0 : 8) +
  17281. (!s.gzhead.comment ? 0 : 16)
  17282. );
  17283. put_byte(s, s.gzhead.time & 0xff);
  17284. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  17285. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  17286. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  17287. put_byte(s, s.level === 9 ? 2 :
  17288. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  17289. 4 : 0));
  17290. put_byte(s, s.gzhead.os & 0xff);
  17291. if (s.gzhead.extra && s.gzhead.extra.length) {
  17292. put_byte(s, s.gzhead.extra.length & 0xff);
  17293. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  17294. }
  17295. if (s.gzhead.hcrc) {
  17296. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  17297. }
  17298. s.gzindex = 0;
  17299. s.status = EXTRA_STATE;
  17300. }
  17301. }
  17302. else // DEFLATE header
  17303. {
  17304. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  17305. var level_flags = -1;
  17306. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  17307. level_flags = 0;
  17308. } else if (s.level < 6) {
  17309. level_flags = 1;
  17310. } else if (s.level === 6) {
  17311. level_flags = 2;
  17312. } else {
  17313. level_flags = 3;
  17314. }
  17315. header |= (level_flags << 6);
  17316. if (s.strstart !== 0) { header |= PRESET_DICT; }
  17317. header += 31 - (header % 31);
  17318. s.status = BUSY_STATE;
  17319. putShortMSB(s, header);
  17320. /* Save the adler32 of the preset dictionary: */
  17321. if (s.strstart !== 0) {
  17322. putShortMSB(s, strm.adler >>> 16);
  17323. putShortMSB(s, strm.adler & 0xffff);
  17324. }
  17325. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  17326. }
  17327. }
  17328. //#ifdef GZIP
  17329. if (s.status === EXTRA_STATE) {
  17330. if (s.gzhead.extra/* != Z_NULL*/) {
  17331. beg = s.pending; /* start of bytes to update crc */
  17332. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  17333. if (s.pending === s.pending_buf_size) {
  17334. if (s.gzhead.hcrc && s.pending > beg) {
  17335. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  17336. }
  17337. flush_pending(strm);
  17338. beg = s.pending;
  17339. if (s.pending === s.pending_buf_size) {
  17340. break;
  17341. }
  17342. }
  17343. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  17344. s.gzindex++;
  17345. }
  17346. if (s.gzhead.hcrc && s.pending > beg) {
  17347. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  17348. }
  17349. if (s.gzindex === s.gzhead.extra.length) {
  17350. s.gzindex = 0;
  17351. s.status = NAME_STATE;
  17352. }
  17353. }
  17354. else {
  17355. s.status = NAME_STATE;
  17356. }
  17357. }
  17358. if (s.status === NAME_STATE) {
  17359. if (s.gzhead.name/* != Z_NULL*/) {
  17360. beg = s.pending; /* start of bytes to update crc */
  17361. //int val;
  17362. do {
  17363. if (s.pending === s.pending_buf_size) {
  17364. if (s.gzhead.hcrc && s.pending > beg) {
  17365. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  17366. }
  17367. flush_pending(strm);
  17368. beg = s.pending;
  17369. if (s.pending === s.pending_buf_size) {
  17370. val = 1;
  17371. break;
  17372. }
  17373. }
  17374. // JS specific: little magic to add zero terminator to end of string
  17375. if (s.gzindex < s.gzhead.name.length) {
  17376. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  17377. } else {
  17378. val = 0;
  17379. }
  17380. put_byte(s, val);
  17381. } while (val !== 0);
  17382. if (s.gzhead.hcrc && s.pending > beg) {
  17383. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  17384. }
  17385. if (val === 0) {
  17386. s.gzindex = 0;
  17387. s.status = COMMENT_STATE;
  17388. }
  17389. }
  17390. else {
  17391. s.status = COMMENT_STATE;
  17392. }
  17393. }
  17394. if (s.status === COMMENT_STATE) {
  17395. if (s.gzhead.comment/* != Z_NULL*/) {
  17396. beg = s.pending; /* start of bytes to update crc */
  17397. //int val;
  17398. do {
  17399. if (s.pending === s.pending_buf_size) {
  17400. if (s.gzhead.hcrc && s.pending > beg) {
  17401. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  17402. }
  17403. flush_pending(strm);
  17404. beg = s.pending;
  17405. if (s.pending === s.pending_buf_size) {
  17406. val = 1;
  17407. break;
  17408. }
  17409. }
  17410. // JS specific: little magic to add zero terminator to end of string
  17411. if (s.gzindex < s.gzhead.comment.length) {
  17412. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  17413. } else {
  17414. val = 0;
  17415. }
  17416. put_byte(s, val);
  17417. } while (val !== 0);
  17418. if (s.gzhead.hcrc && s.pending > beg) {
  17419. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  17420. }
  17421. if (val === 0) {
  17422. s.status = HCRC_STATE;
  17423. }
  17424. }
  17425. else {
  17426. s.status = HCRC_STATE;
  17427. }
  17428. }
  17429. if (s.status === HCRC_STATE) {
  17430. if (s.gzhead.hcrc) {
  17431. if (s.pending + 2 > s.pending_buf_size) {
  17432. flush_pending(strm);
  17433. }
  17434. if (s.pending + 2 <= s.pending_buf_size) {
  17435. put_byte(s, strm.adler & 0xff);
  17436. put_byte(s, (strm.adler >> 8) & 0xff);
  17437. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  17438. s.status = BUSY_STATE;
  17439. }
  17440. }
  17441. else {
  17442. s.status = BUSY_STATE;
  17443. }
  17444. }
  17445. //#endif
  17446. /* Flush as much pending output as possible */
  17447. if (s.pending !== 0) {
  17448. flush_pending(strm);
  17449. if (strm.avail_out === 0) {
  17450. /* Since avail_out is 0, deflate will be called again with
  17451. * more output space, but possibly with both pending and
  17452. * avail_in equal to zero. There won't be anything to do,
  17453. * but this is not an error situation so make sure we
  17454. * return OK instead of BUF_ERROR at next call of deflate:
  17455. */
  17456. s.last_flush = -1;
  17457. return Z_OK;
  17458. }
  17459. /* Make sure there is something to do and avoid duplicate consecutive
  17460. * flushes. For repeated and useless calls with Z_FINISH, we keep
  17461. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  17462. */
  17463. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  17464. flush !== Z_FINISH) {
  17465. return err(strm, Z_BUF_ERROR);
  17466. }
  17467. /* User must not provide more input after the first FINISH: */
  17468. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  17469. return err(strm, Z_BUF_ERROR);
  17470. }
  17471. /* Start a new block or continue the current one.
  17472. */
  17473. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  17474. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  17475. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  17476. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  17477. configuration_table[s.level].func(s, flush));
  17478. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  17479. s.status = FINISH_STATE;
  17480. }
  17481. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  17482. if (strm.avail_out === 0) {
  17483. s.last_flush = -1;
  17484. /* avoid BUF_ERROR next call, see above */
  17485. }
  17486. return Z_OK;
  17487. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  17488. * of deflate should use the same flush parameter to make sure
  17489. * that the flush is complete. So we don't have to output an
  17490. * empty block here, this will be done at next call. This also
  17491. * ensures that for a very small output buffer, we emit at most
  17492. * one empty block.
  17493. */
  17494. }
  17495. if (bstate === BS_BLOCK_DONE) {
  17496. if (flush === Z_PARTIAL_FLUSH) {
  17497. trees._tr_align(s);
  17498. }
  17499. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  17500. trees._tr_stored_block(s, 0, 0, false);
  17501. /* For a full flush, this empty block will be recognized
  17502. * as a special marker by inflate_sync().
  17503. */
  17504. if (flush === Z_FULL_FLUSH) {
  17505. /*** CLEAR_HASH(s); ***/ /* forget history */
  17506. zero(s.head); // Fill with NIL (= 0);
  17507. if (s.lookahead === 0) {
  17508. s.strstart = 0;
  17509. s.block_start = 0;
  17510. s.insert = 0;
  17511. }
  17512. }
  17513. }
  17514. flush_pending(strm);
  17515. if (strm.avail_out === 0) {
  17516. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  17517. return Z_OK;
  17518. }
  17519. }
  17520. }
  17521. //Assert(strm->avail_out > 0, "bug2");
  17522. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  17523. if (flush !== Z_FINISH) { return Z_OK; }
  17524. if (s.wrap <= 0) { return Z_STREAM_END; }
  17525. /* Write the trailer */
  17526. if (s.wrap === 2) {
  17527. put_byte(s, strm.adler & 0xff);
  17528. put_byte(s, (strm.adler >> 8) & 0xff);
  17529. put_byte(s, (strm.adler >> 16) & 0xff);
  17530. put_byte(s, (strm.adler >> 24) & 0xff);
  17531. put_byte(s, strm.total_in & 0xff);
  17532. put_byte(s, (strm.total_in >> 8) & 0xff);
  17533. put_byte(s, (strm.total_in >> 16) & 0xff);
  17534. put_byte(s, (strm.total_in >> 24) & 0xff);
  17535. }
  17536. else
  17537. {
  17538. putShortMSB(s, strm.adler >>> 16);
  17539. putShortMSB(s, strm.adler & 0xffff);
  17540. }
  17541. flush_pending(strm);
  17542. /* If avail_out is zero, the application will call deflate again
  17543. * to flush the rest.
  17544. */
  17545. if (s.wrap > 0) { s.wrap = -s.wrap; }
  17546. /* write the trailer only once! */
  17547. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  17548. }
  17549. function deflateEnd(strm) {
  17550. var status;
  17551. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  17552. return Z_STREAM_ERROR;
  17553. }
  17554. status = strm.state.status;
  17555. if (status !== INIT_STATE &&
  17556. status !== EXTRA_STATE &&
  17557. status !== NAME_STATE &&
  17558. status !== COMMENT_STATE &&
  17559. status !== HCRC_STATE &&
  17560. status !== BUSY_STATE &&
  17561. status !== FINISH_STATE
  17562. ) {
  17563. return err(strm, Z_STREAM_ERROR);
  17564. }
  17565. strm.state = null;
  17566. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  17567. }
  17568. /* =========================================================================
  17569. * Initializes the compression dictionary from the given byte
  17570. * sequence without producing any compressed output.
  17571. */
  17572. function deflateSetDictionary(strm, dictionary) {
  17573. var dictLength = dictionary.length;
  17574. var s;
  17575. var str, n;
  17576. var wrap;
  17577. var avail;
  17578. var next;
  17579. var input;
  17580. var tmpDict;
  17581. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  17582. return Z_STREAM_ERROR;
  17583. }
  17584. s = strm.state;
  17585. wrap = s.wrap;
  17586. if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  17587. return Z_STREAM_ERROR;
  17588. }
  17589. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  17590. if (wrap === 1) {
  17591. /* adler32(strm->adler, dictionary, dictLength); */
  17592. strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  17593. }
  17594. s.wrap = 0; /* avoid computing Adler-32 in read_buf */
  17595. /* if dictionary would fill window, just replace the history */
  17596. if (dictLength >= s.w_size) {
  17597. if (wrap === 0) { /* already empty otherwise */
  17598. /*** CLEAR_HASH(s); ***/
  17599. zero(s.head); // Fill with NIL (= 0);
  17600. s.strstart = 0;
  17601. s.block_start = 0;
  17602. s.insert = 0;
  17603. }
  17604. /* use the tail */
  17605. // dictionary = dictionary.slice(dictLength - s.w_size);
  17606. tmpDict = new utils.Buf8(s.w_size);
  17607. utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
  17608. dictionary = tmpDict;
  17609. dictLength = s.w_size;
  17610. }
  17611. /* insert dictionary into window and hash */
  17612. avail = strm.avail_in;
  17613. next = strm.next_in;
  17614. input = strm.input;
  17615. strm.avail_in = dictLength;
  17616. strm.next_in = 0;
  17617. strm.input = dictionary;
  17618. fill_window(s);
  17619. while (s.lookahead >= MIN_MATCH) {
  17620. str = s.strstart;
  17621. n = s.lookahead - (MIN_MATCH - 1);
  17622. do {
  17623. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  17624. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  17625. s.prev[str & s.w_mask] = s.head[s.ins_h];
  17626. s.head[s.ins_h] = str;
  17627. str++;
  17628. } while (--n);
  17629. s.strstart = str;
  17630. s.lookahead = MIN_MATCH - 1;
  17631. fill_window(s);
  17632. }
  17633. s.strstart += s.lookahead;
  17634. s.block_start = s.strstart;
  17635. s.insert = s.lookahead;
  17636. s.lookahead = 0;
  17637. s.match_length = s.prev_length = MIN_MATCH - 1;
  17638. s.match_available = 0;
  17639. strm.next_in = next;
  17640. strm.input = input;
  17641. strm.avail_in = avail;
  17642. s.wrap = wrap;
  17643. return Z_OK;
  17644. }
  17645. exports.deflateInit = deflateInit;
  17646. exports.deflateInit2 = deflateInit2;
  17647. exports.deflateReset = deflateReset;
  17648. exports.deflateResetKeep = deflateResetKeep;
  17649. exports.deflateSetHeader = deflateSetHeader;
  17650. exports.deflate = deflate;
  17651. exports.deflateEnd = deflateEnd;
  17652. exports.deflateSetDictionary = deflateSetDictionary;
  17653. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  17654. /* Not implemented
  17655. exports.deflateBound = deflateBound;
  17656. exports.deflateCopy = deflateCopy;
  17657. exports.deflateParams = deflateParams;
  17658. exports.deflatePending = deflatePending;
  17659. exports.deflatePrime = deflatePrime;
  17660. exports.deflateTune = deflateTune;
  17661. */
  17662. },{"../utils/common":112,"./adler32":113,"./crc32":115,"./messages":120,"./trees":121}],117:[function(require,module,exports){
  17663. 'use strict';
  17664. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  17665. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  17666. //
  17667. // This software is provided 'as-is', without any express or implied
  17668. // warranty. In no event will the authors be held liable for any damages
  17669. // arising from the use of this software.
  17670. //
  17671. // Permission is granted to anyone to use this software for any purpose,
  17672. // including commercial applications, and to alter it and redistribute it
  17673. // freely, subject to the following restrictions:
  17674. //
  17675. // 1. The origin of this software must not be misrepresented; you must not
  17676. // claim that you wrote the original software. If you use this software
  17677. // in a product, an acknowledgment in the product documentation would be
  17678. // appreciated but is not required.
  17679. // 2. Altered source versions must be plainly marked as such, and must not be
  17680. // misrepresented as being the original software.
  17681. // 3. This notice may not be removed or altered from any source distribution.
  17682. // See state defs from inflate.js
  17683. var BAD = 30; /* got a data error -- remain here until reset */
  17684. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  17685. /*
  17686. Decode literal, length, and distance codes and write out the resulting
  17687. literal and match bytes until either not enough input or output is
  17688. available, an end-of-block is encountered, or a data error is encountered.
  17689. When large enough input and output buffers are supplied to inflate(), for
  17690. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  17691. inflate execution time is spent in this routine.
  17692. Entry assumptions:
  17693. state.mode === LEN
  17694. strm.avail_in >= 6
  17695. strm.avail_out >= 258
  17696. start >= strm.avail_out
  17697. state.bits < 8
  17698. On return, state.mode is one of:
  17699. LEN -- ran out of enough output space or enough available input
  17700. TYPE -- reached end of block code, inflate() to interpret next block
  17701. BAD -- error in block data
  17702. Notes:
  17703. - The maximum input bits used by a length/distance pair is 15 bits for the
  17704. length code, 5 bits for the length extra, 15 bits for the distance code,
  17705. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  17706. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  17707. checking for available input while decoding.
  17708. - The maximum bytes that a single length/distance pair can output is 258
  17709. bytes, which is the maximum length that can be coded. inflate_fast()
  17710. requires strm.avail_out >= 258 for each loop to avoid checking for
  17711. output space.
  17712. */
  17713. module.exports = function inflate_fast(strm, start) {
  17714. var state;
  17715. var _in; /* local strm.input */
  17716. var last; /* have enough input while in < last */
  17717. var _out; /* local strm.output */
  17718. var beg; /* inflate()'s initial strm.output */
  17719. var end; /* while out < end, enough space available */
  17720. //#ifdef INFLATE_STRICT
  17721. var dmax; /* maximum distance from zlib header */
  17722. //#endif
  17723. var wsize; /* window size or zero if not using window */
  17724. var whave; /* valid bytes in the window */
  17725. var wnext; /* window write index */
  17726. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  17727. var s_window; /* allocated sliding window, if wsize != 0 */
  17728. var hold; /* local strm.hold */
  17729. var bits; /* local strm.bits */
  17730. var lcode; /* local strm.lencode */
  17731. var dcode; /* local strm.distcode */
  17732. var lmask; /* mask for first level of length codes */
  17733. var dmask; /* mask for first level of distance codes */
  17734. var here; /* retrieved table entry */
  17735. var op; /* code bits, operation, extra bits, or */
  17736. /* window position, window bytes to copy */
  17737. var len; /* match length, unused bytes */
  17738. var dist; /* match distance */
  17739. var from; /* where to copy match from */
  17740. var from_source;
  17741. var input, output; // JS specific, because we have no pointers
  17742. /* copy state to local variables */
  17743. state = strm.state;
  17744. //here = state.here;
  17745. _in = strm.next_in;
  17746. input = strm.input;
  17747. last = _in + (strm.avail_in - 5);
  17748. _out = strm.next_out;
  17749. output = strm.output;
  17750. beg = _out - (start - strm.avail_out);
  17751. end = _out + (strm.avail_out - 257);
  17752. //#ifdef INFLATE_STRICT
  17753. dmax = state.dmax;
  17754. //#endif
  17755. wsize = state.wsize;
  17756. whave = state.whave;
  17757. wnext = state.wnext;
  17758. s_window = state.window;
  17759. hold = state.hold;
  17760. bits = state.bits;
  17761. lcode = state.lencode;
  17762. dcode = state.distcode;
  17763. lmask = (1 << state.lenbits) - 1;
  17764. dmask = (1 << state.distbits) - 1;
  17765. /* decode literals and length/distances until end-of-block or not enough
  17766. input data or output space */
  17767. top:
  17768. do {
  17769. if (bits < 15) {
  17770. hold += input[_in++] << bits;
  17771. bits += 8;
  17772. hold += input[_in++] << bits;
  17773. bits += 8;
  17774. }
  17775. here = lcode[hold & lmask];
  17776. dolen:
  17777. for (;;) { // Goto emulation
  17778. op = here >>> 24/*here.bits*/;
  17779. hold >>>= op;
  17780. bits -= op;
  17781. op = (here >>> 16) & 0xff/*here.op*/;
  17782. if (op === 0) { /* literal */
  17783. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  17784. // "inflate: literal '%c'\n" :
  17785. // "inflate: literal 0x%02x\n", here.val));
  17786. output[_out++] = here & 0xffff/*here.val*/;
  17787. }
  17788. else if (op & 16) { /* length base */
  17789. len = here & 0xffff/*here.val*/;
  17790. op &= 15; /* number of extra bits */
  17791. if (op) {
  17792. if (bits < op) {
  17793. hold += input[_in++] << bits;
  17794. bits += 8;
  17795. }
  17796. len += hold & ((1 << op) - 1);
  17797. hold >>>= op;
  17798. bits -= op;
  17799. }
  17800. //Tracevv((stderr, "inflate: length %u\n", len));
  17801. if (bits < 15) {
  17802. hold += input[_in++] << bits;
  17803. bits += 8;
  17804. hold += input[_in++] << bits;
  17805. bits += 8;
  17806. }
  17807. here = dcode[hold & dmask];
  17808. dodist:
  17809. for (;;) { // goto emulation
  17810. op = here >>> 24/*here.bits*/;
  17811. hold >>>= op;
  17812. bits -= op;
  17813. op = (here >>> 16) & 0xff/*here.op*/;
  17814. if (op & 16) { /* distance base */
  17815. dist = here & 0xffff/*here.val*/;
  17816. op &= 15; /* number of extra bits */
  17817. if (bits < op) {
  17818. hold += input[_in++] << bits;
  17819. bits += 8;
  17820. if (bits < op) {
  17821. hold += input[_in++] << bits;
  17822. bits += 8;
  17823. }
  17824. }
  17825. dist += hold & ((1 << op) - 1);
  17826. //#ifdef INFLATE_STRICT
  17827. if (dist > dmax) {
  17828. strm.msg = 'invalid distance too far back';
  17829. state.mode = BAD;
  17830. break top;
  17831. }
  17832. //#endif
  17833. hold >>>= op;
  17834. bits -= op;
  17835. //Tracevv((stderr, "inflate: distance %u\n", dist));
  17836. op = _out - beg; /* max distance in output */
  17837. if (dist > op) { /* see if copy from window */
  17838. op = dist - op; /* distance back in window */
  17839. if (op > whave) {
  17840. if (state.sane) {
  17841. strm.msg = 'invalid distance too far back';
  17842. state.mode = BAD;
  17843. break top;
  17844. }
  17845. // (!) This block is disabled in zlib defaults,
  17846. // don't enable it for binary compatibility
  17847. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  17848. // if (len <= op - whave) {
  17849. // do {
  17850. // output[_out++] = 0;
  17851. // } while (--len);
  17852. // continue top;
  17853. // }
  17854. // len -= op - whave;
  17855. // do {
  17856. // output[_out++] = 0;
  17857. // } while (--op > whave);
  17858. // if (op === 0) {
  17859. // from = _out - dist;
  17860. // do {
  17861. // output[_out++] = output[from++];
  17862. // } while (--len);
  17863. // continue top;
  17864. // }
  17865. //#endif
  17866. }
  17867. from = 0; // window index
  17868. from_source = s_window;
  17869. if (wnext === 0) { /* very common case */
  17870. from += wsize - op;
  17871. if (op < len) { /* some from window */
  17872. len -= op;
  17873. do {
  17874. output[_out++] = s_window[from++];
  17875. } while (--op);
  17876. from = _out - dist; /* rest from output */
  17877. from_source = output;
  17878. }
  17879. }
  17880. else if (wnext < op) { /* wrap around window */
  17881. from += wsize + wnext - op;
  17882. op -= wnext;
  17883. if (op < len) { /* some from end of window */
  17884. len -= op;
  17885. do {
  17886. output[_out++] = s_window[from++];
  17887. } while (--op);
  17888. from = 0;
  17889. if (wnext < len) { /* some from start of window */
  17890. op = wnext;
  17891. len -= op;
  17892. do {
  17893. output[_out++] = s_window[from++];
  17894. } while (--op);
  17895. from = _out - dist; /* rest from output */
  17896. from_source = output;
  17897. }
  17898. }
  17899. }
  17900. else { /* contiguous in window */
  17901. from += wnext - op;
  17902. if (op < len) { /* some from window */
  17903. len -= op;
  17904. do {
  17905. output[_out++] = s_window[from++];
  17906. } while (--op);
  17907. from = _out - dist; /* rest from output */
  17908. from_source = output;
  17909. }
  17910. }
  17911. while (len > 2) {
  17912. output[_out++] = from_source[from++];
  17913. output[_out++] = from_source[from++];
  17914. output[_out++] = from_source[from++];
  17915. len -= 3;
  17916. }
  17917. if (len) {
  17918. output[_out++] = from_source[from++];
  17919. if (len > 1) {
  17920. output[_out++] = from_source[from++];
  17921. }
  17922. }
  17923. }
  17924. else {
  17925. from = _out - dist; /* copy direct from output */
  17926. do { /* minimum length is three */
  17927. output[_out++] = output[from++];
  17928. output[_out++] = output[from++];
  17929. output[_out++] = output[from++];
  17930. len -= 3;
  17931. } while (len > 2);
  17932. if (len) {
  17933. output[_out++] = output[from++];
  17934. if (len > 1) {
  17935. output[_out++] = output[from++];
  17936. }
  17937. }
  17938. }
  17939. }
  17940. else if ((op & 64) === 0) { /* 2nd level distance code */
  17941. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  17942. continue dodist;
  17943. }
  17944. else {
  17945. strm.msg = 'invalid distance code';
  17946. state.mode = BAD;
  17947. break top;
  17948. }
  17949. break; // need to emulate goto via "continue"
  17950. }
  17951. }
  17952. else if ((op & 64) === 0) { /* 2nd level length code */
  17953. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  17954. continue dolen;
  17955. }
  17956. else if (op & 32) { /* end-of-block */
  17957. //Tracevv((stderr, "inflate: end of block\n"));
  17958. state.mode = TYPE;
  17959. break top;
  17960. }
  17961. else {
  17962. strm.msg = 'invalid literal/length code';
  17963. state.mode = BAD;
  17964. break top;
  17965. }
  17966. break; // need to emulate goto via "continue"
  17967. }
  17968. } while (_in < last && _out < end);
  17969. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  17970. len = bits >> 3;
  17971. _in -= len;
  17972. bits -= len << 3;
  17973. hold &= (1 << bits) - 1;
  17974. /* update state and return */
  17975. strm.next_in = _in;
  17976. strm.next_out = _out;
  17977. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  17978. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  17979. state.hold = hold;
  17980. state.bits = bits;
  17981. return;
  17982. };
  17983. },{}],118:[function(require,module,exports){
  17984. 'use strict';
  17985. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  17986. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  17987. //
  17988. // This software is provided 'as-is', without any express or implied
  17989. // warranty. In no event will the authors be held liable for any damages
  17990. // arising from the use of this software.
  17991. //
  17992. // Permission is granted to anyone to use this software for any purpose,
  17993. // including commercial applications, and to alter it and redistribute it
  17994. // freely, subject to the following restrictions:
  17995. //
  17996. // 1. The origin of this software must not be misrepresented; you must not
  17997. // claim that you wrote the original software. If you use this software
  17998. // in a product, an acknowledgment in the product documentation would be
  17999. // appreciated but is not required.
  18000. // 2. Altered source versions must be plainly marked as such, and must not be
  18001. // misrepresented as being the original software.
  18002. // 3. This notice may not be removed or altered from any source distribution.
  18003. var utils = require('../utils/common');
  18004. var adler32 = require('./adler32');
  18005. var crc32 = require('./crc32');
  18006. var inflate_fast = require('./inffast');
  18007. var inflate_table = require('./inftrees');
  18008. var CODES = 0;
  18009. var LENS = 1;
  18010. var DISTS = 2;
  18011. /* Public constants ==========================================================*/
  18012. /* ===========================================================================*/
  18013. /* Allowed flush values; see deflate() and inflate() below for details */
  18014. //var Z_NO_FLUSH = 0;
  18015. //var Z_PARTIAL_FLUSH = 1;
  18016. //var Z_SYNC_FLUSH = 2;
  18017. //var Z_FULL_FLUSH = 3;
  18018. var Z_FINISH = 4;
  18019. var Z_BLOCK = 5;
  18020. var Z_TREES = 6;
  18021. /* Return codes for the compression/decompression functions. Negative values
  18022. * are errors, positive values are used for special but normal events.
  18023. */
  18024. var Z_OK = 0;
  18025. var Z_STREAM_END = 1;
  18026. var Z_NEED_DICT = 2;
  18027. //var Z_ERRNO = -1;
  18028. var Z_STREAM_ERROR = -2;
  18029. var Z_DATA_ERROR = -3;
  18030. var Z_MEM_ERROR = -4;
  18031. var Z_BUF_ERROR = -5;
  18032. //var Z_VERSION_ERROR = -6;
  18033. /* The deflate compression method */
  18034. var Z_DEFLATED = 8;
  18035. /* STATES ====================================================================*/
  18036. /* ===========================================================================*/
  18037. var HEAD = 1; /* i: waiting for magic header */
  18038. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  18039. var TIME = 3; /* i: waiting for modification time (gzip) */
  18040. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  18041. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  18042. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  18043. var NAME = 7; /* i: waiting for end of file name (gzip) */
  18044. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  18045. var HCRC = 9; /* i: waiting for header crc (gzip) */
  18046. var DICTID = 10; /* i: waiting for dictionary check value */
  18047. var DICT = 11; /* waiting for inflateSetDictionary() call */
  18048. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  18049. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  18050. var STORED = 14; /* i: waiting for stored size (length and complement) */
  18051. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  18052. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  18053. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  18054. var LENLENS = 18; /* i: waiting for code length code lengths */
  18055. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  18056. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  18057. var LEN = 21; /* i: waiting for length/lit/eob code */
  18058. var LENEXT = 22; /* i: waiting for length extra bits */
  18059. var DIST = 23; /* i: waiting for distance code */
  18060. var DISTEXT = 24; /* i: waiting for distance extra bits */
  18061. var MATCH = 25; /* o: waiting for output space to copy string */
  18062. var LIT = 26; /* o: waiting for output space to write literal */
  18063. var CHECK = 27; /* i: waiting for 32-bit check value */
  18064. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  18065. var DONE = 29; /* finished check, done -- remain here until reset */
  18066. var BAD = 30; /* got a data error -- remain here until reset */
  18067. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  18068. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  18069. /* ===========================================================================*/
  18070. var ENOUGH_LENS = 852;
  18071. var ENOUGH_DISTS = 592;
  18072. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  18073. var MAX_WBITS = 15;
  18074. /* 32K LZ77 window */
  18075. var DEF_WBITS = MAX_WBITS;
  18076. function zswap32(q) {
  18077. return (((q >>> 24) & 0xff) +
  18078. ((q >>> 8) & 0xff00) +
  18079. ((q & 0xff00) << 8) +
  18080. ((q & 0xff) << 24));
  18081. }
  18082. function InflateState() {
  18083. this.mode = 0; /* current inflate mode */
  18084. this.last = false; /* true if processing last block */
  18085. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  18086. this.havedict = false; /* true if dictionary provided */
  18087. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  18088. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  18089. this.check = 0; /* protected copy of check value */
  18090. this.total = 0; /* protected copy of output count */
  18091. // TODO: may be {}
  18092. this.head = null; /* where to save gzip header information */
  18093. /* sliding window */
  18094. this.wbits = 0; /* log base 2 of requested window size */
  18095. this.wsize = 0; /* window size or zero if not using window */
  18096. this.whave = 0; /* valid bytes in the window */
  18097. this.wnext = 0; /* window write index */
  18098. this.window = null; /* allocated sliding window, if needed */
  18099. /* bit accumulator */
  18100. this.hold = 0; /* input bit accumulator */
  18101. this.bits = 0; /* number of bits in "in" */
  18102. /* for string and stored block copying */
  18103. this.length = 0; /* literal or length of data to copy */
  18104. this.offset = 0; /* distance back to copy string from */
  18105. /* for table and code decoding */
  18106. this.extra = 0; /* extra bits needed */
  18107. /* fixed and dynamic code tables */
  18108. this.lencode = null; /* starting table for length/literal codes */
  18109. this.distcode = null; /* starting table for distance codes */
  18110. this.lenbits = 0; /* index bits for lencode */
  18111. this.distbits = 0; /* index bits for distcode */
  18112. /* dynamic table building */
  18113. this.ncode = 0; /* number of code length code lengths */
  18114. this.nlen = 0; /* number of length code lengths */
  18115. this.ndist = 0; /* number of distance code lengths */
  18116. this.have = 0; /* number of code lengths in lens[] */
  18117. this.next = null; /* next available space in codes[] */
  18118. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  18119. this.work = new utils.Buf16(288); /* work area for code table building */
  18120. /*
  18121. because we don't have pointers in js, we use lencode and distcode directly
  18122. as buffers so we don't need codes
  18123. */
  18124. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  18125. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  18126. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  18127. this.sane = 0; /* if false, allow invalid distance too far */
  18128. this.back = 0; /* bits back of last unprocessed length/lit */
  18129. this.was = 0; /* initial length of match */
  18130. }
  18131. function inflateResetKeep(strm) {
  18132. var state;
  18133. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18134. state = strm.state;
  18135. strm.total_in = strm.total_out = state.total = 0;
  18136. strm.msg = ''; /*Z_NULL*/
  18137. if (state.wrap) { /* to support ill-conceived Java test suite */
  18138. strm.adler = state.wrap & 1;
  18139. }
  18140. state.mode = HEAD;
  18141. state.last = 0;
  18142. state.havedict = 0;
  18143. state.dmax = 32768;
  18144. state.head = null/*Z_NULL*/;
  18145. state.hold = 0;
  18146. state.bits = 0;
  18147. //state.lencode = state.distcode = state.next = state.codes;
  18148. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  18149. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  18150. state.sane = 1;
  18151. state.back = -1;
  18152. //Tracev((stderr, "inflate: reset\n"));
  18153. return Z_OK;
  18154. }
  18155. function inflateReset(strm) {
  18156. var state;
  18157. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18158. state = strm.state;
  18159. state.wsize = 0;
  18160. state.whave = 0;
  18161. state.wnext = 0;
  18162. return inflateResetKeep(strm);
  18163. }
  18164. function inflateReset2(strm, windowBits) {
  18165. var wrap;
  18166. var state;
  18167. /* get the state */
  18168. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18169. state = strm.state;
  18170. /* extract wrap request from windowBits parameter */
  18171. if (windowBits < 0) {
  18172. wrap = 0;
  18173. windowBits = -windowBits;
  18174. }
  18175. else {
  18176. wrap = (windowBits >> 4) + 1;
  18177. if (windowBits < 48) {
  18178. windowBits &= 15;
  18179. }
  18180. }
  18181. /* set number of window bits, free window if different */
  18182. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  18183. return Z_STREAM_ERROR;
  18184. }
  18185. if (state.window !== null && state.wbits !== windowBits) {
  18186. state.window = null;
  18187. }
  18188. /* update state and reset the rest of it */
  18189. state.wrap = wrap;
  18190. state.wbits = windowBits;
  18191. return inflateReset(strm);
  18192. }
  18193. function inflateInit2(strm, windowBits) {
  18194. var ret;
  18195. var state;
  18196. if (!strm) { return Z_STREAM_ERROR; }
  18197. //strm.msg = Z_NULL; /* in case we return an error */
  18198. state = new InflateState();
  18199. //if (state === Z_NULL) return Z_MEM_ERROR;
  18200. //Tracev((stderr, "inflate: allocated\n"));
  18201. strm.state = state;
  18202. state.window = null/*Z_NULL*/;
  18203. ret = inflateReset2(strm, windowBits);
  18204. if (ret !== Z_OK) {
  18205. strm.state = null/*Z_NULL*/;
  18206. }
  18207. return ret;
  18208. }
  18209. function inflateInit(strm) {
  18210. return inflateInit2(strm, DEF_WBITS);
  18211. }
  18212. /*
  18213. Return state with length and distance decoding tables and index sizes set to
  18214. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  18215. If BUILDFIXED is defined, then instead this routine builds the tables the
  18216. first time it's called, and returns those tables the first time and
  18217. thereafter. This reduces the size of the code by about 2K bytes, in
  18218. exchange for a little execution time. However, BUILDFIXED should not be
  18219. used for threaded applications, since the rewriting of the tables and virgin
  18220. may not be thread-safe.
  18221. */
  18222. var virgin = true;
  18223. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  18224. function fixedtables(state) {
  18225. /* build fixed huffman tables if first call (may not be thread safe) */
  18226. if (virgin) {
  18227. var sym;
  18228. lenfix = new utils.Buf32(512);
  18229. distfix = new utils.Buf32(32);
  18230. /* literal/length table */
  18231. sym = 0;
  18232. while (sym < 144) { state.lens[sym++] = 8; }
  18233. while (sym < 256) { state.lens[sym++] = 9; }
  18234. while (sym < 280) { state.lens[sym++] = 7; }
  18235. while (sym < 288) { state.lens[sym++] = 8; }
  18236. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
  18237. /* distance table */
  18238. sym = 0;
  18239. while (sym < 32) { state.lens[sym++] = 5; }
  18240. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
  18241. /* do this just once */
  18242. virgin = false;
  18243. }
  18244. state.lencode = lenfix;
  18245. state.lenbits = 9;
  18246. state.distcode = distfix;
  18247. state.distbits = 5;
  18248. }
  18249. /*
  18250. Update the window with the last wsize (normally 32K) bytes written before
  18251. returning. If window does not exist yet, create it. This is only called
  18252. when a window is already in use, or when output has been written during this
  18253. inflate call, but the end of the deflate stream has not been reached yet.
  18254. It is also called to create a window for dictionary data when a dictionary
  18255. is loaded.
  18256. Providing output buffers larger than 32K to inflate() should provide a speed
  18257. advantage, since only the last 32K of output is copied to the sliding window
  18258. upon return from inflate(), and since all distances after the first 32K of
  18259. output will fall in the output data, making match copies simpler and faster.
  18260. The advantage may be dependent on the size of the processor's data caches.
  18261. */
  18262. function updatewindow(strm, src, end, copy) {
  18263. var dist;
  18264. var state = strm.state;
  18265. /* if it hasn't been done already, allocate space for the window */
  18266. if (state.window === null) {
  18267. state.wsize = 1 << state.wbits;
  18268. state.wnext = 0;
  18269. state.whave = 0;
  18270. state.window = new utils.Buf8(state.wsize);
  18271. }
  18272. /* copy state->wsize or less output bytes into the circular window */
  18273. if (copy >= state.wsize) {
  18274. utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
  18275. state.wnext = 0;
  18276. state.whave = state.wsize;
  18277. }
  18278. else {
  18279. dist = state.wsize - state.wnext;
  18280. if (dist > copy) {
  18281. dist = copy;
  18282. }
  18283. //zmemcpy(state->window + state->wnext, end - copy, dist);
  18284. utils.arraySet(state.window, src, end - copy, dist, state.wnext);
  18285. copy -= dist;
  18286. if (copy) {
  18287. //zmemcpy(state->window, end - copy, copy);
  18288. utils.arraySet(state.window, src, end - copy, copy, 0);
  18289. state.wnext = copy;
  18290. state.whave = state.wsize;
  18291. }
  18292. else {
  18293. state.wnext += dist;
  18294. if (state.wnext === state.wsize) { state.wnext = 0; }
  18295. if (state.whave < state.wsize) { state.whave += dist; }
  18296. }
  18297. }
  18298. return 0;
  18299. }
  18300. function inflate(strm, flush) {
  18301. var state;
  18302. var input, output; // input/output buffers
  18303. var next; /* next input INDEX */
  18304. var put; /* next output INDEX */
  18305. var have, left; /* available input and output */
  18306. var hold; /* bit buffer */
  18307. var bits; /* bits in bit buffer */
  18308. var _in, _out; /* save starting available input and output */
  18309. var copy; /* number of stored or match bytes to copy */
  18310. var from; /* where to copy match bytes from */
  18311. var from_source;
  18312. var here = 0; /* current decoding table entry */
  18313. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  18314. //var last; /* parent table entry */
  18315. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  18316. var len; /* length to copy for repeats, bits to drop */
  18317. var ret; /* return code */
  18318. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  18319. var opts;
  18320. var n; // temporary var for NEED_BITS
  18321. var order = /* permutation of code lengths */
  18322. [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  18323. if (!strm || !strm.state || !strm.output ||
  18324. (!strm.input && strm.avail_in !== 0)) {
  18325. return Z_STREAM_ERROR;
  18326. }
  18327. state = strm.state;
  18328. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  18329. //--- LOAD() ---
  18330. put = strm.next_out;
  18331. output = strm.output;
  18332. left = strm.avail_out;
  18333. next = strm.next_in;
  18334. input = strm.input;
  18335. have = strm.avail_in;
  18336. hold = state.hold;
  18337. bits = state.bits;
  18338. //---
  18339. _in = have;
  18340. _out = left;
  18341. ret = Z_OK;
  18342. inf_leave: // goto emulation
  18343. for (;;) {
  18344. switch (state.mode) {
  18345. case HEAD:
  18346. if (state.wrap === 0) {
  18347. state.mode = TYPEDO;
  18348. break;
  18349. }
  18350. //=== NEEDBITS(16);
  18351. while (bits < 16) {
  18352. if (have === 0) { break inf_leave; }
  18353. have--;
  18354. hold += input[next++] << bits;
  18355. bits += 8;
  18356. }
  18357. //===//
  18358. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  18359. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  18360. //=== CRC2(state.check, hold);
  18361. hbuf[0] = hold & 0xff;
  18362. hbuf[1] = (hold >>> 8) & 0xff;
  18363. state.check = crc32(state.check, hbuf, 2, 0);
  18364. //===//
  18365. //=== INITBITS();
  18366. hold = 0;
  18367. bits = 0;
  18368. //===//
  18369. state.mode = FLAGS;
  18370. break;
  18371. }
  18372. state.flags = 0; /* expect zlib header */
  18373. if (state.head) {
  18374. state.head.done = false;
  18375. }
  18376. if (!(state.wrap & 1) || /* check if zlib header allowed */
  18377. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  18378. strm.msg = 'incorrect header check';
  18379. state.mode = BAD;
  18380. break;
  18381. }
  18382. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  18383. strm.msg = 'unknown compression method';
  18384. state.mode = BAD;
  18385. break;
  18386. }
  18387. //--- DROPBITS(4) ---//
  18388. hold >>>= 4;
  18389. bits -= 4;
  18390. //---//
  18391. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  18392. if (state.wbits === 0) {
  18393. state.wbits = len;
  18394. }
  18395. else if (len > state.wbits) {
  18396. strm.msg = 'invalid window size';
  18397. state.mode = BAD;
  18398. break;
  18399. }
  18400. state.dmax = 1 << len;
  18401. //Tracev((stderr, "inflate: zlib header ok\n"));
  18402. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  18403. state.mode = hold & 0x200 ? DICTID : TYPE;
  18404. //=== INITBITS();
  18405. hold = 0;
  18406. bits = 0;
  18407. //===//
  18408. break;
  18409. case FLAGS:
  18410. //=== NEEDBITS(16); */
  18411. while (bits < 16) {
  18412. if (have === 0) { break inf_leave; }
  18413. have--;
  18414. hold += input[next++] << bits;
  18415. bits += 8;
  18416. }
  18417. //===//
  18418. state.flags = hold;
  18419. if ((state.flags & 0xff) !== Z_DEFLATED) {
  18420. strm.msg = 'unknown compression method';
  18421. state.mode = BAD;
  18422. break;
  18423. }
  18424. if (state.flags & 0xe000) {
  18425. strm.msg = 'unknown header flags set';
  18426. state.mode = BAD;
  18427. break;
  18428. }
  18429. if (state.head) {
  18430. state.head.text = ((hold >> 8) & 1);
  18431. }
  18432. if (state.flags & 0x0200) {
  18433. //=== CRC2(state.check, hold);
  18434. hbuf[0] = hold & 0xff;
  18435. hbuf[1] = (hold >>> 8) & 0xff;
  18436. state.check = crc32(state.check, hbuf, 2, 0);
  18437. //===//
  18438. }
  18439. //=== INITBITS();
  18440. hold = 0;
  18441. bits = 0;
  18442. //===//
  18443. state.mode = TIME;
  18444. /* falls through */
  18445. case TIME:
  18446. //=== NEEDBITS(32); */
  18447. while (bits < 32) {
  18448. if (have === 0) { break inf_leave; }
  18449. have--;
  18450. hold += input[next++] << bits;
  18451. bits += 8;
  18452. }
  18453. //===//
  18454. if (state.head) {
  18455. state.head.time = hold;
  18456. }
  18457. if (state.flags & 0x0200) {
  18458. //=== CRC4(state.check, hold)
  18459. hbuf[0] = hold & 0xff;
  18460. hbuf[1] = (hold >>> 8) & 0xff;
  18461. hbuf[2] = (hold >>> 16) & 0xff;
  18462. hbuf[3] = (hold >>> 24) & 0xff;
  18463. state.check = crc32(state.check, hbuf, 4, 0);
  18464. //===
  18465. }
  18466. //=== INITBITS();
  18467. hold = 0;
  18468. bits = 0;
  18469. //===//
  18470. state.mode = OS;
  18471. /* falls through */
  18472. case OS:
  18473. //=== NEEDBITS(16); */
  18474. while (bits < 16) {
  18475. if (have === 0) { break inf_leave; }
  18476. have--;
  18477. hold += input[next++] << bits;
  18478. bits += 8;
  18479. }
  18480. //===//
  18481. if (state.head) {
  18482. state.head.xflags = (hold & 0xff);
  18483. state.head.os = (hold >> 8);
  18484. }
  18485. if (state.flags & 0x0200) {
  18486. //=== CRC2(state.check, hold);
  18487. hbuf[0] = hold & 0xff;
  18488. hbuf[1] = (hold >>> 8) & 0xff;
  18489. state.check = crc32(state.check, hbuf, 2, 0);
  18490. //===//
  18491. }
  18492. //=== INITBITS();
  18493. hold = 0;
  18494. bits = 0;
  18495. //===//
  18496. state.mode = EXLEN;
  18497. /* falls through */
  18498. case EXLEN:
  18499. if (state.flags & 0x0400) {
  18500. //=== NEEDBITS(16); */
  18501. while (bits < 16) {
  18502. if (have === 0) { break inf_leave; }
  18503. have--;
  18504. hold += input[next++] << bits;
  18505. bits += 8;
  18506. }
  18507. //===//
  18508. state.length = hold;
  18509. if (state.head) {
  18510. state.head.extra_len = hold;
  18511. }
  18512. if (state.flags & 0x0200) {
  18513. //=== CRC2(state.check, hold);
  18514. hbuf[0] = hold & 0xff;
  18515. hbuf[1] = (hold >>> 8) & 0xff;
  18516. state.check = crc32(state.check, hbuf, 2, 0);
  18517. //===//
  18518. }
  18519. //=== INITBITS();
  18520. hold = 0;
  18521. bits = 0;
  18522. //===//
  18523. }
  18524. else if (state.head) {
  18525. state.head.extra = null/*Z_NULL*/;
  18526. }
  18527. state.mode = EXTRA;
  18528. /* falls through */
  18529. case EXTRA:
  18530. if (state.flags & 0x0400) {
  18531. copy = state.length;
  18532. if (copy > have) { copy = have; }
  18533. if (copy) {
  18534. if (state.head) {
  18535. len = state.head.extra_len - state.length;
  18536. if (!state.head.extra) {
  18537. // Use untyped array for more convenient processing later
  18538. state.head.extra = new Array(state.head.extra_len);
  18539. }
  18540. utils.arraySet(
  18541. state.head.extra,
  18542. input,
  18543. next,
  18544. // extra field is limited to 65536 bytes
  18545. // - no need for additional size check
  18546. copy,
  18547. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  18548. len
  18549. );
  18550. //zmemcpy(state.head.extra + len, next,
  18551. // len + copy > state.head.extra_max ?
  18552. // state.head.extra_max - len : copy);
  18553. }
  18554. if (state.flags & 0x0200) {
  18555. state.check = crc32(state.check, input, copy, next);
  18556. }
  18557. have -= copy;
  18558. next += copy;
  18559. state.length -= copy;
  18560. }
  18561. if (state.length) { break inf_leave; }
  18562. }
  18563. state.length = 0;
  18564. state.mode = NAME;
  18565. /* falls through */
  18566. case NAME:
  18567. if (state.flags & 0x0800) {
  18568. if (have === 0) { break inf_leave; }
  18569. copy = 0;
  18570. do {
  18571. // TODO: 2 or 1 bytes?
  18572. len = input[next + copy++];
  18573. /* use constant limit because in js we should not preallocate memory */
  18574. if (state.head && len &&
  18575. (state.length < 65536 /*state.head.name_max*/)) {
  18576. state.head.name += String.fromCharCode(len);
  18577. }
  18578. } while (len && copy < have);
  18579. if (state.flags & 0x0200) {
  18580. state.check = crc32(state.check, input, copy, next);
  18581. }
  18582. have -= copy;
  18583. next += copy;
  18584. if (len) { break inf_leave; }
  18585. }
  18586. else if (state.head) {
  18587. state.head.name = null;
  18588. }
  18589. state.length = 0;
  18590. state.mode = COMMENT;
  18591. /* falls through */
  18592. case COMMENT:
  18593. if (state.flags & 0x1000) {
  18594. if (have === 0) { break inf_leave; }
  18595. copy = 0;
  18596. do {
  18597. len = input[next + copy++];
  18598. /* use constant limit because in js we should not preallocate memory */
  18599. if (state.head && len &&
  18600. (state.length < 65536 /*state.head.comm_max*/)) {
  18601. state.head.comment += String.fromCharCode(len);
  18602. }
  18603. } while (len && copy < have);
  18604. if (state.flags & 0x0200) {
  18605. state.check = crc32(state.check, input, copy, next);
  18606. }
  18607. have -= copy;
  18608. next += copy;
  18609. if (len) { break inf_leave; }
  18610. }
  18611. else if (state.head) {
  18612. state.head.comment = null;
  18613. }
  18614. state.mode = HCRC;
  18615. /* falls through */
  18616. case HCRC:
  18617. if (state.flags & 0x0200) {
  18618. //=== NEEDBITS(16); */
  18619. while (bits < 16) {
  18620. if (have === 0) { break inf_leave; }
  18621. have--;
  18622. hold += input[next++] << bits;
  18623. bits += 8;
  18624. }
  18625. //===//
  18626. if (hold !== (state.check & 0xffff)) {
  18627. strm.msg = 'header crc mismatch';
  18628. state.mode = BAD;
  18629. break;
  18630. }
  18631. //=== INITBITS();
  18632. hold = 0;
  18633. bits = 0;
  18634. //===//
  18635. }
  18636. if (state.head) {
  18637. state.head.hcrc = ((state.flags >> 9) & 1);
  18638. state.head.done = true;
  18639. }
  18640. strm.adler = state.check = 0;
  18641. state.mode = TYPE;
  18642. break;
  18643. case DICTID:
  18644. //=== NEEDBITS(32); */
  18645. while (bits < 32) {
  18646. if (have === 0) { break inf_leave; }
  18647. have--;
  18648. hold += input[next++] << bits;
  18649. bits += 8;
  18650. }
  18651. //===//
  18652. strm.adler = state.check = zswap32(hold);
  18653. //=== INITBITS();
  18654. hold = 0;
  18655. bits = 0;
  18656. //===//
  18657. state.mode = DICT;
  18658. /* falls through */
  18659. case DICT:
  18660. if (state.havedict === 0) {
  18661. //--- RESTORE() ---
  18662. strm.next_out = put;
  18663. strm.avail_out = left;
  18664. strm.next_in = next;
  18665. strm.avail_in = have;
  18666. state.hold = hold;
  18667. state.bits = bits;
  18668. //---
  18669. return Z_NEED_DICT;
  18670. }
  18671. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  18672. state.mode = TYPE;
  18673. /* falls through */
  18674. case TYPE:
  18675. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  18676. /* falls through */
  18677. case TYPEDO:
  18678. if (state.last) {
  18679. //--- BYTEBITS() ---//
  18680. hold >>>= bits & 7;
  18681. bits -= bits & 7;
  18682. //---//
  18683. state.mode = CHECK;
  18684. break;
  18685. }
  18686. //=== NEEDBITS(3); */
  18687. while (bits < 3) {
  18688. if (have === 0) { break inf_leave; }
  18689. have--;
  18690. hold += input[next++] << bits;
  18691. bits += 8;
  18692. }
  18693. //===//
  18694. state.last = (hold & 0x01)/*BITS(1)*/;
  18695. //--- DROPBITS(1) ---//
  18696. hold >>>= 1;
  18697. bits -= 1;
  18698. //---//
  18699. switch ((hold & 0x03)/*BITS(2)*/) {
  18700. case 0: /* stored block */
  18701. //Tracev((stderr, "inflate: stored block%s\n",
  18702. // state.last ? " (last)" : ""));
  18703. state.mode = STORED;
  18704. break;
  18705. case 1: /* fixed block */
  18706. fixedtables(state);
  18707. //Tracev((stderr, "inflate: fixed codes block%s\n",
  18708. // state.last ? " (last)" : ""));
  18709. state.mode = LEN_; /* decode codes */
  18710. if (flush === Z_TREES) {
  18711. //--- DROPBITS(2) ---//
  18712. hold >>>= 2;
  18713. bits -= 2;
  18714. //---//
  18715. break inf_leave;
  18716. }
  18717. break;
  18718. case 2: /* dynamic block */
  18719. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  18720. // state.last ? " (last)" : ""));
  18721. state.mode = TABLE;
  18722. break;
  18723. case 3:
  18724. strm.msg = 'invalid block type';
  18725. state.mode = BAD;
  18726. }
  18727. //--- DROPBITS(2) ---//
  18728. hold >>>= 2;
  18729. bits -= 2;
  18730. //---//
  18731. break;
  18732. case STORED:
  18733. //--- BYTEBITS() ---// /* go to byte boundary */
  18734. hold >>>= bits & 7;
  18735. bits -= bits & 7;
  18736. //---//
  18737. //=== NEEDBITS(32); */
  18738. while (bits < 32) {
  18739. if (have === 0) { break inf_leave; }
  18740. have--;
  18741. hold += input[next++] << bits;
  18742. bits += 8;
  18743. }
  18744. //===//
  18745. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  18746. strm.msg = 'invalid stored block lengths';
  18747. state.mode = BAD;
  18748. break;
  18749. }
  18750. state.length = hold & 0xffff;
  18751. //Tracev((stderr, "inflate: stored length %u\n",
  18752. // state.length));
  18753. //=== INITBITS();
  18754. hold = 0;
  18755. bits = 0;
  18756. //===//
  18757. state.mode = COPY_;
  18758. if (flush === Z_TREES) { break inf_leave; }
  18759. /* falls through */
  18760. case COPY_:
  18761. state.mode = COPY;
  18762. /* falls through */
  18763. case COPY:
  18764. copy = state.length;
  18765. if (copy) {
  18766. if (copy > have) { copy = have; }
  18767. if (copy > left) { copy = left; }
  18768. if (copy === 0) { break inf_leave; }
  18769. //--- zmemcpy(put, next, copy); ---
  18770. utils.arraySet(output, input, next, copy, put);
  18771. //---//
  18772. have -= copy;
  18773. next += copy;
  18774. left -= copy;
  18775. put += copy;
  18776. state.length -= copy;
  18777. break;
  18778. }
  18779. //Tracev((stderr, "inflate: stored end\n"));
  18780. state.mode = TYPE;
  18781. break;
  18782. case TABLE:
  18783. //=== NEEDBITS(14); */
  18784. while (bits < 14) {
  18785. if (have === 0) { break inf_leave; }
  18786. have--;
  18787. hold += input[next++] << bits;
  18788. bits += 8;
  18789. }
  18790. //===//
  18791. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  18792. //--- DROPBITS(5) ---//
  18793. hold >>>= 5;
  18794. bits -= 5;
  18795. //---//
  18796. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  18797. //--- DROPBITS(5) ---//
  18798. hold >>>= 5;
  18799. bits -= 5;
  18800. //---//
  18801. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  18802. //--- DROPBITS(4) ---//
  18803. hold >>>= 4;
  18804. bits -= 4;
  18805. //---//
  18806. //#ifndef PKZIP_BUG_WORKAROUND
  18807. if (state.nlen > 286 || state.ndist > 30) {
  18808. strm.msg = 'too many length or distance symbols';
  18809. state.mode = BAD;
  18810. break;
  18811. }
  18812. //#endif
  18813. //Tracev((stderr, "inflate: table sizes ok\n"));
  18814. state.have = 0;
  18815. state.mode = LENLENS;
  18816. /* falls through */
  18817. case LENLENS:
  18818. while (state.have < state.ncode) {
  18819. //=== NEEDBITS(3);
  18820. while (bits < 3) {
  18821. if (have === 0) { break inf_leave; }
  18822. have--;
  18823. hold += input[next++] << bits;
  18824. bits += 8;
  18825. }
  18826. //===//
  18827. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  18828. //--- DROPBITS(3) ---//
  18829. hold >>>= 3;
  18830. bits -= 3;
  18831. //---//
  18832. }
  18833. while (state.have < 19) {
  18834. state.lens[order[state.have++]] = 0;
  18835. }
  18836. // We have separate tables & no pointers. 2 commented lines below not needed.
  18837. //state.next = state.codes;
  18838. //state.lencode = state.next;
  18839. // Switch to use dynamic table
  18840. state.lencode = state.lendyn;
  18841. state.lenbits = 7;
  18842. opts = { bits: state.lenbits };
  18843. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  18844. state.lenbits = opts.bits;
  18845. if (ret) {
  18846. strm.msg = 'invalid code lengths set';
  18847. state.mode = BAD;
  18848. break;
  18849. }
  18850. //Tracev((stderr, "inflate: code lengths ok\n"));
  18851. state.have = 0;
  18852. state.mode = CODELENS;
  18853. /* falls through */
  18854. case CODELENS:
  18855. while (state.have < state.nlen + state.ndist) {
  18856. for (;;) {
  18857. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  18858. here_bits = here >>> 24;
  18859. here_op = (here >>> 16) & 0xff;
  18860. here_val = here & 0xffff;
  18861. if ((here_bits) <= bits) { break; }
  18862. //--- PULLBYTE() ---//
  18863. if (have === 0) { break inf_leave; }
  18864. have--;
  18865. hold += input[next++] << bits;
  18866. bits += 8;
  18867. //---//
  18868. }
  18869. if (here_val < 16) {
  18870. //--- DROPBITS(here.bits) ---//
  18871. hold >>>= here_bits;
  18872. bits -= here_bits;
  18873. //---//
  18874. state.lens[state.have++] = here_val;
  18875. }
  18876. else {
  18877. if (here_val === 16) {
  18878. //=== NEEDBITS(here.bits + 2);
  18879. n = here_bits + 2;
  18880. while (bits < n) {
  18881. if (have === 0) { break inf_leave; }
  18882. have--;
  18883. hold += input[next++] << bits;
  18884. bits += 8;
  18885. }
  18886. //===//
  18887. //--- DROPBITS(here.bits) ---//
  18888. hold >>>= here_bits;
  18889. bits -= here_bits;
  18890. //---//
  18891. if (state.have === 0) {
  18892. strm.msg = 'invalid bit length repeat';
  18893. state.mode = BAD;
  18894. break;
  18895. }
  18896. len = state.lens[state.have - 1];
  18897. copy = 3 + (hold & 0x03);//BITS(2);
  18898. //--- DROPBITS(2) ---//
  18899. hold >>>= 2;
  18900. bits -= 2;
  18901. //---//
  18902. }
  18903. else if (here_val === 17) {
  18904. //=== NEEDBITS(here.bits + 3);
  18905. n = here_bits + 3;
  18906. while (bits < n) {
  18907. if (have === 0) { break inf_leave; }
  18908. have--;
  18909. hold += input[next++] << bits;
  18910. bits += 8;
  18911. }
  18912. //===//
  18913. //--- DROPBITS(here.bits) ---//
  18914. hold >>>= here_bits;
  18915. bits -= here_bits;
  18916. //---//
  18917. len = 0;
  18918. copy = 3 + (hold & 0x07);//BITS(3);
  18919. //--- DROPBITS(3) ---//
  18920. hold >>>= 3;
  18921. bits -= 3;
  18922. //---//
  18923. }
  18924. else {
  18925. //=== NEEDBITS(here.bits + 7);
  18926. n = here_bits + 7;
  18927. while (bits < n) {
  18928. if (have === 0) { break inf_leave; }
  18929. have--;
  18930. hold += input[next++] << bits;
  18931. bits += 8;
  18932. }
  18933. //===//
  18934. //--- DROPBITS(here.bits) ---//
  18935. hold >>>= here_bits;
  18936. bits -= here_bits;
  18937. //---//
  18938. len = 0;
  18939. copy = 11 + (hold & 0x7f);//BITS(7);
  18940. //--- DROPBITS(7) ---//
  18941. hold >>>= 7;
  18942. bits -= 7;
  18943. //---//
  18944. }
  18945. if (state.have + copy > state.nlen + state.ndist) {
  18946. strm.msg = 'invalid bit length repeat';
  18947. state.mode = BAD;
  18948. break;
  18949. }
  18950. while (copy--) {
  18951. state.lens[state.have++] = len;
  18952. }
  18953. }
  18954. }
  18955. /* handle error breaks in while */
  18956. if (state.mode === BAD) { break; }
  18957. /* check for end-of-block code (better have one) */
  18958. if (state.lens[256] === 0) {
  18959. strm.msg = 'invalid code -- missing end-of-block';
  18960. state.mode = BAD;
  18961. break;
  18962. }
  18963. /* build code tables -- note: do not change the lenbits or distbits
  18964. values here (9 and 6) without reading the comments in inftrees.h
  18965. concerning the ENOUGH constants, which depend on those values */
  18966. state.lenbits = 9;
  18967. opts = { bits: state.lenbits };
  18968. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  18969. // We have separate tables & no pointers. 2 commented lines below not needed.
  18970. // state.next_index = opts.table_index;
  18971. state.lenbits = opts.bits;
  18972. // state.lencode = state.next;
  18973. if (ret) {
  18974. strm.msg = 'invalid literal/lengths set';
  18975. state.mode = BAD;
  18976. break;
  18977. }
  18978. state.distbits = 6;
  18979. //state.distcode.copy(state.codes);
  18980. // Switch to use dynamic table
  18981. state.distcode = state.distdyn;
  18982. opts = { bits: state.distbits };
  18983. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  18984. // We have separate tables & no pointers. 2 commented lines below not needed.
  18985. // state.next_index = opts.table_index;
  18986. state.distbits = opts.bits;
  18987. // state.distcode = state.next;
  18988. if (ret) {
  18989. strm.msg = 'invalid distances set';
  18990. state.mode = BAD;
  18991. break;
  18992. }
  18993. //Tracev((stderr, 'inflate: codes ok\n'));
  18994. state.mode = LEN_;
  18995. if (flush === Z_TREES) { break inf_leave; }
  18996. /* falls through */
  18997. case LEN_:
  18998. state.mode = LEN;
  18999. /* falls through */
  19000. case LEN:
  19001. if (have >= 6 && left >= 258) {
  19002. //--- RESTORE() ---
  19003. strm.next_out = put;
  19004. strm.avail_out = left;
  19005. strm.next_in = next;
  19006. strm.avail_in = have;
  19007. state.hold = hold;
  19008. state.bits = bits;
  19009. //---
  19010. inflate_fast(strm, _out);
  19011. //--- LOAD() ---
  19012. put = strm.next_out;
  19013. output = strm.output;
  19014. left = strm.avail_out;
  19015. next = strm.next_in;
  19016. input = strm.input;
  19017. have = strm.avail_in;
  19018. hold = state.hold;
  19019. bits = state.bits;
  19020. //---
  19021. if (state.mode === TYPE) {
  19022. state.back = -1;
  19023. }
  19024. break;
  19025. }
  19026. state.back = 0;
  19027. for (;;) {
  19028. here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
  19029. here_bits = here >>> 24;
  19030. here_op = (here >>> 16) & 0xff;
  19031. here_val = here & 0xffff;
  19032. if (here_bits <= bits) { break; }
  19033. //--- PULLBYTE() ---//
  19034. if (have === 0) { break inf_leave; }
  19035. have--;
  19036. hold += input[next++] << bits;
  19037. bits += 8;
  19038. //---//
  19039. }
  19040. if (here_op && (here_op & 0xf0) === 0) {
  19041. last_bits = here_bits;
  19042. last_op = here_op;
  19043. last_val = here_val;
  19044. for (;;) {
  19045. here = state.lencode[last_val +
  19046. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  19047. here_bits = here >>> 24;
  19048. here_op = (here >>> 16) & 0xff;
  19049. here_val = here & 0xffff;
  19050. if ((last_bits + here_bits) <= bits) { break; }
  19051. //--- PULLBYTE() ---//
  19052. if (have === 0) { break inf_leave; }
  19053. have--;
  19054. hold += input[next++] << bits;
  19055. bits += 8;
  19056. //---//
  19057. }
  19058. //--- DROPBITS(last.bits) ---//
  19059. hold >>>= last_bits;
  19060. bits -= last_bits;
  19061. //---//
  19062. state.back += last_bits;
  19063. }
  19064. //--- DROPBITS(here.bits) ---//
  19065. hold >>>= here_bits;
  19066. bits -= here_bits;
  19067. //---//
  19068. state.back += here_bits;
  19069. state.length = here_val;
  19070. if (here_op === 0) {
  19071. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  19072. // "inflate: literal '%c'\n" :
  19073. // "inflate: literal 0x%02x\n", here.val));
  19074. state.mode = LIT;
  19075. break;
  19076. }
  19077. if (here_op & 32) {
  19078. //Tracevv((stderr, "inflate: end of block\n"));
  19079. state.back = -1;
  19080. state.mode = TYPE;
  19081. break;
  19082. }
  19083. if (here_op & 64) {
  19084. strm.msg = 'invalid literal/length code';
  19085. state.mode = BAD;
  19086. break;
  19087. }
  19088. state.extra = here_op & 15;
  19089. state.mode = LENEXT;
  19090. /* falls through */
  19091. case LENEXT:
  19092. if (state.extra) {
  19093. //=== NEEDBITS(state.extra);
  19094. n = state.extra;
  19095. while (bits < n) {
  19096. if (have === 0) { break inf_leave; }
  19097. have--;
  19098. hold += input[next++] << bits;
  19099. bits += 8;
  19100. }
  19101. //===//
  19102. state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  19103. //--- DROPBITS(state.extra) ---//
  19104. hold >>>= state.extra;
  19105. bits -= state.extra;
  19106. //---//
  19107. state.back += state.extra;
  19108. }
  19109. //Tracevv((stderr, "inflate: length %u\n", state.length));
  19110. state.was = state.length;
  19111. state.mode = DIST;
  19112. /* falls through */
  19113. case DIST:
  19114. for (;;) {
  19115. here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
  19116. here_bits = here >>> 24;
  19117. here_op = (here >>> 16) & 0xff;
  19118. here_val = here & 0xffff;
  19119. if ((here_bits) <= bits) { break; }
  19120. //--- PULLBYTE() ---//
  19121. if (have === 0) { break inf_leave; }
  19122. have--;
  19123. hold += input[next++] << bits;
  19124. bits += 8;
  19125. //---//
  19126. }
  19127. if ((here_op & 0xf0) === 0) {
  19128. last_bits = here_bits;
  19129. last_op = here_op;
  19130. last_val = here_val;
  19131. for (;;) {
  19132. here = state.distcode[last_val +
  19133. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  19134. here_bits = here >>> 24;
  19135. here_op = (here >>> 16) & 0xff;
  19136. here_val = here & 0xffff;
  19137. if ((last_bits + here_bits) <= bits) { break; }
  19138. //--- PULLBYTE() ---//
  19139. if (have === 0) { break inf_leave; }
  19140. have--;
  19141. hold += input[next++] << bits;
  19142. bits += 8;
  19143. //---//
  19144. }
  19145. //--- DROPBITS(last.bits) ---//
  19146. hold >>>= last_bits;
  19147. bits -= last_bits;
  19148. //---//
  19149. state.back += last_bits;
  19150. }
  19151. //--- DROPBITS(here.bits) ---//
  19152. hold >>>= here_bits;
  19153. bits -= here_bits;
  19154. //---//
  19155. state.back += here_bits;
  19156. if (here_op & 64) {
  19157. strm.msg = 'invalid distance code';
  19158. state.mode = BAD;
  19159. break;
  19160. }
  19161. state.offset = here_val;
  19162. state.extra = (here_op) & 15;
  19163. state.mode = DISTEXT;
  19164. /* falls through */
  19165. case DISTEXT:
  19166. if (state.extra) {
  19167. //=== NEEDBITS(state.extra);
  19168. n = state.extra;
  19169. while (bits < n) {
  19170. if (have === 0) { break inf_leave; }
  19171. have--;
  19172. hold += input[next++] << bits;
  19173. bits += 8;
  19174. }
  19175. //===//
  19176. state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  19177. //--- DROPBITS(state.extra) ---//
  19178. hold >>>= state.extra;
  19179. bits -= state.extra;
  19180. //---//
  19181. state.back += state.extra;
  19182. }
  19183. //#ifdef INFLATE_STRICT
  19184. if (state.offset > state.dmax) {
  19185. strm.msg = 'invalid distance too far back';
  19186. state.mode = BAD;
  19187. break;
  19188. }
  19189. //#endif
  19190. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  19191. state.mode = MATCH;
  19192. /* falls through */
  19193. case MATCH:
  19194. if (left === 0) { break inf_leave; }
  19195. copy = _out - left;
  19196. if (state.offset > copy) { /* copy from window */
  19197. copy = state.offset - copy;
  19198. if (copy > state.whave) {
  19199. if (state.sane) {
  19200. strm.msg = 'invalid distance too far back';
  19201. state.mode = BAD;
  19202. break;
  19203. }
  19204. // (!) This block is disabled in zlib defaults,
  19205. // don't enable it for binary compatibility
  19206. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  19207. // Trace((stderr, "inflate.c too far\n"));
  19208. // copy -= state.whave;
  19209. // if (copy > state.length) { copy = state.length; }
  19210. // if (copy > left) { copy = left; }
  19211. // left -= copy;
  19212. // state.length -= copy;
  19213. // do {
  19214. // output[put++] = 0;
  19215. // } while (--copy);
  19216. // if (state.length === 0) { state.mode = LEN; }
  19217. // break;
  19218. //#endif
  19219. }
  19220. if (copy > state.wnext) {
  19221. copy -= state.wnext;
  19222. from = state.wsize - copy;
  19223. }
  19224. else {
  19225. from = state.wnext - copy;
  19226. }
  19227. if (copy > state.length) { copy = state.length; }
  19228. from_source = state.window;
  19229. }
  19230. else { /* copy from output */
  19231. from_source = output;
  19232. from = put - state.offset;
  19233. copy = state.length;
  19234. }
  19235. if (copy > left) { copy = left; }
  19236. left -= copy;
  19237. state.length -= copy;
  19238. do {
  19239. output[put++] = from_source[from++];
  19240. } while (--copy);
  19241. if (state.length === 0) { state.mode = LEN; }
  19242. break;
  19243. case LIT:
  19244. if (left === 0) { break inf_leave; }
  19245. output[put++] = state.length;
  19246. left--;
  19247. state.mode = LEN;
  19248. break;
  19249. case CHECK:
  19250. if (state.wrap) {
  19251. //=== NEEDBITS(32);
  19252. while (bits < 32) {
  19253. if (have === 0) { break inf_leave; }
  19254. have--;
  19255. // Use '|' instead of '+' to make sure that result is signed
  19256. hold |= input[next++] << bits;
  19257. bits += 8;
  19258. }
  19259. //===//
  19260. _out -= left;
  19261. strm.total_out += _out;
  19262. state.total += _out;
  19263. if (_out) {
  19264. strm.adler = state.check =
  19265. /*UPDATE(state.check, put - _out, _out);*/
  19266. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  19267. }
  19268. _out = left;
  19269. // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
  19270. if ((state.flags ? hold : zswap32(hold)) !== state.check) {
  19271. strm.msg = 'incorrect data check';
  19272. state.mode = BAD;
  19273. break;
  19274. }
  19275. //=== INITBITS();
  19276. hold = 0;
  19277. bits = 0;
  19278. //===//
  19279. //Tracev((stderr, "inflate: check matches trailer\n"));
  19280. }
  19281. state.mode = LENGTH;
  19282. /* falls through */
  19283. case LENGTH:
  19284. if (state.wrap && state.flags) {
  19285. //=== NEEDBITS(32);
  19286. while (bits < 32) {
  19287. if (have === 0) { break inf_leave; }
  19288. have--;
  19289. hold += input[next++] << bits;
  19290. bits += 8;
  19291. }
  19292. //===//
  19293. if (hold !== (state.total & 0xffffffff)) {
  19294. strm.msg = 'incorrect length check';
  19295. state.mode = BAD;
  19296. break;
  19297. }
  19298. //=== INITBITS();
  19299. hold = 0;
  19300. bits = 0;
  19301. //===//
  19302. //Tracev((stderr, "inflate: length matches trailer\n"));
  19303. }
  19304. state.mode = DONE;
  19305. /* falls through */
  19306. case DONE:
  19307. ret = Z_STREAM_END;
  19308. break inf_leave;
  19309. case BAD:
  19310. ret = Z_DATA_ERROR;
  19311. break inf_leave;
  19312. case MEM:
  19313. return Z_MEM_ERROR;
  19314. case SYNC:
  19315. /* falls through */
  19316. default:
  19317. return Z_STREAM_ERROR;
  19318. }
  19319. }
  19320. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  19321. /*
  19322. Return from inflate(), updating the total counts and the check value.
  19323. If there was no progress during the inflate() call, return a buffer
  19324. error. Call updatewindow() to create and/or update the window state.
  19325. Note: a memory error from inflate() is non-recoverable.
  19326. */
  19327. //--- RESTORE() ---
  19328. strm.next_out = put;
  19329. strm.avail_out = left;
  19330. strm.next_in = next;
  19331. strm.avail_in = have;
  19332. state.hold = hold;
  19333. state.bits = bits;
  19334. //---
  19335. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  19336. (state.mode < CHECK || flush !== Z_FINISH))) {
  19337. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  19338. state.mode = MEM;
  19339. return Z_MEM_ERROR;
  19340. }
  19341. }
  19342. _in -= strm.avail_in;
  19343. _out -= strm.avail_out;
  19344. strm.total_in += _in;
  19345. strm.total_out += _out;
  19346. state.total += _out;
  19347. if (state.wrap && _out) {
  19348. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  19349. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  19350. }
  19351. strm.data_type = state.bits + (state.last ? 64 : 0) +
  19352. (state.mode === TYPE ? 128 : 0) +
  19353. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  19354. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  19355. ret = Z_BUF_ERROR;
  19356. }
  19357. return ret;
  19358. }
  19359. function inflateEnd(strm) {
  19360. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  19361. return Z_STREAM_ERROR;
  19362. }
  19363. var state = strm.state;
  19364. if (state.window) {
  19365. state.window = null;
  19366. }
  19367. strm.state = null;
  19368. return Z_OK;
  19369. }
  19370. function inflateGetHeader(strm, head) {
  19371. var state;
  19372. /* check state */
  19373. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19374. state = strm.state;
  19375. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  19376. /* save header structure */
  19377. state.head = head;
  19378. head.done = false;
  19379. return Z_OK;
  19380. }
  19381. function inflateSetDictionary(strm, dictionary) {
  19382. var dictLength = dictionary.length;
  19383. var state;
  19384. var dictid;
  19385. var ret;
  19386. /* check state */
  19387. if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  19388. state = strm.state;
  19389. if (state.wrap !== 0 && state.mode !== DICT) {
  19390. return Z_STREAM_ERROR;
  19391. }
  19392. /* check for correct dictionary identifier */
  19393. if (state.mode === DICT) {
  19394. dictid = 1; /* adler32(0, null, 0)*/
  19395. /* dictid = adler32(dictid, dictionary, dictLength); */
  19396. dictid = adler32(dictid, dictionary, dictLength, 0);
  19397. if (dictid !== state.check) {
  19398. return Z_DATA_ERROR;
  19399. }
  19400. }
  19401. /* copy dictionary to window using updatewindow(), which will amend the
  19402. existing dictionary if appropriate */
  19403. ret = updatewindow(strm, dictionary, dictLength, dictLength);
  19404. if (ret) {
  19405. state.mode = MEM;
  19406. return Z_MEM_ERROR;
  19407. }
  19408. state.havedict = 1;
  19409. // Tracev((stderr, "inflate: dictionary set\n"));
  19410. return Z_OK;
  19411. }
  19412. exports.inflateReset = inflateReset;
  19413. exports.inflateReset2 = inflateReset2;
  19414. exports.inflateResetKeep = inflateResetKeep;
  19415. exports.inflateInit = inflateInit;
  19416. exports.inflateInit2 = inflateInit2;
  19417. exports.inflate = inflate;
  19418. exports.inflateEnd = inflateEnd;
  19419. exports.inflateGetHeader = inflateGetHeader;
  19420. exports.inflateSetDictionary = inflateSetDictionary;
  19421. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  19422. /* Not implemented
  19423. exports.inflateCopy = inflateCopy;
  19424. exports.inflateGetDictionary = inflateGetDictionary;
  19425. exports.inflateMark = inflateMark;
  19426. exports.inflatePrime = inflatePrime;
  19427. exports.inflateSync = inflateSync;
  19428. exports.inflateSyncPoint = inflateSyncPoint;
  19429. exports.inflateUndermine = inflateUndermine;
  19430. */
  19431. },{"../utils/common":112,"./adler32":113,"./crc32":115,"./inffast":117,"./inftrees":119}],119:[function(require,module,exports){
  19432. 'use strict';
  19433. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  19434. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  19435. //
  19436. // This software is provided 'as-is', without any express or implied
  19437. // warranty. In no event will the authors be held liable for any damages
  19438. // arising from the use of this software.
  19439. //
  19440. // Permission is granted to anyone to use this software for any purpose,
  19441. // including commercial applications, and to alter it and redistribute it
  19442. // freely, subject to the following restrictions:
  19443. //
  19444. // 1. The origin of this software must not be misrepresented; you must not
  19445. // claim that you wrote the original software. If you use this software
  19446. // in a product, an acknowledgment in the product documentation would be
  19447. // appreciated but is not required.
  19448. // 2. Altered source versions must be plainly marked as such, and must not be
  19449. // misrepresented as being the original software.
  19450. // 3. This notice may not be removed or altered from any source distribution.
  19451. var utils = require('../utils/common');
  19452. var MAXBITS = 15;
  19453. var ENOUGH_LENS = 852;
  19454. var ENOUGH_DISTS = 592;
  19455. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  19456. var CODES = 0;
  19457. var LENS = 1;
  19458. var DISTS = 2;
  19459. var lbase = [ /* Length codes 257..285 base */
  19460. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  19461. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  19462. ];
  19463. var lext = [ /* Length codes 257..285 extra */
  19464. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  19465. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  19466. ];
  19467. var dbase = [ /* Distance codes 0..29 base */
  19468. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  19469. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  19470. 8193, 12289, 16385, 24577, 0, 0
  19471. ];
  19472. var dext = [ /* Distance codes 0..29 extra */
  19473. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  19474. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  19475. 28, 28, 29, 29, 64, 64
  19476. ];
  19477. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  19478. {
  19479. var bits = opts.bits;
  19480. //here = opts.here; /* table entry for duplication */
  19481. var len = 0; /* a code's length in bits */
  19482. var sym = 0; /* index of code symbols */
  19483. var min = 0, max = 0; /* minimum and maximum code lengths */
  19484. var root = 0; /* number of index bits for root table */
  19485. var curr = 0; /* number of index bits for current table */
  19486. var drop = 0; /* code bits to drop for sub-table */
  19487. var left = 0; /* number of prefix codes available */
  19488. var used = 0; /* code entries in table used */
  19489. var huff = 0; /* Huffman code */
  19490. var incr; /* for incrementing code, index */
  19491. var fill; /* index for replicating entries */
  19492. var low; /* low bits for current root entry */
  19493. var mask; /* mask for low root bits */
  19494. var next; /* next available space in table */
  19495. var base = null; /* base value table to use */
  19496. var base_index = 0;
  19497. // var shoextra; /* extra bits table to use */
  19498. var end; /* use base and extra for symbol > end */
  19499. var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
  19500. var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
  19501. var extra = null;
  19502. var extra_index = 0;
  19503. var here_bits, here_op, here_val;
  19504. /*
  19505. Process a set of code lengths to create a canonical Huffman code. The
  19506. code lengths are lens[0..codes-1]. Each length corresponds to the
  19507. symbols 0..codes-1. The Huffman code is generated by first sorting the
  19508. symbols by length from short to long, and retaining the symbol order
  19509. for codes with equal lengths. Then the code starts with all zero bits
  19510. for the first code of the shortest length, and the codes are integer
  19511. increments for the same length, and zeros are appended as the length
  19512. increases. For the deflate format, these bits are stored backwards
  19513. from their more natural integer increment ordering, and so when the
  19514. decoding tables are built in the large loop below, the integer codes
  19515. are incremented backwards.
  19516. This routine assumes, but does not check, that all of the entries in
  19517. lens[] are in the range 0..MAXBITS. The caller must assure this.
  19518. 1..MAXBITS is interpreted as that code length. zero means that that
  19519. symbol does not occur in this code.
  19520. The codes are sorted by computing a count of codes for each length,
  19521. creating from that a table of starting indices for each length in the
  19522. sorted table, and then entering the symbols in order in the sorted
  19523. table. The sorted table is work[], with that space being provided by
  19524. the caller.
  19525. The length counts are used for other purposes as well, i.e. finding
  19526. the minimum and maximum length codes, determining if there are any
  19527. codes at all, checking for a valid set of lengths, and looking ahead
  19528. at length counts to determine sub-table sizes when building the
  19529. decoding tables.
  19530. */
  19531. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  19532. for (len = 0; len <= MAXBITS; len++) {
  19533. count[len] = 0;
  19534. }
  19535. for (sym = 0; sym < codes; sym++) {
  19536. count[lens[lens_index + sym]]++;
  19537. }
  19538. /* bound code lengths, force root to be within code lengths */
  19539. root = bits;
  19540. for (max = MAXBITS; max >= 1; max--) {
  19541. if (count[max] !== 0) { break; }
  19542. }
  19543. if (root > max) {
  19544. root = max;
  19545. }
  19546. if (max === 0) { /* no symbols to code at all */
  19547. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  19548. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  19549. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  19550. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  19551. //table.op[opts.table_index] = 64;
  19552. //table.bits[opts.table_index] = 1;
  19553. //table.val[opts.table_index++] = 0;
  19554. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  19555. opts.bits = 1;
  19556. return 0; /* no symbols, but wait for decoding to report error */
  19557. }
  19558. for (min = 1; min < max; min++) {
  19559. if (count[min] !== 0) { break; }
  19560. }
  19561. if (root < min) {
  19562. root = min;
  19563. }
  19564. /* check for an over-subscribed or incomplete set of lengths */
  19565. left = 1;
  19566. for (len = 1; len <= MAXBITS; len++) {
  19567. left <<= 1;
  19568. left -= count[len];
  19569. if (left < 0) {
  19570. return -1;
  19571. } /* over-subscribed */
  19572. }
  19573. if (left > 0 && (type === CODES || max !== 1)) {
  19574. return -1; /* incomplete set */
  19575. }
  19576. /* generate offsets into symbol table for each length for sorting */
  19577. offs[1] = 0;
  19578. for (len = 1; len < MAXBITS; len++) {
  19579. offs[len + 1] = offs[len] + count[len];
  19580. }
  19581. /* sort symbols by length, by symbol order within each length */
  19582. for (sym = 0; sym < codes; sym++) {
  19583. if (lens[lens_index + sym] !== 0) {
  19584. work[offs[lens[lens_index + sym]]++] = sym;
  19585. }
  19586. }
  19587. /*
  19588. Create and fill in decoding tables. In this loop, the table being
  19589. filled is at next and has curr index bits. The code being used is huff
  19590. with length len. That code is converted to an index by dropping drop
  19591. bits off of the bottom. For codes where len is less than drop + curr,
  19592. those top drop + curr - len bits are incremented through all values to
  19593. fill the table with replicated entries.
  19594. root is the number of index bits for the root table. When len exceeds
  19595. root, sub-tables are created pointed to by the root entry with an index
  19596. of the low root bits of huff. This is saved in low to check for when a
  19597. new sub-table should be started. drop is zero when the root table is
  19598. being filled, and drop is root when sub-tables are being filled.
  19599. When a new sub-table is needed, it is necessary to look ahead in the
  19600. code lengths to determine what size sub-table is needed. The length
  19601. counts are used for this, and so count[] is decremented as codes are
  19602. entered in the tables.
  19603. used keeps track of how many table entries have been allocated from the
  19604. provided *table space. It is checked for LENS and DIST tables against
  19605. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  19606. the initial root table size constants. See the comments in inftrees.h
  19607. for more information.
  19608. sym increments through all symbols, and the loop terminates when
  19609. all codes of length max, i.e. all codes, have been processed. This
  19610. routine permits incomplete codes, so another loop after this one fills
  19611. in the rest of the decoding tables with invalid code markers.
  19612. */
  19613. /* set up for code type */
  19614. // poor man optimization - use if-else instead of switch,
  19615. // to avoid deopts in old v8
  19616. if (type === CODES) {
  19617. base = extra = work; /* dummy value--not used */
  19618. end = 19;
  19619. } else if (type === LENS) {
  19620. base = lbase;
  19621. base_index -= 257;
  19622. extra = lext;
  19623. extra_index -= 257;
  19624. end = 256;
  19625. } else { /* DISTS */
  19626. base = dbase;
  19627. extra = dext;
  19628. end = -1;
  19629. }
  19630. /* initialize opts for loop */
  19631. huff = 0; /* starting code */
  19632. sym = 0; /* starting code symbol */
  19633. len = min; /* starting code length */
  19634. next = table_index; /* current table to fill in */
  19635. curr = root; /* current table index bits */
  19636. drop = 0; /* current bits to drop from code for index */
  19637. low = -1; /* trigger new sub-table when len > root */
  19638. used = 1 << root; /* use root table entries */
  19639. mask = used - 1; /* mask for comparing low */
  19640. /* check available table space */
  19641. if ((type === LENS && used > ENOUGH_LENS) ||
  19642. (type === DISTS && used > ENOUGH_DISTS)) {
  19643. return 1;
  19644. }
  19645. /* process all codes and make table entries */
  19646. for (;;) {
  19647. /* create table entry */
  19648. here_bits = len - drop;
  19649. if (work[sym] < end) {
  19650. here_op = 0;
  19651. here_val = work[sym];
  19652. }
  19653. else if (work[sym] > end) {
  19654. here_op = extra[extra_index + work[sym]];
  19655. here_val = base[base_index + work[sym]];
  19656. }
  19657. else {
  19658. here_op = 32 + 64; /* end of block */
  19659. here_val = 0;
  19660. }
  19661. /* replicate for those indices with low len bits equal to huff */
  19662. incr = 1 << (len - drop);
  19663. fill = 1 << curr;
  19664. min = fill; /* save offset to next table */
  19665. do {
  19666. fill -= incr;
  19667. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  19668. } while (fill !== 0);
  19669. /* backwards increment the len-bit code huff */
  19670. incr = 1 << (len - 1);
  19671. while (huff & incr) {
  19672. incr >>= 1;
  19673. }
  19674. if (incr !== 0) {
  19675. huff &= incr - 1;
  19676. huff += incr;
  19677. } else {
  19678. huff = 0;
  19679. }
  19680. /* go to next symbol, update count, len */
  19681. sym++;
  19682. if (--count[len] === 0) {
  19683. if (len === max) { break; }
  19684. len = lens[lens_index + work[sym]];
  19685. }
  19686. /* create new sub-table if needed */
  19687. if (len > root && (huff & mask) !== low) {
  19688. /* if first time, transition to sub-tables */
  19689. if (drop === 0) {
  19690. drop = root;
  19691. }
  19692. /* increment past last table */
  19693. next += min; /* here min is 1 << curr */
  19694. /* determine length of next table */
  19695. curr = len - drop;
  19696. left = 1 << curr;
  19697. while (curr + drop < max) {
  19698. left -= count[curr + drop];
  19699. if (left <= 0) { break; }
  19700. curr++;
  19701. left <<= 1;
  19702. }
  19703. /* check for enough space */
  19704. used += 1 << curr;
  19705. if ((type === LENS && used > ENOUGH_LENS) ||
  19706. (type === DISTS && used > ENOUGH_DISTS)) {
  19707. return 1;
  19708. }
  19709. /* point entry in root table to sub-table */
  19710. low = huff & mask;
  19711. /*table.op[low] = curr;
  19712. table.bits[low] = root;
  19713. table.val[low] = next - opts.table_index;*/
  19714. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  19715. }
  19716. }
  19717. /* fill in remaining table entry if code is incomplete (guaranteed to have
  19718. at most one remaining entry, since if the code is incomplete, the
  19719. maximum code length that was allowed to get this far is one bit) */
  19720. if (huff !== 0) {
  19721. //table.op[next + huff] = 64; /* invalid code marker */
  19722. //table.bits[next + huff] = len - drop;
  19723. //table.val[next + huff] = 0;
  19724. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  19725. }
  19726. /* set return parameters */
  19727. //opts.table_index += used;
  19728. opts.bits = root;
  19729. return 0;
  19730. };
  19731. },{"../utils/common":112}],120:[function(require,module,exports){
  19732. 'use strict';
  19733. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  19734. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  19735. //
  19736. // This software is provided 'as-is', without any express or implied
  19737. // warranty. In no event will the authors be held liable for any damages
  19738. // arising from the use of this software.
  19739. //
  19740. // Permission is granted to anyone to use this software for any purpose,
  19741. // including commercial applications, and to alter it and redistribute it
  19742. // freely, subject to the following restrictions:
  19743. //
  19744. // 1. The origin of this software must not be misrepresented; you must not
  19745. // claim that you wrote the original software. If you use this software
  19746. // in a product, an acknowledgment in the product documentation would be
  19747. // appreciated but is not required.
  19748. // 2. Altered source versions must be plainly marked as such, and must not be
  19749. // misrepresented as being the original software.
  19750. // 3. This notice may not be removed or altered from any source distribution.
  19751. module.exports = {
  19752. 2: 'need dictionary', /* Z_NEED_DICT 2 */
  19753. 1: 'stream end', /* Z_STREAM_END 1 */
  19754. 0: '', /* Z_OK 0 */
  19755. '-1': 'file error', /* Z_ERRNO (-1) */
  19756. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  19757. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  19758. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  19759. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  19760. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  19761. };
  19762. },{}],121:[function(require,module,exports){
  19763. 'use strict';
  19764. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  19765. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  19766. //
  19767. // This software is provided 'as-is', without any express or implied
  19768. // warranty. In no event will the authors be held liable for any damages
  19769. // arising from the use of this software.
  19770. //
  19771. // Permission is granted to anyone to use this software for any purpose,
  19772. // including commercial applications, and to alter it and redistribute it
  19773. // freely, subject to the following restrictions:
  19774. //
  19775. // 1. The origin of this software must not be misrepresented; you must not
  19776. // claim that you wrote the original software. If you use this software
  19777. // in a product, an acknowledgment in the product documentation would be
  19778. // appreciated but is not required.
  19779. // 2. Altered source versions must be plainly marked as such, and must not be
  19780. // misrepresented as being the original software.
  19781. // 3. This notice may not be removed or altered from any source distribution.
  19782. var utils = require('../utils/common');
  19783. /* Public constants ==========================================================*/
  19784. /* ===========================================================================*/
  19785. //var Z_FILTERED = 1;
  19786. //var Z_HUFFMAN_ONLY = 2;
  19787. //var Z_RLE = 3;
  19788. var Z_FIXED = 4;
  19789. //var Z_DEFAULT_STRATEGY = 0;
  19790. /* Possible values of the data_type field (though see inflate()) */
  19791. var Z_BINARY = 0;
  19792. var Z_TEXT = 1;
  19793. //var Z_ASCII = 1; // = Z_TEXT
  19794. var Z_UNKNOWN = 2;
  19795. /*============================================================================*/
  19796. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  19797. // From zutil.h
  19798. var STORED_BLOCK = 0;
  19799. var STATIC_TREES = 1;
  19800. var DYN_TREES = 2;
  19801. /* The three kinds of block type */
  19802. var MIN_MATCH = 3;
  19803. var MAX_MATCH = 258;
  19804. /* The minimum and maximum match lengths */
  19805. // From deflate.h
  19806. /* ===========================================================================
  19807. * Internal compression state.
  19808. */
  19809. var LENGTH_CODES = 29;
  19810. /* number of length codes, not counting the special END_BLOCK code */
  19811. var LITERALS = 256;
  19812. /* number of literal bytes 0..255 */
  19813. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  19814. /* number of Literal or Length codes, including the END_BLOCK code */
  19815. var D_CODES = 30;
  19816. /* number of distance codes */
  19817. var BL_CODES = 19;
  19818. /* number of codes used to transfer the bit lengths */
  19819. var HEAP_SIZE = 2 * L_CODES + 1;
  19820. /* maximum heap size */
  19821. var MAX_BITS = 15;
  19822. /* All codes must not exceed MAX_BITS bits */
  19823. var Buf_size = 16;
  19824. /* size of bit buffer in bi_buf */
  19825. /* ===========================================================================
  19826. * Constants
  19827. */
  19828. var MAX_BL_BITS = 7;
  19829. /* Bit length codes must not exceed MAX_BL_BITS bits */
  19830. var END_BLOCK = 256;
  19831. /* end of block literal code */
  19832. var REP_3_6 = 16;
  19833. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  19834. var REPZ_3_10 = 17;
  19835. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  19836. var REPZ_11_138 = 18;
  19837. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  19838. /* eslint-disable comma-spacing,array-bracket-spacing */
  19839. var extra_lbits = /* extra bits for each length code */
  19840. [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
  19841. var extra_dbits = /* extra bits for each distance code */
  19842. [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
  19843. var extra_blbits = /* extra bits for each bit length code */
  19844. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  19845. var bl_order =
  19846. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  19847. /* eslint-enable comma-spacing,array-bracket-spacing */
  19848. /* The lengths of the bit length codes are sent in order of decreasing
  19849. * probability, to avoid transmitting the lengths for unused bit length codes.
  19850. */
  19851. /* ===========================================================================
  19852. * Local data. These are initialized only once.
  19853. */
  19854. // We pre-fill arrays with 0 to avoid uninitialized gaps
  19855. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  19856. // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
  19857. var static_ltree = new Array((L_CODES + 2) * 2);
  19858. zero(static_ltree);
  19859. /* The static literal tree. Since the bit lengths are imposed, there is no
  19860. * need for the L_CODES extra codes used during heap construction. However
  19861. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  19862. * below).
  19863. */
  19864. var static_dtree = new Array(D_CODES * 2);
  19865. zero(static_dtree);
  19866. /* The static distance tree. (Actually a trivial tree since all codes use
  19867. * 5 bits.)
  19868. */
  19869. var _dist_code = new Array(DIST_CODE_LEN);
  19870. zero(_dist_code);
  19871. /* Distance codes. The first 256 values correspond to the distances
  19872. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  19873. * the 15 bit distances.
  19874. */
  19875. var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
  19876. zero(_length_code);
  19877. /* length code for each normalized match length (0 == MIN_MATCH) */
  19878. var base_length = new Array(LENGTH_CODES);
  19879. zero(base_length);
  19880. /* First normalized length for each code (0 = MIN_MATCH) */
  19881. var base_dist = new Array(D_CODES);
  19882. zero(base_dist);
  19883. /* First normalized distance for each code (0 = distance of 1) */
  19884. function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  19885. this.static_tree = static_tree; /* static tree or NULL */
  19886. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  19887. this.extra_base = extra_base; /* base index for extra_bits */
  19888. this.elems = elems; /* max number of elements in the tree */
  19889. this.max_length = max_length; /* max bit length for the codes */
  19890. // show if `static_tree` has data or dummy - needed for monomorphic objects
  19891. this.has_stree = static_tree && static_tree.length;
  19892. }
  19893. var static_l_desc;
  19894. var static_d_desc;
  19895. var static_bl_desc;
  19896. function TreeDesc(dyn_tree, stat_desc) {
  19897. this.dyn_tree = dyn_tree; /* the dynamic tree */
  19898. this.max_code = 0; /* largest code with non zero frequency */
  19899. this.stat_desc = stat_desc; /* the corresponding static tree */
  19900. }
  19901. function d_code(dist) {
  19902. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  19903. }
  19904. /* ===========================================================================
  19905. * Output a short LSB first on the stream.
  19906. * IN assertion: there is enough room in pendingBuf.
  19907. */
  19908. function put_short(s, w) {
  19909. // put_byte(s, (uch)((w) & 0xff));
  19910. // put_byte(s, (uch)((ush)(w) >> 8));
  19911. s.pending_buf[s.pending++] = (w) & 0xff;
  19912. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  19913. }
  19914. /* ===========================================================================
  19915. * Send a value on a given number of bits.
  19916. * IN assertion: length <= 16 and value fits in length bits.
  19917. */
  19918. function send_bits(s, value, length) {
  19919. if (s.bi_valid > (Buf_size - length)) {
  19920. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  19921. put_short(s, s.bi_buf);
  19922. s.bi_buf = value >> (Buf_size - s.bi_valid);
  19923. s.bi_valid += length - Buf_size;
  19924. } else {
  19925. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  19926. s.bi_valid += length;
  19927. }
  19928. }
  19929. function send_code(s, c, tree) {
  19930. send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  19931. }
  19932. /* ===========================================================================
  19933. * Reverse the first len bits of a code, using straightforward code (a faster
  19934. * method would use a table)
  19935. * IN assertion: 1 <= len <= 15
  19936. */
  19937. function bi_reverse(code, len) {
  19938. var res = 0;
  19939. do {
  19940. res |= code & 1;
  19941. code >>>= 1;
  19942. res <<= 1;
  19943. } while (--len > 0);
  19944. return res >>> 1;
  19945. }
  19946. /* ===========================================================================
  19947. * Flush the bit buffer, keeping at most 7 bits in it.
  19948. */
  19949. function bi_flush(s) {
  19950. if (s.bi_valid === 16) {
  19951. put_short(s, s.bi_buf);
  19952. s.bi_buf = 0;
  19953. s.bi_valid = 0;
  19954. } else if (s.bi_valid >= 8) {
  19955. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  19956. s.bi_buf >>= 8;
  19957. s.bi_valid -= 8;
  19958. }
  19959. }
  19960. /* ===========================================================================
  19961. * Compute the optimal bit lengths for a tree and update the total bit length
  19962. * for the current block.
  19963. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  19964. * above are the tree nodes sorted by increasing frequency.
  19965. * OUT assertions: the field len is set to the optimal bit length, the
  19966. * array bl_count contains the frequencies for each bit length.
  19967. * The length opt_len is updated; static_len is also updated if stree is
  19968. * not null.
  19969. */
  19970. function gen_bitlen(s, desc)
  19971. // deflate_state *s;
  19972. // tree_desc *desc; /* the tree descriptor */
  19973. {
  19974. var tree = desc.dyn_tree;
  19975. var max_code = desc.max_code;
  19976. var stree = desc.stat_desc.static_tree;
  19977. var has_stree = desc.stat_desc.has_stree;
  19978. var extra = desc.stat_desc.extra_bits;
  19979. var base = desc.stat_desc.extra_base;
  19980. var max_length = desc.stat_desc.max_length;
  19981. var h; /* heap index */
  19982. var n, m; /* iterate over the tree elements */
  19983. var bits; /* bit length */
  19984. var xbits; /* extra bits */
  19985. var f; /* frequency */
  19986. var overflow = 0; /* number of elements with bit length too large */
  19987. for (bits = 0; bits <= MAX_BITS; bits++) {
  19988. s.bl_count[bits] = 0;
  19989. }
  19990. /* In a first pass, compute the optimal bit lengths (which may
  19991. * overflow in the case of the bit length tree).
  19992. */
  19993. tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  19994. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  19995. n = s.heap[h];
  19996. bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  19997. if (bits > max_length) {
  19998. bits = max_length;
  19999. overflow++;
  20000. }
  20001. tree[n * 2 + 1]/*.Len*/ = bits;
  20002. /* We overwrite tree[n].Dad which is no longer needed */
  20003. if (n > max_code) { continue; } /* not a leaf node */
  20004. s.bl_count[bits]++;
  20005. xbits = 0;
  20006. if (n >= base) {
  20007. xbits = extra[n - base];
  20008. }
  20009. f = tree[n * 2]/*.Freq*/;
  20010. s.opt_len += f * (bits + xbits);
  20011. if (has_stree) {
  20012. s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
  20013. }
  20014. }
  20015. if (overflow === 0) { return; }
  20016. // Trace((stderr,"\nbit length overflow\n"));
  20017. /* This happens for example on obj2 and pic of the Calgary corpus */
  20018. /* Find the first bit length which could increase: */
  20019. do {
  20020. bits = max_length - 1;
  20021. while (s.bl_count[bits] === 0) { bits--; }
  20022. s.bl_count[bits]--; /* move one leaf down the tree */
  20023. s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  20024. s.bl_count[max_length]--;
  20025. /* The brother of the overflow item also moves one step up,
  20026. * but this does not affect bl_count[max_length]
  20027. */
  20028. overflow -= 2;
  20029. } while (overflow > 0);
  20030. /* Now recompute all bit lengths, scanning in increasing frequency.
  20031. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  20032. * lengths instead of fixing only the wrong ones. This idea is taken
  20033. * from 'ar' written by Haruhiko Okumura.)
  20034. */
  20035. for (bits = max_length; bits !== 0; bits--) {
  20036. n = s.bl_count[bits];
  20037. while (n !== 0) {
  20038. m = s.heap[--h];
  20039. if (m > max_code) { continue; }
  20040. if (tree[m * 2 + 1]/*.Len*/ !== bits) {
  20041. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  20042. s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
  20043. tree[m * 2 + 1]/*.Len*/ = bits;
  20044. }
  20045. n--;
  20046. }
  20047. }
  20048. }
  20049. /* ===========================================================================
  20050. * Generate the codes for a given tree and bit counts (which need not be
  20051. * optimal).
  20052. * IN assertion: the array bl_count contains the bit length statistics for
  20053. * the given tree and the field len is set for all tree elements.
  20054. * OUT assertion: the field code is set for all tree elements of non
  20055. * zero code length.
  20056. */
  20057. function gen_codes(tree, max_code, bl_count)
  20058. // ct_data *tree; /* the tree to decorate */
  20059. // int max_code; /* largest code with non zero frequency */
  20060. // ushf *bl_count; /* number of codes at each bit length */
  20061. {
  20062. var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
  20063. var code = 0; /* running code value */
  20064. var bits; /* bit index */
  20065. var n; /* code index */
  20066. /* The distribution counts are first used to generate the code values
  20067. * without bit reversal.
  20068. */
  20069. for (bits = 1; bits <= MAX_BITS; bits++) {
  20070. next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  20071. }
  20072. /* Check that the bit counts in bl_count are consistent. The last code
  20073. * must be all ones.
  20074. */
  20075. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  20076. // "inconsistent bit counts");
  20077. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  20078. for (n = 0; n <= max_code; n++) {
  20079. var len = tree[n * 2 + 1]/*.Len*/;
  20080. if (len === 0) { continue; }
  20081. /* Now reverse the bits */
  20082. tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  20083. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  20084. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  20085. }
  20086. }
  20087. /* ===========================================================================
  20088. * Initialize the various 'constant' tables.
  20089. */
  20090. function tr_static_init() {
  20091. var n; /* iterates over tree elements */
  20092. var bits; /* bit counter */
  20093. var length; /* length value */
  20094. var code; /* code value */
  20095. var dist; /* distance index */
  20096. var bl_count = new Array(MAX_BITS + 1);
  20097. /* number of codes at each bit length for an optimal tree */
  20098. // do check in _tr_init()
  20099. //if (static_init_done) return;
  20100. /* For some embedded targets, global variables are not initialized: */
  20101. /*#ifdef NO_INIT_GLOBAL_POINTERS
  20102. static_l_desc.static_tree = static_ltree;
  20103. static_l_desc.extra_bits = extra_lbits;
  20104. static_d_desc.static_tree = static_dtree;
  20105. static_d_desc.extra_bits = extra_dbits;
  20106. static_bl_desc.extra_bits = extra_blbits;
  20107. #endif*/
  20108. /* Initialize the mapping length (0..255) -> length code (0..28) */
  20109. length = 0;
  20110. for (code = 0; code < LENGTH_CODES - 1; code++) {
  20111. base_length[code] = length;
  20112. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  20113. _length_code[length++] = code;
  20114. }
  20115. }
  20116. //Assert (length == 256, "tr_static_init: length != 256");
  20117. /* Note that the length 255 (match length 258) can be represented
  20118. * in two different ways: code 284 + 5 bits or code 285, so we
  20119. * overwrite length_code[255] to use the best encoding:
  20120. */
  20121. _length_code[length - 1] = code;
  20122. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  20123. dist = 0;
  20124. for (code = 0; code < 16; code++) {
  20125. base_dist[code] = dist;
  20126. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  20127. _dist_code[dist++] = code;
  20128. }
  20129. }
  20130. //Assert (dist == 256, "tr_static_init: dist != 256");
  20131. dist >>= 7; /* from now on, all distances are divided by 128 */
  20132. for (; code < D_CODES; code++) {
  20133. base_dist[code] = dist << 7;
  20134. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  20135. _dist_code[256 + dist++] = code;
  20136. }
  20137. }
  20138. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  20139. /* Construct the codes of the static literal tree */
  20140. for (bits = 0; bits <= MAX_BITS; bits++) {
  20141. bl_count[bits] = 0;
  20142. }
  20143. n = 0;
  20144. while (n <= 143) {
  20145. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  20146. n++;
  20147. bl_count[8]++;
  20148. }
  20149. while (n <= 255) {
  20150. static_ltree[n * 2 + 1]/*.Len*/ = 9;
  20151. n++;
  20152. bl_count[9]++;
  20153. }
  20154. while (n <= 279) {
  20155. static_ltree[n * 2 + 1]/*.Len*/ = 7;
  20156. n++;
  20157. bl_count[7]++;
  20158. }
  20159. while (n <= 287) {
  20160. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  20161. n++;
  20162. bl_count[8]++;
  20163. }
  20164. /* Codes 286 and 287 do not exist, but we must include them in the
  20165. * tree construction to get a canonical Huffman tree (longest code
  20166. * all ones)
  20167. */
  20168. gen_codes(static_ltree, L_CODES + 1, bl_count);
  20169. /* The static distance tree is trivial: */
  20170. for (n = 0; n < D_CODES; n++) {
  20171. static_dtree[n * 2 + 1]/*.Len*/ = 5;
  20172. static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  20173. }
  20174. // Now data ready and we can init static trees
  20175. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  20176. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  20177. static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  20178. //static_init_done = true;
  20179. }
  20180. /* ===========================================================================
  20181. * Initialize a new block.
  20182. */
  20183. function init_block(s) {
  20184. var n; /* iterates over tree elements */
  20185. /* Initialize the trees. */
  20186. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  20187. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  20188. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  20189. s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  20190. s.opt_len = s.static_len = 0;
  20191. s.last_lit = s.matches = 0;
  20192. }
  20193. /* ===========================================================================
  20194. * Flush the bit buffer and align the output on a byte boundary
  20195. */
  20196. function bi_windup(s)
  20197. {
  20198. if (s.bi_valid > 8) {
  20199. put_short(s, s.bi_buf);
  20200. } else if (s.bi_valid > 0) {
  20201. //put_byte(s, (Byte)s->bi_buf);
  20202. s.pending_buf[s.pending++] = s.bi_buf;
  20203. }
  20204. s.bi_buf = 0;
  20205. s.bi_valid = 0;
  20206. }
  20207. /* ===========================================================================
  20208. * Copy a stored block, storing first the length and its
  20209. * one's complement if requested.
  20210. */
  20211. function copy_block(s, buf, len, header)
  20212. //DeflateState *s;
  20213. //charf *buf; /* the input data */
  20214. //unsigned len; /* its length */
  20215. //int header; /* true if block header must be written */
  20216. {
  20217. bi_windup(s); /* align on byte boundary */
  20218. if (header) {
  20219. put_short(s, len);
  20220. put_short(s, ~len);
  20221. }
  20222. // while (len--) {
  20223. // put_byte(s, *buf++);
  20224. // }
  20225. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  20226. s.pending += len;
  20227. }
  20228. /* ===========================================================================
  20229. * Compares to subtrees, using the tree depth as tie breaker when
  20230. * the subtrees have equal frequency. This minimizes the worst case length.
  20231. */
  20232. function smaller(tree, n, m, depth) {
  20233. var _n2 = n * 2;
  20234. var _m2 = m * 2;
  20235. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  20236. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  20237. }
  20238. /* ===========================================================================
  20239. * Restore the heap property by moving down the tree starting at node k,
  20240. * exchanging a node with the smallest of its two sons if necessary, stopping
  20241. * when the heap property is re-established (each father smaller than its
  20242. * two sons).
  20243. */
  20244. function pqdownheap(s, tree, k)
  20245. // deflate_state *s;
  20246. // ct_data *tree; /* the tree to restore */
  20247. // int k; /* node to move down */
  20248. {
  20249. var v = s.heap[k];
  20250. var j = k << 1; /* left son of k */
  20251. while (j <= s.heap_len) {
  20252. /* Set j to the smallest of the two sons: */
  20253. if (j < s.heap_len &&
  20254. smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
  20255. j++;
  20256. }
  20257. /* Exit if v is smaller than both sons */
  20258. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  20259. /* Exchange v with the smallest son */
  20260. s.heap[k] = s.heap[j];
  20261. k = j;
  20262. /* And continue down the tree, setting j to the left son of k */
  20263. j <<= 1;
  20264. }
  20265. s.heap[k] = v;
  20266. }
  20267. // inlined manually
  20268. // var SMALLEST = 1;
  20269. /* ===========================================================================
  20270. * Send the block data compressed using the given Huffman trees
  20271. */
  20272. function compress_block(s, ltree, dtree)
  20273. // deflate_state *s;
  20274. // const ct_data *ltree; /* literal tree */
  20275. // const ct_data *dtree; /* distance tree */
  20276. {
  20277. var dist; /* distance of matched string */
  20278. var lc; /* match length or unmatched char (if dist == 0) */
  20279. var lx = 0; /* running index in l_buf */
  20280. var code; /* the code to send */
  20281. var extra; /* number of extra bits to send */
  20282. if (s.last_lit !== 0) {
  20283. do {
  20284. dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
  20285. lc = s.pending_buf[s.l_buf + lx];
  20286. lx++;
  20287. if (dist === 0) {
  20288. send_code(s, lc, ltree); /* send a literal byte */
  20289. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  20290. } else {
  20291. /* Here, lc is the match length - MIN_MATCH */
  20292. code = _length_code[lc];
  20293. send_code(s, code + LITERALS + 1, ltree); /* send the length code */
  20294. extra = extra_lbits[code];
  20295. if (extra !== 0) {
  20296. lc -= base_length[code];
  20297. send_bits(s, lc, extra); /* send the extra length bits */
  20298. }
  20299. dist--; /* dist is now the match distance - 1 */
  20300. code = d_code(dist);
  20301. //Assert (code < D_CODES, "bad d_code");
  20302. send_code(s, code, dtree); /* send the distance code */
  20303. extra = extra_dbits[code];
  20304. if (extra !== 0) {
  20305. dist -= base_dist[code];
  20306. send_bits(s, dist, extra); /* send the extra distance bits */
  20307. }
  20308. } /* literal or match pair ? */
  20309. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  20310. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  20311. // "pendingBuf overflow");
  20312. } while (lx < s.last_lit);
  20313. }
  20314. send_code(s, END_BLOCK, ltree);
  20315. }
  20316. /* ===========================================================================
  20317. * Construct one Huffman tree and assigns the code bit strings and lengths.
  20318. * Update the total bit length for the current block.
  20319. * IN assertion: the field freq is set for all tree elements.
  20320. * OUT assertions: the fields len and code are set to the optimal bit length
  20321. * and corresponding code. The length opt_len is updated; static_len is
  20322. * also updated if stree is not null. The field max_code is set.
  20323. */
  20324. function build_tree(s, desc)
  20325. // deflate_state *s;
  20326. // tree_desc *desc; /* the tree descriptor */
  20327. {
  20328. var tree = desc.dyn_tree;
  20329. var stree = desc.stat_desc.static_tree;
  20330. var has_stree = desc.stat_desc.has_stree;
  20331. var elems = desc.stat_desc.elems;
  20332. var n, m; /* iterate over heap elements */
  20333. var max_code = -1; /* largest code with non zero frequency */
  20334. var node; /* new node being created */
  20335. /* Construct the initial heap, with least frequent element in
  20336. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  20337. * heap[0] is not used.
  20338. */
  20339. s.heap_len = 0;
  20340. s.heap_max = HEAP_SIZE;
  20341. for (n = 0; n < elems; n++) {
  20342. if (tree[n * 2]/*.Freq*/ !== 0) {
  20343. s.heap[++s.heap_len] = max_code = n;
  20344. s.depth[n] = 0;
  20345. } else {
  20346. tree[n * 2 + 1]/*.Len*/ = 0;
  20347. }
  20348. }
  20349. /* The pkzip format requires that at least one distance code exists,
  20350. * and that at least one bit should be sent even if there is only one
  20351. * possible code. So to avoid special checks later on we force at least
  20352. * two codes of non zero frequency.
  20353. */
  20354. while (s.heap_len < 2) {
  20355. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  20356. tree[node * 2]/*.Freq*/ = 1;
  20357. s.depth[node] = 0;
  20358. s.opt_len--;
  20359. if (has_stree) {
  20360. s.static_len -= stree[node * 2 + 1]/*.Len*/;
  20361. }
  20362. /* node is 0 or 1 so it does not have extra bits */
  20363. }
  20364. desc.max_code = max_code;
  20365. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  20366. * establish sub-heaps of increasing lengths:
  20367. */
  20368. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  20369. /* Construct the Huffman tree by repeatedly combining the least two
  20370. * frequent nodes.
  20371. */
  20372. node = elems; /* next internal node of the tree */
  20373. do {
  20374. //pqremove(s, tree, n); /* n = node of least frequency */
  20375. /*** pqremove ***/
  20376. n = s.heap[1/*SMALLEST*/];
  20377. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  20378. pqdownheap(s, tree, 1/*SMALLEST*/);
  20379. /***/
  20380. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  20381. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  20382. s.heap[--s.heap_max] = m;
  20383. /* Create a new node father of n and m */
  20384. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  20385. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  20386. tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  20387. /* and insert the new node in the heap */
  20388. s.heap[1/*SMALLEST*/] = node++;
  20389. pqdownheap(s, tree, 1/*SMALLEST*/);
  20390. } while (s.heap_len >= 2);
  20391. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  20392. /* At this point, the fields freq and dad are set. We can now
  20393. * generate the bit lengths.
  20394. */
  20395. gen_bitlen(s, desc);
  20396. /* The field len is now set, we can generate the bit codes */
  20397. gen_codes(tree, max_code, s.bl_count);
  20398. }
  20399. /* ===========================================================================
  20400. * Scan a literal or distance tree to determine the frequencies of the codes
  20401. * in the bit length tree.
  20402. */
  20403. function scan_tree(s, tree, max_code)
  20404. // deflate_state *s;
  20405. // ct_data *tree; /* the tree to be scanned */
  20406. // int max_code; /* and its largest code of non zero frequency */
  20407. {
  20408. var n; /* iterates over all tree elements */
  20409. var prevlen = -1; /* last emitted length */
  20410. var curlen; /* length of current code */
  20411. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  20412. var count = 0; /* repeat count of the current code */
  20413. var max_count = 7; /* max repeat count */
  20414. var min_count = 4; /* min repeat count */
  20415. if (nextlen === 0) {
  20416. max_count = 138;
  20417. min_count = 3;
  20418. }
  20419. tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  20420. for (n = 0; n <= max_code; n++) {
  20421. curlen = nextlen;
  20422. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  20423. if (++count < max_count && curlen === nextlen) {
  20424. continue;
  20425. } else if (count < min_count) {
  20426. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  20427. } else if (curlen !== 0) {
  20428. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  20429. s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  20430. } else if (count <= 10) {
  20431. s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  20432. } else {
  20433. s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
  20434. }
  20435. count = 0;
  20436. prevlen = curlen;
  20437. if (nextlen === 0) {
  20438. max_count = 138;
  20439. min_count = 3;
  20440. } else if (curlen === nextlen) {
  20441. max_count = 6;
  20442. min_count = 3;
  20443. } else {
  20444. max_count = 7;
  20445. min_count = 4;
  20446. }
  20447. }
  20448. }
  20449. /* ===========================================================================
  20450. * Send a literal or distance tree in compressed form, using the codes in
  20451. * bl_tree.
  20452. */
  20453. function send_tree(s, tree, max_code)
  20454. // deflate_state *s;
  20455. // ct_data *tree; /* the tree to be scanned */
  20456. // int max_code; /* and its largest code of non zero frequency */
  20457. {
  20458. var n; /* iterates over all tree elements */
  20459. var prevlen = -1; /* last emitted length */
  20460. var curlen; /* length of current code */
  20461. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  20462. var count = 0; /* repeat count of the current code */
  20463. var max_count = 7; /* max repeat count */
  20464. var min_count = 4; /* min repeat count */
  20465. /* tree[max_code+1].Len = -1; */ /* guard already set */
  20466. if (nextlen === 0) {
  20467. max_count = 138;
  20468. min_count = 3;
  20469. }
  20470. for (n = 0; n <= max_code; n++) {
  20471. curlen = nextlen;
  20472. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  20473. if (++count < max_count && curlen === nextlen) {
  20474. continue;
  20475. } else if (count < min_count) {
  20476. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  20477. } else if (curlen !== 0) {
  20478. if (curlen !== prevlen) {
  20479. send_code(s, curlen, s.bl_tree);
  20480. count--;
  20481. }
  20482. //Assert(count >= 3 && count <= 6, " 3_6?");
  20483. send_code(s, REP_3_6, s.bl_tree);
  20484. send_bits(s, count - 3, 2);
  20485. } else if (count <= 10) {
  20486. send_code(s, REPZ_3_10, s.bl_tree);
  20487. send_bits(s, count - 3, 3);
  20488. } else {
  20489. send_code(s, REPZ_11_138, s.bl_tree);
  20490. send_bits(s, count - 11, 7);
  20491. }
  20492. count = 0;
  20493. prevlen = curlen;
  20494. if (nextlen === 0) {
  20495. max_count = 138;
  20496. min_count = 3;
  20497. } else if (curlen === nextlen) {
  20498. max_count = 6;
  20499. min_count = 3;
  20500. } else {
  20501. max_count = 7;
  20502. min_count = 4;
  20503. }
  20504. }
  20505. }
  20506. /* ===========================================================================
  20507. * Construct the Huffman tree for the bit lengths and return the index in
  20508. * bl_order of the last bit length code to send.
  20509. */
  20510. function build_bl_tree(s) {
  20511. var max_blindex; /* index of last bit length code of non zero freq */
  20512. /* Determine the bit length frequencies for literal and distance trees */
  20513. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  20514. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  20515. /* Build the bit length tree: */
  20516. build_tree(s, s.bl_desc);
  20517. /* opt_len now includes the length of the tree representations, except
  20518. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  20519. */
  20520. /* Determine the number of bit length codes to send. The pkzip format
  20521. * requires that at least 4 bit length codes be sent. (appnote.txt says
  20522. * 3 but the actual value used is 4.)
  20523. */
  20524. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  20525. if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
  20526. break;
  20527. }
  20528. }
  20529. /* Update opt_len to include the bit length tree and counts */
  20530. s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  20531. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  20532. // s->opt_len, s->static_len));
  20533. return max_blindex;
  20534. }
  20535. /* ===========================================================================
  20536. * Send the header for a block using dynamic Huffman trees: the counts, the
  20537. * lengths of the bit length codes, the literal tree and the distance tree.
  20538. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  20539. */
  20540. function send_all_trees(s, lcodes, dcodes, blcodes)
  20541. // deflate_state *s;
  20542. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  20543. {
  20544. var rank; /* index in bl_order */
  20545. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  20546. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  20547. // "too many codes");
  20548. //Tracev((stderr, "\nbl counts: "));
  20549. send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  20550. send_bits(s, dcodes - 1, 5);
  20551. send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  20552. for (rank = 0; rank < blcodes; rank++) {
  20553. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  20554. send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  20555. }
  20556. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  20557. send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  20558. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  20559. send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  20560. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  20561. }
  20562. /* ===========================================================================
  20563. * Check if the data type is TEXT or BINARY, using the following algorithm:
  20564. * - TEXT if the two conditions below are satisfied:
  20565. * a) There are no non-portable control characters belonging to the
  20566. * "black list" (0..6, 14..25, 28..31).
  20567. * b) There is at least one printable character belonging to the
  20568. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  20569. * - BINARY otherwise.
  20570. * - The following partially-portable control characters form a
  20571. * "gray list" that is ignored in this detection algorithm:
  20572. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  20573. * IN assertion: the fields Freq of dyn_ltree are set.
  20574. */
  20575. function detect_data_type(s) {
  20576. /* black_mask is the bit mask of black-listed bytes
  20577. * set bits 0..6, 14..25, and 28..31
  20578. * 0xf3ffc07f = binary 11110011111111111100000001111111
  20579. */
  20580. var black_mask = 0xf3ffc07f;
  20581. var n;
  20582. /* Check for non-textual ("black-listed") bytes. */
  20583. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  20584. if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
  20585. return Z_BINARY;
  20586. }
  20587. }
  20588. /* Check for textual ("white-listed") bytes. */
  20589. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  20590. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  20591. return Z_TEXT;
  20592. }
  20593. for (n = 32; n < LITERALS; n++) {
  20594. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  20595. return Z_TEXT;
  20596. }
  20597. }
  20598. /* There are no "black-listed" or "white-listed" bytes:
  20599. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  20600. */
  20601. return Z_BINARY;
  20602. }
  20603. var static_init_done = false;
  20604. /* ===========================================================================
  20605. * Initialize the tree data structures for a new zlib stream.
  20606. */
  20607. function _tr_init(s)
  20608. {
  20609. if (!static_init_done) {
  20610. tr_static_init();
  20611. static_init_done = true;
  20612. }
  20613. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  20614. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  20615. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  20616. s.bi_buf = 0;
  20617. s.bi_valid = 0;
  20618. /* Initialize the first block of the first file: */
  20619. init_block(s);
  20620. }
  20621. /* ===========================================================================
  20622. * Send a stored block
  20623. */
  20624. function _tr_stored_block(s, buf, stored_len, last)
  20625. //DeflateState *s;
  20626. //charf *buf; /* input block */
  20627. //ulg stored_len; /* length of input block */
  20628. //int last; /* one if this is the last block for a file */
  20629. {
  20630. send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
  20631. copy_block(s, buf, stored_len, true); /* with header */
  20632. }
  20633. /* ===========================================================================
  20634. * Send one empty static block to give enough lookahead for inflate.
  20635. * This takes 10 bits, of which 7 may remain in the bit buffer.
  20636. */
  20637. function _tr_align(s) {
  20638. send_bits(s, STATIC_TREES << 1, 3);
  20639. send_code(s, END_BLOCK, static_ltree);
  20640. bi_flush(s);
  20641. }
  20642. /* ===========================================================================
  20643. * Determine the best encoding for the current block: dynamic trees, static
  20644. * trees or store, and output the encoded block to the zip file.
  20645. */
  20646. function _tr_flush_block(s, buf, stored_len, last)
  20647. //DeflateState *s;
  20648. //charf *buf; /* input block, or NULL if too old */
  20649. //ulg stored_len; /* length of input block */
  20650. //int last; /* one if this is the last block for a file */
  20651. {
  20652. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  20653. var max_blindex = 0; /* index of last bit length code of non zero freq */
  20654. /* Build the Huffman trees unless a stored block is forced */
  20655. if (s.level > 0) {
  20656. /* Check if the file is binary or text */
  20657. if (s.strm.data_type === Z_UNKNOWN) {
  20658. s.strm.data_type = detect_data_type(s);
  20659. }
  20660. /* Construct the literal and distance trees */
  20661. build_tree(s, s.l_desc);
  20662. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  20663. // s->static_len));
  20664. build_tree(s, s.d_desc);
  20665. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  20666. // s->static_len));
  20667. /* At this point, opt_len and static_len are the total bit lengths of
  20668. * the compressed block data, excluding the tree representations.
  20669. */
  20670. /* Build the bit length tree for the above two trees, and get the index
  20671. * in bl_order of the last bit length code to send.
  20672. */
  20673. max_blindex = build_bl_tree(s);
  20674. /* Determine the best encoding. Compute the block lengths in bytes. */
  20675. opt_lenb = (s.opt_len + 3 + 7) >>> 3;
  20676. static_lenb = (s.static_len + 3 + 7) >>> 3;
  20677. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  20678. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  20679. // s->last_lit));
  20680. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  20681. } else {
  20682. // Assert(buf != (char*)0, "lost buf");
  20683. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  20684. }
  20685. if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
  20686. /* 4: two words for the lengths */
  20687. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  20688. * Otherwise we can't have processed more than WSIZE input bytes since
  20689. * the last block flush, because compression would have been
  20690. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  20691. * transform a block into a stored block.
  20692. */
  20693. _tr_stored_block(s, buf, stored_len, last);
  20694. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  20695. send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
  20696. compress_block(s, static_ltree, static_dtree);
  20697. } else {
  20698. send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
  20699. send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
  20700. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  20701. }
  20702. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  20703. /* The above check is made mod 2^32, for files larger than 512 MB
  20704. * and uLong implemented on 32 bits.
  20705. */
  20706. init_block(s);
  20707. if (last) {
  20708. bi_windup(s);
  20709. }
  20710. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  20711. // s->compressed_len-7*last));
  20712. }
  20713. /* ===========================================================================
  20714. * Save the match info and tally the frequency counts. Return true if
  20715. * the current block must be flushed.
  20716. */
  20717. function _tr_tally(s, dist, lc)
  20718. // deflate_state *s;
  20719. // unsigned dist; /* distance of matched string */
  20720. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  20721. {
  20722. //var out_length, in_length, dcode;
  20723. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  20724. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  20725. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  20726. s.last_lit++;
  20727. if (dist === 0) {
  20728. /* lc is the unmatched char */
  20729. s.dyn_ltree[lc * 2]/*.Freq*/++;
  20730. } else {
  20731. s.matches++;
  20732. /* Here, lc is the match length - MIN_MATCH */
  20733. dist--; /* dist = match distance - 1 */
  20734. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  20735. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  20736. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  20737. s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
  20738. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  20739. }
  20740. // (!) This block is disabled in zlib defaults,
  20741. // don't enable it for binary compatibility
  20742. //#ifdef TRUNCATE_BLOCK
  20743. // /* Try to guess if it is profitable to stop the current block here */
  20744. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  20745. // /* Compute an upper bound for the compressed length */
  20746. // out_length = s.last_lit*8;
  20747. // in_length = s.strstart - s.block_start;
  20748. //
  20749. // for (dcode = 0; dcode < D_CODES; dcode++) {
  20750. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  20751. // }
  20752. // out_length >>>= 3;
  20753. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  20754. // // s->last_lit, in_length, out_length,
  20755. // // 100L - out_length*100L/in_length));
  20756. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  20757. // return true;
  20758. // }
  20759. // }
  20760. //#endif
  20761. return (s.last_lit === s.lit_bufsize - 1);
  20762. /* We avoid equality with lit_bufsize because of wraparound at 64K
  20763. * on 16 bit machines and because stored blocks are restricted to
  20764. * 64K-1 bytes.
  20765. */
  20766. }
  20767. exports._tr_init = _tr_init;
  20768. exports._tr_stored_block = _tr_stored_block;
  20769. exports._tr_flush_block = _tr_flush_block;
  20770. exports._tr_tally = _tr_tally;
  20771. exports._tr_align = _tr_align;
  20772. },{"../utils/common":112}],122:[function(require,module,exports){
  20773. 'use strict';
  20774. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  20775. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  20776. //
  20777. // This software is provided 'as-is', without any express or implied
  20778. // warranty. In no event will the authors be held liable for any damages
  20779. // arising from the use of this software.
  20780. //
  20781. // Permission is granted to anyone to use this software for any purpose,
  20782. // including commercial applications, and to alter it and redistribute it
  20783. // freely, subject to the following restrictions:
  20784. //
  20785. // 1. The origin of this software must not be misrepresented; you must not
  20786. // claim that you wrote the original software. If you use this software
  20787. // in a product, an acknowledgment in the product documentation would be
  20788. // appreciated but is not required.
  20789. // 2. Altered source versions must be plainly marked as such, and must not be
  20790. // misrepresented as being the original software.
  20791. // 3. This notice may not be removed or altered from any source distribution.
  20792. function ZStream() {
  20793. /* next input byte */
  20794. this.input = null; // JS specific, because we have no pointers
  20795. this.next_in = 0;
  20796. /* number of bytes available at input */
  20797. this.avail_in = 0;
  20798. /* total number of input bytes read so far */
  20799. this.total_in = 0;
  20800. /* next output byte should be put there */
  20801. this.output = null; // JS specific, because we have no pointers
  20802. this.next_out = 0;
  20803. /* remaining free space at output */
  20804. this.avail_out = 0;
  20805. /* total number of bytes output so far */
  20806. this.total_out = 0;
  20807. /* last error message, NULL if no error */
  20808. this.msg = ''/*Z_NULL*/;
  20809. /* not visible by applications */
  20810. this.state = null;
  20811. /* best guess about the data type: binary or text */
  20812. this.data_type = 2/*Z_UNKNOWN*/;
  20813. /* adler32 value of the uncompressed data */
  20814. this.adler = 0;
  20815. }
  20816. module.exports = ZStream;
  20817. },{}],123:[function(require,module,exports){
  20818. module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb",
  20819. "2.16.840.1.101.3.4.1.2": "aes-128-cbc",
  20820. "2.16.840.1.101.3.4.1.3": "aes-128-ofb",
  20821. "2.16.840.1.101.3.4.1.4": "aes-128-cfb",
  20822. "2.16.840.1.101.3.4.1.21": "aes-192-ecb",
  20823. "2.16.840.1.101.3.4.1.22": "aes-192-cbc",
  20824. "2.16.840.1.101.3.4.1.23": "aes-192-ofb",
  20825. "2.16.840.1.101.3.4.1.24": "aes-192-cfb",
  20826. "2.16.840.1.101.3.4.1.41": "aes-256-ecb",
  20827. "2.16.840.1.101.3.4.1.42": "aes-256-cbc",
  20828. "2.16.840.1.101.3.4.1.43": "aes-256-ofb",
  20829. "2.16.840.1.101.3.4.1.44": "aes-256-cfb"
  20830. }
  20831. },{}],124:[function(require,module,exports){
  20832. // from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js
  20833. // Fedor, you are amazing.
  20834. 'use strict'
  20835. var asn1 = require('asn1.js')
  20836. exports.certificate = require('./certificate')
  20837. var RSAPrivateKey = asn1.define('RSAPrivateKey', function () {
  20838. this.seq().obj(
  20839. this.key('version').int(),
  20840. this.key('modulus').int(),
  20841. this.key('publicExponent').int(),
  20842. this.key('privateExponent').int(),
  20843. this.key('prime1').int(),
  20844. this.key('prime2').int(),
  20845. this.key('exponent1').int(),
  20846. this.key('exponent2').int(),
  20847. this.key('coefficient').int()
  20848. )
  20849. })
  20850. exports.RSAPrivateKey = RSAPrivateKey
  20851. var RSAPublicKey = asn1.define('RSAPublicKey', function () {
  20852. this.seq().obj(
  20853. this.key('modulus').int(),
  20854. this.key('publicExponent').int()
  20855. )
  20856. })
  20857. exports.RSAPublicKey = RSAPublicKey
  20858. var PublicKey = asn1.define('SubjectPublicKeyInfo', function () {
  20859. this.seq().obj(
  20860. this.key('algorithm').use(AlgorithmIdentifier),
  20861. this.key('subjectPublicKey').bitstr()
  20862. )
  20863. })
  20864. exports.PublicKey = PublicKey
  20865. var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () {
  20866. this.seq().obj(
  20867. this.key('algorithm').objid(),
  20868. this.key('none').null_().optional(),
  20869. this.key('curve').objid().optional(),
  20870. this.key('params').seq().obj(
  20871. this.key('p').int(),
  20872. this.key('q').int(),
  20873. this.key('g').int()
  20874. ).optional()
  20875. )
  20876. })
  20877. var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () {
  20878. this.seq().obj(
  20879. this.key('version').int(),
  20880. this.key('algorithm').use(AlgorithmIdentifier),
  20881. this.key('subjectPrivateKey').octstr()
  20882. )
  20883. })
  20884. exports.PrivateKey = PrivateKeyInfo
  20885. var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () {
  20886. this.seq().obj(
  20887. this.key('algorithm').seq().obj(
  20888. this.key('id').objid(),
  20889. this.key('decrypt').seq().obj(
  20890. this.key('kde').seq().obj(
  20891. this.key('id').objid(),
  20892. this.key('kdeparams').seq().obj(
  20893. this.key('salt').octstr(),
  20894. this.key('iters').int()
  20895. )
  20896. ),
  20897. this.key('cipher').seq().obj(
  20898. this.key('algo').objid(),
  20899. this.key('iv').octstr()
  20900. )
  20901. )
  20902. ),
  20903. this.key('subjectPrivateKey').octstr()
  20904. )
  20905. })
  20906. exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo
  20907. var DSAPrivateKey = asn1.define('DSAPrivateKey', function () {
  20908. this.seq().obj(
  20909. this.key('version').int(),
  20910. this.key('p').int(),
  20911. this.key('q').int(),
  20912. this.key('g').int(),
  20913. this.key('pub_key').int(),
  20914. this.key('priv_key').int()
  20915. )
  20916. })
  20917. exports.DSAPrivateKey = DSAPrivateKey
  20918. exports.DSAparam = asn1.define('DSAparam', function () {
  20919. this.int()
  20920. })
  20921. var ECPrivateKey = asn1.define('ECPrivateKey', function () {
  20922. this.seq().obj(
  20923. this.key('version').int(),
  20924. this.key('privateKey').octstr(),
  20925. this.key('parameters').optional().explicit(0).use(ECParameters),
  20926. this.key('publicKey').optional().explicit(1).bitstr()
  20927. )
  20928. })
  20929. exports.ECPrivateKey = ECPrivateKey
  20930. var ECParameters = asn1.define('ECParameters', function () {
  20931. this.choice({
  20932. namedCurve: this.objid()
  20933. })
  20934. })
  20935. exports.signature = asn1.define('signature', function () {
  20936. this.seq().obj(
  20937. this.key('r').int(),
  20938. this.key('s').int()
  20939. )
  20940. })
  20941. },{"./certificate":125,"asn1.js":1}],125:[function(require,module,exports){
  20942. // from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js
  20943. // thanks to @Rantanen
  20944. 'use strict'
  20945. var asn = require('asn1.js')
  20946. var Time = asn.define('Time', function () {
  20947. this.choice({
  20948. utcTime: this.utctime(),
  20949. generalTime: this.gentime()
  20950. })
  20951. })
  20952. var AttributeTypeValue = asn.define('AttributeTypeValue', function () {
  20953. this.seq().obj(
  20954. this.key('type').objid(),
  20955. this.key('value').any()
  20956. )
  20957. })
  20958. var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () {
  20959. this.seq().obj(
  20960. this.key('algorithm').objid(),
  20961. this.key('parameters').optional()
  20962. )
  20963. })
  20964. var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () {
  20965. this.seq().obj(
  20966. this.key('algorithm').use(AlgorithmIdentifier),
  20967. this.key('subjectPublicKey').bitstr()
  20968. )
  20969. })
  20970. var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () {
  20971. this.setof(AttributeTypeValue)
  20972. })
  20973. var RDNSequence = asn.define('RDNSequence', function () {
  20974. this.seqof(RelativeDistinguishedName)
  20975. })
  20976. var Name = asn.define('Name', function () {
  20977. this.choice({
  20978. rdnSequence: this.use(RDNSequence)
  20979. })
  20980. })
  20981. var Validity = asn.define('Validity', function () {
  20982. this.seq().obj(
  20983. this.key('notBefore').use(Time),
  20984. this.key('notAfter').use(Time)
  20985. )
  20986. })
  20987. var Extension = asn.define('Extension', function () {
  20988. this.seq().obj(
  20989. this.key('extnID').objid(),
  20990. this.key('critical').bool().def(false),
  20991. this.key('extnValue').octstr()
  20992. )
  20993. })
  20994. var TBSCertificate = asn.define('TBSCertificate', function () {
  20995. this.seq().obj(
  20996. this.key('version').explicit(0).int(),
  20997. this.key('serialNumber').int(),
  20998. this.key('signature').use(AlgorithmIdentifier),
  20999. this.key('issuer').use(Name),
  21000. this.key('validity').use(Validity),
  21001. this.key('subject').use(Name),
  21002. this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo),
  21003. this.key('issuerUniqueID').implicit(1).bitstr().optional(),
  21004. this.key('subjectUniqueID').implicit(2).bitstr().optional(),
  21005. this.key('extensions').explicit(3).seqof(Extension).optional()
  21006. )
  21007. })
  21008. var X509Certificate = asn.define('X509Certificate', function () {
  21009. this.seq().obj(
  21010. this.key('tbsCertificate').use(TBSCertificate),
  21011. this.key('signatureAlgorithm').use(AlgorithmIdentifier),
  21012. this.key('signatureValue').bitstr()
  21013. )
  21014. })
  21015. module.exports = X509Certificate
  21016. },{"asn1.js":1}],126:[function(require,module,exports){
  21017. (function (Buffer){
  21018. // adapted from https://github.com/apatil/pemstrip
  21019. var findProc = /Proc-Type: 4,ENCRYPTED\n\r?DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)\n\r?\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?/m
  21020. var startRegex = /^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n/m
  21021. var fullRegex = /^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?-----END \1-----$/m
  21022. var evp = require('evp_bytestokey')
  21023. var ciphers = require('browserify-aes')
  21024. module.exports = function (okey, password) {
  21025. var key = okey.toString()
  21026. var match = key.match(findProc)
  21027. var decrypted
  21028. if (!match) {
  21029. var match2 = key.match(fullRegex)
  21030. decrypted = new Buffer(match2[2].replace(/\r?\n/g, ''), 'base64')
  21031. } else {
  21032. var suite = 'aes' + match[1]
  21033. var iv = new Buffer(match[2], 'hex')
  21034. var cipherText = new Buffer(match[3].replace(/\r?\n/g, ''), 'base64')
  21035. var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key
  21036. var out = []
  21037. var cipher = ciphers.createDecipheriv(suite, cipherKey, iv)
  21038. out.push(cipher.update(cipherText))
  21039. out.push(cipher.final())
  21040. decrypted = Buffer.concat(out)
  21041. }
  21042. var tag = key.match(startRegex)[1]
  21043. return {
  21044. tag: tag,
  21045. data: decrypted
  21046. }
  21047. }
  21048. }).call(this,require("buffer").Buffer)
  21049. },{"browserify-aes":22,"buffer":50,"evp_bytestokey":87}],127:[function(require,module,exports){
  21050. (function (Buffer){
  21051. var asn1 = require('./asn1')
  21052. var aesid = require('./aesid.json')
  21053. var fixProc = require('./fixProc')
  21054. var ciphers = require('browserify-aes')
  21055. var compat = require('pbkdf2')
  21056. module.exports = parseKeys
  21057. function parseKeys (buffer) {
  21058. var password
  21059. if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) {
  21060. password = buffer.passphrase
  21061. buffer = buffer.key
  21062. }
  21063. if (typeof buffer === 'string') {
  21064. buffer = new Buffer(buffer)
  21065. }
  21066. var stripped = fixProc(buffer, password)
  21067. var type = stripped.tag
  21068. var data = stripped.data
  21069. var subtype, ndata
  21070. switch (type) {
  21071. case 'CERTIFICATE':
  21072. ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo
  21073. // falls through
  21074. case 'PUBLIC KEY':
  21075. if (!ndata) {
  21076. ndata = asn1.PublicKey.decode(data, 'der')
  21077. }
  21078. subtype = ndata.algorithm.algorithm.join('.')
  21079. switch (subtype) {
  21080. case '1.2.840.113549.1.1.1':
  21081. return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der')
  21082. case '1.2.840.10045.2.1':
  21083. ndata.subjectPrivateKey = ndata.subjectPublicKey
  21084. return {
  21085. type: 'ec',
  21086. data: ndata
  21087. }
  21088. case '1.2.840.10040.4.1':
  21089. ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der')
  21090. return {
  21091. type: 'dsa',
  21092. data: ndata.algorithm.params
  21093. }
  21094. default: throw new Error('unknown key id ' + subtype)
  21095. }
  21096. throw new Error('unknown key type ' + type)
  21097. case 'ENCRYPTED PRIVATE KEY':
  21098. data = asn1.EncryptedPrivateKey.decode(data, 'der')
  21099. data = decrypt(data, password)
  21100. // falls through
  21101. case 'PRIVATE KEY':
  21102. ndata = asn1.PrivateKey.decode(data, 'der')
  21103. subtype = ndata.algorithm.algorithm.join('.')
  21104. switch (subtype) {
  21105. case '1.2.840.113549.1.1.1':
  21106. return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der')
  21107. case '1.2.840.10045.2.1':
  21108. return {
  21109. curve: ndata.algorithm.curve,
  21110. privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey
  21111. }
  21112. case '1.2.840.10040.4.1':
  21113. ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der')
  21114. return {
  21115. type: 'dsa',
  21116. params: ndata.algorithm.params
  21117. }
  21118. default: throw new Error('unknown key id ' + subtype)
  21119. }
  21120. throw new Error('unknown key type ' + type)
  21121. case 'RSA PUBLIC KEY':
  21122. return asn1.RSAPublicKey.decode(data, 'der')
  21123. case 'RSA PRIVATE KEY':
  21124. return asn1.RSAPrivateKey.decode(data, 'der')
  21125. case 'DSA PRIVATE KEY':
  21126. return {
  21127. type: 'dsa',
  21128. params: asn1.DSAPrivateKey.decode(data, 'der')
  21129. }
  21130. case 'EC PRIVATE KEY':
  21131. data = asn1.ECPrivateKey.decode(data, 'der')
  21132. return {
  21133. curve: data.parameters.value,
  21134. privateKey: data.privateKey
  21135. }
  21136. default: throw new Error('unknown key type ' + type)
  21137. }
  21138. }
  21139. parseKeys.signature = asn1.signature
  21140. function decrypt (data, password) {
  21141. var salt = data.algorithm.decrypt.kde.kdeparams.salt
  21142. var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10)
  21143. var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')]
  21144. var iv = data.algorithm.decrypt.cipher.iv
  21145. var cipherText = data.subjectPrivateKey
  21146. var keylen = parseInt(algo.split('-')[1], 10) / 8
  21147. var key = compat.pbkdf2Sync(password, salt, iters, keylen)
  21148. var cipher = ciphers.createDecipheriv(algo, key, iv)
  21149. var out = []
  21150. out.push(cipher.update(cipherText))
  21151. out.push(cipher.final())
  21152. return Buffer.concat(out)
  21153. }
  21154. }).call(this,require("buffer").Buffer)
  21155. },{"./aesid.json":123,"./asn1":124,"./fixProc":126,"browserify-aes":22,"buffer":50,"pbkdf2":128}],128:[function(require,module,exports){
  21156. exports.pbkdf2 = require('./lib/async')
  21157. exports.pbkdf2Sync = require('./lib/sync')
  21158. },{"./lib/async":129,"./lib/sync":132}],129:[function(require,module,exports){
  21159. (function (process,global){
  21160. var checkParameters = require('./precondition')
  21161. var defaultEncoding = require('./default-encoding')
  21162. var sync = require('./sync')
  21163. var Buffer = require('safe-buffer').Buffer
  21164. var ZERO_BUF
  21165. var subtle = global.crypto && global.crypto.subtle
  21166. var toBrowser = {
  21167. 'sha': 'SHA-1',
  21168. 'sha-1': 'SHA-1',
  21169. 'sha1': 'SHA-1',
  21170. 'sha256': 'SHA-256',
  21171. 'sha-256': 'SHA-256',
  21172. 'sha384': 'SHA-384',
  21173. 'sha-384': 'SHA-384',
  21174. 'sha-512': 'SHA-512',
  21175. 'sha512': 'SHA-512'
  21176. }
  21177. var checks = []
  21178. function checkNative (algo) {
  21179. if (global.process && !global.process.browser) {
  21180. return Promise.resolve(false)
  21181. }
  21182. if (!subtle || !subtle.importKey || !subtle.deriveBits) {
  21183. return Promise.resolve(false)
  21184. }
  21185. if (checks[algo] !== undefined) {
  21186. return checks[algo]
  21187. }
  21188. ZERO_BUF = ZERO_BUF || Buffer.alloc(8)
  21189. var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo)
  21190. .then(function () {
  21191. return true
  21192. }).catch(function () {
  21193. return false
  21194. })
  21195. checks[algo] = prom
  21196. return prom
  21197. }
  21198. function browserPbkdf2 (password, salt, iterations, length, algo) {
  21199. return subtle.importKey(
  21200. 'raw', password, {name: 'PBKDF2'}, false, ['deriveBits']
  21201. ).then(function (key) {
  21202. return subtle.deriveBits({
  21203. name: 'PBKDF2',
  21204. salt: salt,
  21205. iterations: iterations,
  21206. hash: {
  21207. name: algo
  21208. }
  21209. }, key, length << 3)
  21210. }).then(function (res) {
  21211. return Buffer.from(res)
  21212. })
  21213. }
  21214. function resolvePromise (promise, callback) {
  21215. promise.then(function (out) {
  21216. process.nextTick(function () {
  21217. callback(null, out)
  21218. })
  21219. }, function (e) {
  21220. process.nextTick(function () {
  21221. callback(e)
  21222. })
  21223. })
  21224. }
  21225. module.exports = function (password, salt, iterations, keylen, digest, callback) {
  21226. if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding)
  21227. if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding)
  21228. checkParameters(iterations, keylen)
  21229. if (typeof digest === 'function') {
  21230. callback = digest
  21231. digest = undefined
  21232. }
  21233. if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2')
  21234. digest = digest || 'sha1'
  21235. var algo = toBrowser[digest.toLowerCase()]
  21236. if (!algo || typeof global.Promise !== 'function') {
  21237. return process.nextTick(function () {
  21238. var out
  21239. try {
  21240. out = sync(password, salt, iterations, keylen, digest)
  21241. } catch (e) {
  21242. return callback(e)
  21243. }
  21244. callback(null, out)
  21245. })
  21246. }
  21247. resolvePromise(checkNative(algo).then(function (resp) {
  21248. if (resp) {
  21249. return browserPbkdf2(password, salt, iterations, keylen, algo)
  21250. } else {
  21251. return sync(password, salt, iterations, keylen, digest)
  21252. }
  21253. }), callback)
  21254. }
  21255. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  21256. },{"./default-encoding":130,"./precondition":131,"./sync":132,"_process":134,"safe-buffer":157}],130:[function(require,module,exports){
  21257. (function (process){
  21258. var defaultEncoding
  21259. /* istanbul ignore next */
  21260. if (process.browser) {
  21261. defaultEncoding = 'utf-8'
  21262. } else {
  21263. var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10)
  21264. defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary'
  21265. }
  21266. module.exports = defaultEncoding
  21267. }).call(this,require('_process'))
  21268. },{"_process":134}],131:[function(require,module,exports){
  21269. var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs
  21270. module.exports = function (iterations, keylen) {
  21271. if (typeof iterations !== 'number') {
  21272. throw new TypeError('Iterations not a number')
  21273. }
  21274. if (iterations < 0) {
  21275. throw new TypeError('Bad iterations')
  21276. }
  21277. if (typeof keylen !== 'number') {
  21278. throw new TypeError('Key length not a number')
  21279. }
  21280. if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */
  21281. throw new TypeError('Bad key length')
  21282. }
  21283. }
  21284. },{}],132:[function(require,module,exports){
  21285. var md5 = require('create-hash/md5')
  21286. var rmd160 = require('ripemd160')
  21287. var sha = require('sha.js')
  21288. var checkParameters = require('./precondition')
  21289. var defaultEncoding = require('./default-encoding')
  21290. var Buffer = require('safe-buffer').Buffer
  21291. var ZEROS = Buffer.alloc(128)
  21292. var sizes = {
  21293. md5: 16,
  21294. sha1: 20,
  21295. sha224: 28,
  21296. sha256: 32,
  21297. sha384: 48,
  21298. sha512: 64,
  21299. rmd160: 20,
  21300. ripemd160: 20
  21301. }
  21302. function Hmac (alg, key, saltLen) {
  21303. var hash = getDigest(alg)
  21304. var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
  21305. if (key.length > blocksize) {
  21306. key = hash(key)
  21307. } else if (key.length < blocksize) {
  21308. key = Buffer.concat([key, ZEROS], blocksize)
  21309. }
  21310. var ipad = Buffer.allocUnsafe(blocksize + sizes[alg])
  21311. var opad = Buffer.allocUnsafe(blocksize + sizes[alg])
  21312. for (var i = 0; i < blocksize; i++) {
  21313. ipad[i] = key[i] ^ 0x36
  21314. opad[i] = key[i] ^ 0x5C
  21315. }
  21316. var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4)
  21317. ipad.copy(ipad1, 0, 0, blocksize)
  21318. this.ipad1 = ipad1
  21319. this.ipad2 = ipad
  21320. this.opad = opad
  21321. this.alg = alg
  21322. this.blocksize = blocksize
  21323. this.hash = hash
  21324. this.size = sizes[alg]
  21325. }
  21326. Hmac.prototype.run = function (data, ipad) {
  21327. data.copy(ipad, this.blocksize)
  21328. var h = this.hash(ipad)
  21329. h.copy(this.opad, this.blocksize)
  21330. return this.hash(this.opad)
  21331. }
  21332. function getDigest (alg) {
  21333. function shaFunc (data) {
  21334. return sha(alg).update(data).digest()
  21335. }
  21336. if (alg === 'rmd160' || alg === 'ripemd160') return rmd160
  21337. if (alg === 'md5') return md5
  21338. return shaFunc
  21339. }
  21340. function pbkdf2 (password, salt, iterations, keylen, digest) {
  21341. if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding)
  21342. if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding)
  21343. checkParameters(iterations, keylen)
  21344. digest = digest || 'sha1'
  21345. var hmac = new Hmac(digest, password, salt.length)
  21346. var DK = Buffer.allocUnsafe(keylen)
  21347. var block1 = Buffer.allocUnsafe(salt.length + 4)
  21348. salt.copy(block1, 0, 0, salt.length)
  21349. var destPos = 0
  21350. var hLen = sizes[digest]
  21351. var l = Math.ceil(keylen / hLen)
  21352. for (var i = 1; i <= l; i++) {
  21353. block1.writeUInt32BE(i, salt.length)
  21354. var T = hmac.run(block1, hmac.ipad1)
  21355. var U = T
  21356. for (var j = 1; j < iterations; j++) {
  21357. U = hmac.run(U, hmac.ipad2)
  21358. for (var k = 0; k < hLen; k++) T[k] ^= U[k]
  21359. }
  21360. T.copy(DK, destPos)
  21361. destPos += hLen
  21362. }
  21363. return DK
  21364. }
  21365. module.exports = pbkdf2
  21366. },{"./default-encoding":130,"./precondition":131,"create-hash/md5":56,"ripemd160":156,"safe-buffer":157,"sha.js":159}],133:[function(require,module,exports){
  21367. (function (process){
  21368. 'use strict';
  21369. if (!process.version ||
  21370. process.version.indexOf('v0.') === 0 ||
  21371. process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  21372. module.exports = nextTick;
  21373. } else {
  21374. module.exports = process.nextTick;
  21375. }
  21376. function nextTick(fn, arg1, arg2, arg3) {
  21377. if (typeof fn !== 'function') {
  21378. throw new TypeError('"callback" argument must be a function');
  21379. }
  21380. var len = arguments.length;
  21381. var args, i;
  21382. switch (len) {
  21383. case 0:
  21384. case 1:
  21385. return process.nextTick(fn);
  21386. case 2:
  21387. return process.nextTick(function afterTickOne() {
  21388. fn.call(null, arg1);
  21389. });
  21390. case 3:
  21391. return process.nextTick(function afterTickTwo() {
  21392. fn.call(null, arg1, arg2);
  21393. });
  21394. case 4:
  21395. return process.nextTick(function afterTickThree() {
  21396. fn.call(null, arg1, arg2, arg3);
  21397. });
  21398. default:
  21399. args = new Array(len - 1);
  21400. i = 0;
  21401. while (i < args.length) {
  21402. args[i++] = arguments[i];
  21403. }
  21404. return process.nextTick(function afterTick() {
  21405. fn.apply(null, args);
  21406. });
  21407. }
  21408. }
  21409. }).call(this,require('_process'))
  21410. },{"_process":134}],134:[function(require,module,exports){
  21411. // shim for using process in browser
  21412. var process = module.exports = {};
  21413. // cached from whatever global is present so that test runners that stub it
  21414. // don't break things. But we need to wrap it in a try catch in case it is
  21415. // wrapped in strict mode code which doesn't define any globals. It's inside a
  21416. // function because try/catches deoptimize in certain engines.
  21417. var cachedSetTimeout;
  21418. var cachedClearTimeout;
  21419. function defaultSetTimout() {
  21420. throw new Error('setTimeout has not been defined');
  21421. }
  21422. function defaultClearTimeout () {
  21423. throw new Error('clearTimeout has not been defined');
  21424. }
  21425. (function () {
  21426. try {
  21427. if (typeof setTimeout === 'function') {
  21428. cachedSetTimeout = setTimeout;
  21429. } else {
  21430. cachedSetTimeout = defaultSetTimout;
  21431. }
  21432. } catch (e) {
  21433. cachedSetTimeout = defaultSetTimout;
  21434. }
  21435. try {
  21436. if (typeof clearTimeout === 'function') {
  21437. cachedClearTimeout = clearTimeout;
  21438. } else {
  21439. cachedClearTimeout = defaultClearTimeout;
  21440. }
  21441. } catch (e) {
  21442. cachedClearTimeout = defaultClearTimeout;
  21443. }
  21444. } ())
  21445. function runTimeout(fun) {
  21446. if (cachedSetTimeout === setTimeout) {
  21447. //normal enviroments in sane situations
  21448. return setTimeout(fun, 0);
  21449. }
  21450. // if setTimeout wasn't available but was latter defined
  21451. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  21452. cachedSetTimeout = setTimeout;
  21453. return setTimeout(fun, 0);
  21454. }
  21455. try {
  21456. // when when somebody has screwed with setTimeout but no I.E. maddness
  21457. return cachedSetTimeout(fun, 0);
  21458. } catch(e){
  21459. try {
  21460. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  21461. return cachedSetTimeout.call(null, fun, 0);
  21462. } catch(e){
  21463. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  21464. return cachedSetTimeout.call(this, fun, 0);
  21465. }
  21466. }
  21467. }
  21468. function runClearTimeout(marker) {
  21469. if (cachedClearTimeout === clearTimeout) {
  21470. //normal enviroments in sane situations
  21471. return clearTimeout(marker);
  21472. }
  21473. // if clearTimeout wasn't available but was latter defined
  21474. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  21475. cachedClearTimeout = clearTimeout;
  21476. return clearTimeout(marker);
  21477. }
  21478. try {
  21479. // when when somebody has screwed with setTimeout but no I.E. maddness
  21480. return cachedClearTimeout(marker);
  21481. } catch (e){
  21482. try {
  21483. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  21484. return cachedClearTimeout.call(null, marker);
  21485. } catch (e){
  21486. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  21487. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  21488. return cachedClearTimeout.call(this, marker);
  21489. }
  21490. }
  21491. }
  21492. var queue = [];
  21493. var draining = false;
  21494. var currentQueue;
  21495. var queueIndex = -1;
  21496. function cleanUpNextTick() {
  21497. if (!draining || !currentQueue) {
  21498. return;
  21499. }
  21500. draining = false;
  21501. if (currentQueue.length) {
  21502. queue = currentQueue.concat(queue);
  21503. } else {
  21504. queueIndex = -1;
  21505. }
  21506. if (queue.length) {
  21507. drainQueue();
  21508. }
  21509. }
  21510. function drainQueue() {
  21511. if (draining) {
  21512. return;
  21513. }
  21514. var timeout = runTimeout(cleanUpNextTick);
  21515. draining = true;
  21516. var len = queue.length;
  21517. while(len) {
  21518. currentQueue = queue;
  21519. queue = [];
  21520. while (++queueIndex < len) {
  21521. if (currentQueue) {
  21522. currentQueue[queueIndex].run();
  21523. }
  21524. }
  21525. queueIndex = -1;
  21526. len = queue.length;
  21527. }
  21528. currentQueue = null;
  21529. draining = false;
  21530. runClearTimeout(timeout);
  21531. }
  21532. process.nextTick = function (fun) {
  21533. var args = new Array(arguments.length - 1);
  21534. if (arguments.length > 1) {
  21535. for (var i = 1; i < arguments.length; i++) {
  21536. args[i - 1] = arguments[i];
  21537. }
  21538. }
  21539. queue.push(new Item(fun, args));
  21540. if (queue.length === 1 && !draining) {
  21541. runTimeout(drainQueue);
  21542. }
  21543. };
  21544. // v8 likes predictible objects
  21545. function Item(fun, array) {
  21546. this.fun = fun;
  21547. this.array = array;
  21548. }
  21549. Item.prototype.run = function () {
  21550. this.fun.apply(null, this.array);
  21551. };
  21552. process.title = 'browser';
  21553. process.browser = true;
  21554. process.env = {};
  21555. process.argv = [];
  21556. process.version = ''; // empty string to avoid regexp issues
  21557. process.versions = {};
  21558. function noop() {}
  21559. process.on = noop;
  21560. process.addListener = noop;
  21561. process.once = noop;
  21562. process.off = noop;
  21563. process.removeListener = noop;
  21564. process.removeAllListeners = noop;
  21565. process.emit = noop;
  21566. process.prependListener = noop;
  21567. process.prependOnceListener = noop;
  21568. process.listeners = function (name) { return [] }
  21569. process.binding = function (name) {
  21570. throw new Error('process.binding is not supported');
  21571. };
  21572. process.cwd = function () { return '/' };
  21573. process.chdir = function (dir) {
  21574. throw new Error('process.chdir is not supported');
  21575. };
  21576. process.umask = function() { return 0; };
  21577. },{}],135:[function(require,module,exports){
  21578. exports.publicEncrypt = require('./publicEncrypt');
  21579. exports.privateDecrypt = require('./privateDecrypt');
  21580. exports.privateEncrypt = function privateEncrypt(key, buf) {
  21581. return exports.publicEncrypt(key, buf, true);
  21582. };
  21583. exports.publicDecrypt = function publicDecrypt(key, buf) {
  21584. return exports.privateDecrypt(key, buf, true);
  21585. };
  21586. },{"./privateDecrypt":137,"./publicEncrypt":138}],136:[function(require,module,exports){
  21587. (function (Buffer){
  21588. var createHash = require('create-hash');
  21589. module.exports = function (seed, len) {
  21590. var t = new Buffer('');
  21591. var i = 0, c;
  21592. while (t.length < len) {
  21593. c = i2ops(i++);
  21594. t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()]);
  21595. }
  21596. return t.slice(0, len);
  21597. };
  21598. function i2ops(c) {
  21599. var out = new Buffer(4);
  21600. out.writeUInt32BE(c,0);
  21601. return out;
  21602. }
  21603. }).call(this,require("buffer").Buffer)
  21604. },{"buffer":50,"create-hash":54}],137:[function(require,module,exports){
  21605. (function (Buffer){
  21606. var parseKeys = require('parse-asn1');
  21607. var mgf = require('./mgf');
  21608. var xor = require('./xor');
  21609. var bn = require('bn.js');
  21610. var crt = require('browserify-rsa');
  21611. var createHash = require('create-hash');
  21612. var withPublic = require('./withPublic');
  21613. module.exports = function privateDecrypt(private_key, enc, reverse) {
  21614. var padding;
  21615. if (private_key.padding) {
  21616. padding = private_key.padding;
  21617. } else if (reverse) {
  21618. padding = 1;
  21619. } else {
  21620. padding = 4;
  21621. }
  21622. var key = parseKeys(private_key);
  21623. var k = key.modulus.byteLength();
  21624. if (enc.length > k || new bn(enc).cmp(key.modulus) >= 0) {
  21625. throw new Error('decryption error');
  21626. }
  21627. var msg;
  21628. if (reverse) {
  21629. msg = withPublic(new bn(enc), key);
  21630. } else {
  21631. msg = crt(enc, key);
  21632. }
  21633. var zBuffer = new Buffer(k - msg.length);
  21634. zBuffer.fill(0);
  21635. msg = Buffer.concat([zBuffer, msg], k);
  21636. if (padding === 4) {
  21637. return oaep(key, msg);
  21638. } else if (padding === 1) {
  21639. return pkcs1(key, msg, reverse);
  21640. } else if (padding === 3) {
  21641. return msg;
  21642. } else {
  21643. throw new Error('unknown padding');
  21644. }
  21645. };
  21646. function oaep(key, msg){
  21647. var n = key.modulus;
  21648. var k = key.modulus.byteLength();
  21649. var mLen = msg.length;
  21650. var iHash = createHash('sha1').update(new Buffer('')).digest();
  21651. var hLen = iHash.length;
  21652. var hLen2 = 2 * hLen;
  21653. if (msg[0] !== 0) {
  21654. throw new Error('decryption error');
  21655. }
  21656. var maskedSeed = msg.slice(1, hLen + 1);
  21657. var maskedDb = msg.slice(hLen + 1);
  21658. var seed = xor(maskedSeed, mgf(maskedDb, hLen));
  21659. var db = xor(maskedDb, mgf(seed, k - hLen - 1));
  21660. if (compare(iHash, db.slice(0, hLen))) {
  21661. throw new Error('decryption error');
  21662. }
  21663. var i = hLen;
  21664. while (db[i] === 0) {
  21665. i++;
  21666. }
  21667. if (db[i++] !== 1) {
  21668. throw new Error('decryption error');
  21669. }
  21670. return db.slice(i);
  21671. }
  21672. function pkcs1(key, msg, reverse){
  21673. var p1 = msg.slice(0, 2);
  21674. var i = 2;
  21675. var status = 0;
  21676. while (msg[i++] !== 0) {
  21677. if (i >= msg.length) {
  21678. status++;
  21679. break;
  21680. }
  21681. }
  21682. var ps = msg.slice(2, i - 1);
  21683. var p2 = msg.slice(i - 1, i);
  21684. if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)){
  21685. status++;
  21686. }
  21687. if (ps.length < 8) {
  21688. status++;
  21689. }
  21690. if (status) {
  21691. throw new Error('decryption error');
  21692. }
  21693. return msg.slice(i);
  21694. }
  21695. function compare(a, b){
  21696. a = new Buffer(a);
  21697. b = new Buffer(b);
  21698. var dif = 0;
  21699. var len = a.length;
  21700. if (a.length !== b.length) {
  21701. dif++;
  21702. len = Math.min(a.length, b.length);
  21703. }
  21704. var i = -1;
  21705. while (++i < len) {
  21706. dif += (a[i] ^ b[i]);
  21707. }
  21708. return dif;
  21709. }
  21710. }).call(this,require("buffer").Buffer)
  21711. },{"./mgf":136,"./withPublic":139,"./xor":140,"bn.js":17,"browserify-rsa":40,"buffer":50,"create-hash":54,"parse-asn1":127}],138:[function(require,module,exports){
  21712. (function (Buffer){
  21713. var parseKeys = require('parse-asn1');
  21714. var randomBytes = require('randombytes');
  21715. var createHash = require('create-hash');
  21716. var mgf = require('./mgf');
  21717. var xor = require('./xor');
  21718. var bn = require('bn.js');
  21719. var withPublic = require('./withPublic');
  21720. var crt = require('browserify-rsa');
  21721. var constants = {
  21722. RSA_PKCS1_OAEP_PADDING: 4,
  21723. RSA_PKCS1_PADDIN: 1,
  21724. RSA_NO_PADDING: 3
  21725. };
  21726. module.exports = function publicEncrypt(public_key, msg, reverse) {
  21727. var padding;
  21728. if (public_key.padding) {
  21729. padding = public_key.padding;
  21730. } else if (reverse) {
  21731. padding = 1;
  21732. } else {
  21733. padding = 4;
  21734. }
  21735. var key = parseKeys(public_key);
  21736. var paddedMsg;
  21737. if (padding === 4) {
  21738. paddedMsg = oaep(key, msg);
  21739. } else if (padding === 1) {
  21740. paddedMsg = pkcs1(key, msg, reverse);
  21741. } else if (padding === 3) {
  21742. paddedMsg = new bn(msg);
  21743. if (paddedMsg.cmp(key.modulus) >= 0) {
  21744. throw new Error('data too long for modulus');
  21745. }
  21746. } else {
  21747. throw new Error('unknown padding');
  21748. }
  21749. if (reverse) {
  21750. return crt(paddedMsg, key);
  21751. } else {
  21752. return withPublic(paddedMsg, key);
  21753. }
  21754. };
  21755. function oaep(key, msg){
  21756. var k = key.modulus.byteLength();
  21757. var mLen = msg.length;
  21758. var iHash = createHash('sha1').update(new Buffer('')).digest();
  21759. var hLen = iHash.length;
  21760. var hLen2 = 2 * hLen;
  21761. if (mLen > k - hLen2 - 2) {
  21762. throw new Error('message too long');
  21763. }
  21764. var ps = new Buffer(k - mLen - hLen2 - 2);
  21765. ps.fill(0);
  21766. var dblen = k - hLen - 1;
  21767. var seed = randomBytes(hLen);
  21768. var maskedDb = xor(Buffer.concat([iHash, ps, new Buffer([1]), msg], dblen), mgf(seed, dblen));
  21769. var maskedSeed = xor(seed, mgf(maskedDb, hLen));
  21770. return new bn(Buffer.concat([new Buffer([0]), maskedSeed, maskedDb], k));
  21771. }
  21772. function pkcs1(key, msg, reverse){
  21773. var mLen = msg.length;
  21774. var k = key.modulus.byteLength();
  21775. if (mLen > k - 11) {
  21776. throw new Error('message too long');
  21777. }
  21778. var ps;
  21779. if (reverse) {
  21780. ps = new Buffer(k - mLen - 3);
  21781. ps.fill(0xff);
  21782. } else {
  21783. ps = nonZero(k - mLen - 3);
  21784. }
  21785. return new bn(Buffer.concat([new Buffer([0, reverse?1:2]), ps, new Buffer([0]), msg], k));
  21786. }
  21787. function nonZero(len, crypto) {
  21788. var out = new Buffer(len);
  21789. var i = 0;
  21790. var cache = randomBytes(len*2);
  21791. var cur = 0;
  21792. var num;
  21793. while (i < len) {
  21794. if (cur === cache.length) {
  21795. cache = randomBytes(len*2);
  21796. cur = 0;
  21797. }
  21798. num = cache[cur++];
  21799. if (num) {
  21800. out[i++] = num;
  21801. }
  21802. }
  21803. return out;
  21804. }
  21805. }).call(this,require("buffer").Buffer)
  21806. },{"./mgf":136,"./withPublic":139,"./xor":140,"bn.js":17,"browserify-rsa":40,"buffer":50,"create-hash":54,"parse-asn1":127,"randombytes":141}],139:[function(require,module,exports){
  21807. (function (Buffer){
  21808. var bn = require('bn.js');
  21809. function withPublic(paddedMsg, key) {
  21810. return new Buffer(paddedMsg
  21811. .toRed(bn.mont(key.modulus))
  21812. .redPow(new bn(key.publicExponent))
  21813. .fromRed()
  21814. .toArray());
  21815. }
  21816. module.exports = withPublic;
  21817. }).call(this,require("buffer").Buffer)
  21818. },{"bn.js":17,"buffer":50}],140:[function(require,module,exports){
  21819. module.exports = function xor(a, b) {
  21820. var len = a.length;
  21821. var i = -1;
  21822. while (++i < len) {
  21823. a[i] ^= b[i];
  21824. }
  21825. return a
  21826. };
  21827. },{}],141:[function(require,module,exports){
  21828. (function (process,global){
  21829. 'use strict'
  21830. function oldBrowser () {
  21831. throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11')
  21832. }
  21833. var Buffer = require('safe-buffer').Buffer
  21834. var crypto = global.crypto || global.msCrypto
  21835. if (crypto && crypto.getRandomValues) {
  21836. module.exports = randomBytes
  21837. } else {
  21838. module.exports = oldBrowser
  21839. }
  21840. function randomBytes (size, cb) {
  21841. // phantomjs needs to throw
  21842. if (size > 65536) throw new Error('requested too many random bytes')
  21843. // in case browserify isn't using the Uint8Array version
  21844. var rawBytes = new global.Uint8Array(size)
  21845. // This will not work in older browsers.
  21846. // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
  21847. if (size > 0) { // getRandomValues fails on IE if size == 0
  21848. crypto.getRandomValues(rawBytes)
  21849. }
  21850. // XXX: phantomjs doesn't like a buffer being passed here
  21851. var bytes = Buffer.from(rawBytes.buffer)
  21852. if (typeof cb === 'function') {
  21853. return process.nextTick(function () {
  21854. cb(null, bytes)
  21855. })
  21856. }
  21857. return bytes
  21858. }
  21859. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  21860. },{"_process":134,"safe-buffer":157}],142:[function(require,module,exports){
  21861. (function (process,global){
  21862. 'use strict'
  21863. function oldBrowser () {
  21864. throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
  21865. }
  21866. var safeBuffer = require('safe-buffer')
  21867. var randombytes = require('randombytes')
  21868. var Buffer = safeBuffer.Buffer
  21869. var kBufferMaxLength = safeBuffer.kMaxLength
  21870. var crypto = global.crypto || global.msCrypto
  21871. var kMaxUint32 = Math.pow(2, 32) - 1
  21872. function assertOffset (offset, length) {
  21873. if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare
  21874. throw new TypeError('offset must be a number')
  21875. }
  21876. if (offset > kMaxUint32 || offset < 0) {
  21877. throw new TypeError('offset must be a uint32')
  21878. }
  21879. if (offset > kBufferMaxLength || offset > length) {
  21880. throw new RangeError('offset out of range')
  21881. }
  21882. }
  21883. function assertSize (size, offset, length) {
  21884. if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare
  21885. throw new TypeError('size must be a number')
  21886. }
  21887. if (size > kMaxUint32 || size < 0) {
  21888. throw new TypeError('size must be a uint32')
  21889. }
  21890. if (size + offset > length || size > kBufferMaxLength) {
  21891. throw new RangeError('buffer too small')
  21892. }
  21893. }
  21894. if ((crypto && crypto.getRandomValues) || !process.browser) {
  21895. exports.randomFill = randomFill
  21896. exports.randomFillSync = randomFillSync
  21897. } else {
  21898. exports.randomFill = oldBrowser
  21899. exports.randomFillSync = oldBrowser
  21900. }
  21901. function randomFill (buf, offset, size, cb) {
  21902. if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
  21903. throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
  21904. }
  21905. if (typeof offset === 'function') {
  21906. cb = offset
  21907. offset = 0
  21908. size = buf.length
  21909. } else if (typeof size === 'function') {
  21910. cb = size
  21911. size = buf.length - offset
  21912. } else if (typeof cb !== 'function') {
  21913. throw new TypeError('"cb" argument must be a function')
  21914. }
  21915. assertOffset(offset, buf.length)
  21916. assertSize(size, offset, buf.length)
  21917. return actualFill(buf, offset, size, cb)
  21918. }
  21919. function actualFill (buf, offset, size, cb) {
  21920. if (process.browser) {
  21921. var ourBuf = buf.buffer
  21922. var uint = new Uint8Array(ourBuf, offset, size)
  21923. crypto.getRandomValues(uint)
  21924. if (cb) {
  21925. process.nextTick(function () {
  21926. cb(null, buf)
  21927. })
  21928. return
  21929. }
  21930. return buf
  21931. }
  21932. if (cb) {
  21933. randombytes(size, function (err, bytes) {
  21934. if (err) {
  21935. return cb(err)
  21936. }
  21937. bytes.copy(buf, offset)
  21938. cb(null, buf)
  21939. })
  21940. return
  21941. }
  21942. var bytes = randombytes(size)
  21943. bytes.copy(buf, offset)
  21944. return buf
  21945. }
  21946. function randomFillSync (buf, offset, size) {
  21947. if (typeof offset === 'undefined') {
  21948. offset = 0
  21949. }
  21950. if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
  21951. throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
  21952. }
  21953. assertOffset(offset, buf.length)
  21954. if (size === undefined) size = buf.length - offset
  21955. assertSize(size, offset, buf.length)
  21956. return actualFill(buf, offset, size)
  21957. }
  21958. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  21959. },{"_process":134,"randombytes":141,"safe-buffer":157}],143:[function(require,module,exports){
  21960. module.exports = require('./lib/_stream_duplex.js');
  21961. },{"./lib/_stream_duplex.js":144}],144:[function(require,module,exports){
  21962. // Copyright Joyent, Inc. and other Node contributors.
  21963. //
  21964. // Permission is hereby granted, free of charge, to any person obtaining a
  21965. // copy of this software and associated documentation files (the
  21966. // "Software"), to deal in the Software without restriction, including
  21967. // without limitation the rights to use, copy, modify, merge, publish,
  21968. // distribute, sublicense, and/or sell copies of the Software, and to permit
  21969. // persons to whom the Software is furnished to do so, subject to the
  21970. // following conditions:
  21971. //
  21972. // The above copyright notice and this permission notice shall be included
  21973. // in all copies or substantial portions of the Software.
  21974. //
  21975. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  21976. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  21977. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  21978. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  21979. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  21980. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  21981. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  21982. // a duplex stream is just a stream that is both readable and writable.
  21983. // Since JS doesn't have multiple prototypal inheritance, this class
  21984. // prototypally inherits from Readable, and then parasitically from
  21985. // Writable.
  21986. 'use strict';
  21987. /*<replacement>*/
  21988. var processNextTick = require('process-nextick-args');
  21989. /*</replacement>*/
  21990. /*<replacement>*/
  21991. var objectKeys = Object.keys || function (obj) {
  21992. var keys = [];
  21993. for (var key in obj) {
  21994. keys.push(key);
  21995. }return keys;
  21996. };
  21997. /*</replacement>*/
  21998. module.exports = Duplex;
  21999. /*<replacement>*/
  22000. var util = require('core-util-is');
  22001. util.inherits = require('inherits');
  22002. /*</replacement>*/
  22003. var Readable = require('./_stream_readable');
  22004. var Writable = require('./_stream_writable');
  22005. util.inherits(Duplex, Readable);
  22006. var keys = objectKeys(Writable.prototype);
  22007. for (var v = 0; v < keys.length; v++) {
  22008. var method = keys[v];
  22009. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  22010. }
  22011. function Duplex(options) {
  22012. if (!(this instanceof Duplex)) return new Duplex(options);
  22013. Readable.call(this, options);
  22014. Writable.call(this, options);
  22015. if (options && options.readable === false) this.readable = false;
  22016. if (options && options.writable === false) this.writable = false;
  22017. this.allowHalfOpen = true;
  22018. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  22019. this.once('end', onend);
  22020. }
  22021. // the no-half-open enforcer
  22022. function onend() {
  22023. // if we allow half-open state, or if the writable side ended,
  22024. // then we're ok.
  22025. if (this.allowHalfOpen || this._writableState.ended) return;
  22026. // no more data can be written.
  22027. // But allow more writes to happen in this tick.
  22028. processNextTick(onEndNT, this);
  22029. }
  22030. function onEndNT(self) {
  22031. self.end();
  22032. }
  22033. Object.defineProperty(Duplex.prototype, 'destroyed', {
  22034. get: function () {
  22035. if (this._readableState === undefined || this._writableState === undefined) {
  22036. return false;
  22037. }
  22038. return this._readableState.destroyed && this._writableState.destroyed;
  22039. },
  22040. set: function (value) {
  22041. // we ignore the value if the stream
  22042. // has not been initialized yet
  22043. if (this._readableState === undefined || this._writableState === undefined) {
  22044. return;
  22045. }
  22046. // backward compatibility, the user is explicitly
  22047. // managing destroyed
  22048. this._readableState.destroyed = value;
  22049. this._writableState.destroyed = value;
  22050. }
  22051. });
  22052. Duplex.prototype._destroy = function (err, cb) {
  22053. this.push(null);
  22054. this.end();
  22055. processNextTick(cb, err);
  22056. };
  22057. function forEach(xs, f) {
  22058. for (var i = 0, l = xs.length; i < l; i++) {
  22059. f(xs[i], i);
  22060. }
  22061. }
  22062. },{"./_stream_readable":146,"./_stream_writable":148,"core-util-is":52,"inherits":104,"process-nextick-args":133}],145:[function(require,module,exports){
  22063. // Copyright Joyent, Inc. and other Node contributors.
  22064. //
  22065. // Permission is hereby granted, free of charge, to any person obtaining a
  22066. // copy of this software and associated documentation files (the
  22067. // "Software"), to deal in the Software without restriction, including
  22068. // without limitation the rights to use, copy, modify, merge, publish,
  22069. // distribute, sublicense, and/or sell copies of the Software, and to permit
  22070. // persons to whom the Software is furnished to do so, subject to the
  22071. // following conditions:
  22072. //
  22073. // The above copyright notice and this permission notice shall be included
  22074. // in all copies or substantial portions of the Software.
  22075. //
  22076. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  22077. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22078. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  22079. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  22080. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22081. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  22082. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  22083. // a passthrough stream.
  22084. // basically just the most minimal sort of Transform stream.
  22085. // Every written chunk gets output as-is.
  22086. 'use strict';
  22087. module.exports = PassThrough;
  22088. var Transform = require('./_stream_transform');
  22089. /*<replacement>*/
  22090. var util = require('core-util-is');
  22091. util.inherits = require('inherits');
  22092. /*</replacement>*/
  22093. util.inherits(PassThrough, Transform);
  22094. function PassThrough(options) {
  22095. if (!(this instanceof PassThrough)) return new PassThrough(options);
  22096. Transform.call(this, options);
  22097. }
  22098. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  22099. cb(null, chunk);
  22100. };
  22101. },{"./_stream_transform":147,"core-util-is":52,"inherits":104}],146:[function(require,module,exports){
  22102. (function (process,global){
  22103. // Copyright Joyent, Inc. and other Node contributors.
  22104. //
  22105. // Permission is hereby granted, free of charge, to any person obtaining a
  22106. // copy of this software and associated documentation files (the
  22107. // "Software"), to deal in the Software without restriction, including
  22108. // without limitation the rights to use, copy, modify, merge, publish,
  22109. // distribute, sublicense, and/or sell copies of the Software, and to permit
  22110. // persons to whom the Software is furnished to do so, subject to the
  22111. // following conditions:
  22112. //
  22113. // The above copyright notice and this permission notice shall be included
  22114. // in all copies or substantial portions of the Software.
  22115. //
  22116. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  22117. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22118. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  22119. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  22120. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22121. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  22122. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  22123. 'use strict';
  22124. /*<replacement>*/
  22125. var processNextTick = require('process-nextick-args');
  22126. /*</replacement>*/
  22127. module.exports = Readable;
  22128. /*<replacement>*/
  22129. var isArray = require('isarray');
  22130. /*</replacement>*/
  22131. /*<replacement>*/
  22132. var Duplex;
  22133. /*</replacement>*/
  22134. Readable.ReadableState = ReadableState;
  22135. /*<replacement>*/
  22136. var EE = require('events').EventEmitter;
  22137. var EElistenerCount = function (emitter, type) {
  22138. return emitter.listeners(type).length;
  22139. };
  22140. /*</replacement>*/
  22141. /*<replacement>*/
  22142. var Stream = require('./internal/streams/stream');
  22143. /*</replacement>*/
  22144. // TODO(bmeurer): Change this back to const once hole checks are
  22145. // properly optimized away early in Ignition+TurboFan.
  22146. /*<replacement>*/
  22147. var Buffer = require('safe-buffer').Buffer;
  22148. var OurUint8Array = global.Uint8Array || function () {};
  22149. function _uint8ArrayToBuffer(chunk) {
  22150. return Buffer.from(chunk);
  22151. }
  22152. function _isUint8Array(obj) {
  22153. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  22154. }
  22155. /*</replacement>*/
  22156. /*<replacement>*/
  22157. var util = require('core-util-is');
  22158. util.inherits = require('inherits');
  22159. /*</replacement>*/
  22160. /*<replacement>*/
  22161. var debugUtil = require('util');
  22162. var debug = void 0;
  22163. if (debugUtil && debugUtil.debuglog) {
  22164. debug = debugUtil.debuglog('stream');
  22165. } else {
  22166. debug = function () {};
  22167. }
  22168. /*</replacement>*/
  22169. var BufferList = require('./internal/streams/BufferList');
  22170. var destroyImpl = require('./internal/streams/destroy');
  22171. var StringDecoder;
  22172. util.inherits(Readable, Stream);
  22173. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  22174. function prependListener(emitter, event, fn) {
  22175. // Sadly this is not cacheable as some libraries bundle their own
  22176. // event emitter implementation with them.
  22177. if (typeof emitter.prependListener === 'function') {
  22178. return emitter.prependListener(event, fn);
  22179. } else {
  22180. // This is a hack to make sure that our error handler is attached before any
  22181. // userland ones. NEVER DO THIS. This is here only because this code needs
  22182. // to continue to work with older versions of Node.js that do not include
  22183. // the prependListener() method. The goal is to eventually remove this hack.
  22184. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
  22185. }
  22186. }
  22187. function ReadableState(options, stream) {
  22188. Duplex = Duplex || require('./_stream_duplex');
  22189. options = options || {};
  22190. // object stream flag. Used to make read(n) ignore n and to
  22191. // make all the buffer merging and length checks go away
  22192. this.objectMode = !!options.objectMode;
  22193. if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  22194. // the point at which it stops calling _read() to fill the buffer
  22195. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  22196. var hwm = options.highWaterMark;
  22197. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  22198. this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
  22199. // cast to ints.
  22200. this.highWaterMark = Math.floor(this.highWaterMark);
  22201. // A linked list is used to store data chunks instead of an array because the
  22202. // linked list can remove elements from the beginning faster than
  22203. // array.shift()
  22204. this.buffer = new BufferList();
  22205. this.length = 0;
  22206. this.pipes = null;
  22207. this.pipesCount = 0;
  22208. this.flowing = null;
  22209. this.ended = false;
  22210. this.endEmitted = false;
  22211. this.reading = false;
  22212. // a flag to be able to tell if the event 'readable'/'data' is emitted
  22213. // immediately, or on a later tick. We set this to true at first, because
  22214. // any actions that shouldn't happen until "later" should generally also
  22215. // not happen before the first read call.
  22216. this.sync = true;
  22217. // whenever we return null, then we set a flag to say
  22218. // that we're awaiting a 'readable' event emission.
  22219. this.needReadable = false;
  22220. this.emittedReadable = false;
  22221. this.readableListening = false;
  22222. this.resumeScheduled = false;
  22223. // has it been destroyed
  22224. this.destroyed = false;
  22225. // Crypto is kind of old and crusty. Historically, its default string
  22226. // encoding is 'binary' so we have to make this configurable.
  22227. // Everything else in the universe uses 'utf8', though.
  22228. this.defaultEncoding = options.defaultEncoding || 'utf8';
  22229. // the number of writers that are awaiting a drain event in .pipe()s
  22230. this.awaitDrain = 0;
  22231. // if true, a maybeReadMore has been scheduled
  22232. this.readingMore = false;
  22233. this.decoder = null;
  22234. this.encoding = null;
  22235. if (options.encoding) {
  22236. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  22237. this.decoder = new StringDecoder(options.encoding);
  22238. this.encoding = options.encoding;
  22239. }
  22240. }
  22241. function Readable(options) {
  22242. Duplex = Duplex || require('./_stream_duplex');
  22243. if (!(this instanceof Readable)) return new Readable(options);
  22244. this._readableState = new ReadableState(options, this);
  22245. // legacy
  22246. this.readable = true;
  22247. if (options) {
  22248. if (typeof options.read === 'function') this._read = options.read;
  22249. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  22250. }
  22251. Stream.call(this);
  22252. }
  22253. Object.defineProperty(Readable.prototype, 'destroyed', {
  22254. get: function () {
  22255. if (this._readableState === undefined) {
  22256. return false;
  22257. }
  22258. return this._readableState.destroyed;
  22259. },
  22260. set: function (value) {
  22261. // we ignore the value if the stream
  22262. // has not been initialized yet
  22263. if (!this._readableState) {
  22264. return;
  22265. }
  22266. // backward compatibility, the user is explicitly
  22267. // managing destroyed
  22268. this._readableState.destroyed = value;
  22269. }
  22270. });
  22271. Readable.prototype.destroy = destroyImpl.destroy;
  22272. Readable.prototype._undestroy = destroyImpl.undestroy;
  22273. Readable.prototype._destroy = function (err, cb) {
  22274. this.push(null);
  22275. cb(err);
  22276. };
  22277. // Manually shove something into the read() buffer.
  22278. // This returns true if the highWaterMark has not been hit yet,
  22279. // similar to how Writable.write() returns true if you should
  22280. // write() some more.
  22281. Readable.prototype.push = function (chunk, encoding) {
  22282. var state = this._readableState;
  22283. var skipChunkCheck;
  22284. if (!state.objectMode) {
  22285. if (typeof chunk === 'string') {
  22286. encoding = encoding || state.defaultEncoding;
  22287. if (encoding !== state.encoding) {
  22288. chunk = Buffer.from(chunk, encoding);
  22289. encoding = '';
  22290. }
  22291. skipChunkCheck = true;
  22292. }
  22293. } else {
  22294. skipChunkCheck = true;
  22295. }
  22296. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  22297. };
  22298. // Unshift should *always* be something directly out of read()
  22299. Readable.prototype.unshift = function (chunk) {
  22300. return readableAddChunk(this, chunk, null, true, false);
  22301. };
  22302. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  22303. var state = stream._readableState;
  22304. if (chunk === null) {
  22305. state.reading = false;
  22306. onEofChunk(stream, state);
  22307. } else {
  22308. var er;
  22309. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  22310. if (er) {
  22311. stream.emit('error', er);
  22312. } else if (state.objectMode || chunk && chunk.length > 0) {
  22313. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  22314. chunk = _uint8ArrayToBuffer(chunk);
  22315. }
  22316. if (addToFront) {
  22317. if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
  22318. } else if (state.ended) {
  22319. stream.emit('error', new Error('stream.push() after EOF'));
  22320. } else {
  22321. state.reading = false;
  22322. if (state.decoder && !encoding) {
  22323. chunk = state.decoder.write(chunk);
  22324. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  22325. } else {
  22326. addChunk(stream, state, chunk, false);
  22327. }
  22328. }
  22329. } else if (!addToFront) {
  22330. state.reading = false;
  22331. }
  22332. }
  22333. return needMoreData(state);
  22334. }
  22335. function addChunk(stream, state, chunk, addToFront) {
  22336. if (state.flowing && state.length === 0 && !state.sync) {
  22337. stream.emit('data', chunk);
  22338. stream.read(0);
  22339. } else {
  22340. // update the buffer info.
  22341. state.length += state.objectMode ? 1 : chunk.length;
  22342. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  22343. if (state.needReadable) emitReadable(stream);
  22344. }
  22345. maybeReadMore(stream, state);
  22346. }
  22347. function chunkInvalid(state, chunk) {
  22348. var er;
  22349. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  22350. er = new TypeError('Invalid non-string/buffer chunk');
  22351. }
  22352. return er;
  22353. }
  22354. // if it's past the high water mark, we can push in some more.
  22355. // Also, if we have no data yet, we can stand some
  22356. // more bytes. This is to work around cases where hwm=0,
  22357. // such as the repl. Also, if the push() triggered a
  22358. // readable event, and the user called read(largeNumber) such that
  22359. // needReadable was set, then we ought to push more, so that another
  22360. // 'readable' event will be triggered.
  22361. function needMoreData(state) {
  22362. return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  22363. }
  22364. Readable.prototype.isPaused = function () {
  22365. return this._readableState.flowing === false;
  22366. };
  22367. // backwards compatibility.
  22368. Readable.prototype.setEncoding = function (enc) {
  22369. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  22370. this._readableState.decoder = new StringDecoder(enc);
  22371. this._readableState.encoding = enc;
  22372. return this;
  22373. };
  22374. // Don't raise the hwm > 8MB
  22375. var MAX_HWM = 0x800000;
  22376. function computeNewHighWaterMark(n) {
  22377. if (n >= MAX_HWM) {
  22378. n = MAX_HWM;
  22379. } else {
  22380. // Get the next highest power of 2 to prevent increasing hwm excessively in
  22381. // tiny amounts
  22382. n--;
  22383. n |= n >>> 1;
  22384. n |= n >>> 2;
  22385. n |= n >>> 4;
  22386. n |= n >>> 8;
  22387. n |= n >>> 16;
  22388. n++;
  22389. }
  22390. return n;
  22391. }
  22392. // This function is designed to be inlinable, so please take care when making
  22393. // changes to the function body.
  22394. function howMuchToRead(n, state) {
  22395. if (n <= 0 || state.length === 0 && state.ended) return 0;
  22396. if (state.objectMode) return 1;
  22397. if (n !== n) {
  22398. // Only flow one buffer at a time
  22399. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  22400. }
  22401. // If we're asking for more than the current hwm, then raise the hwm.
  22402. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  22403. if (n <= state.length) return n;
  22404. // Don't have enough
  22405. if (!state.ended) {
  22406. state.needReadable = true;
  22407. return 0;
  22408. }
  22409. return state.length;
  22410. }
  22411. // you can override either this method, or the async _read(n) below.
  22412. Readable.prototype.read = function (n) {
  22413. debug('read', n);
  22414. n = parseInt(n, 10);
  22415. var state = this._readableState;
  22416. var nOrig = n;
  22417. if (n !== 0) state.emittedReadable = false;
  22418. // if we're doing read(0) to trigger a readable event, but we
  22419. // already have a bunch of data in the buffer, then just trigger
  22420. // the 'readable' event and move on.
  22421. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
  22422. debug('read: emitReadable', state.length, state.ended);
  22423. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  22424. return null;
  22425. }
  22426. n = howMuchToRead(n, state);
  22427. // if we've ended, and we're now clear, then finish it up.
  22428. if (n === 0 && state.ended) {
  22429. if (state.length === 0) endReadable(this);
  22430. return null;
  22431. }
  22432. // All the actual chunk generation logic needs to be
  22433. // *below* the call to _read. The reason is that in certain
  22434. // synthetic stream cases, such as passthrough streams, _read
  22435. // may be a completely synchronous operation which may change
  22436. // the state of the read buffer, providing enough data when
  22437. // before there was *not* enough.
  22438. //
  22439. // So, the steps are:
  22440. // 1. Figure out what the state of things will be after we do
  22441. // a read from the buffer.
  22442. //
  22443. // 2. If that resulting state will trigger a _read, then call _read.
  22444. // Note that this may be asynchronous, or synchronous. Yes, it is
  22445. // deeply ugly to write APIs this way, but that still doesn't mean
  22446. // that the Readable class should behave improperly, as streams are
  22447. // designed to be sync/async agnostic.
  22448. // Take note if the _read call is sync or async (ie, if the read call
  22449. // has returned yet), so that we know whether or not it's safe to emit
  22450. // 'readable' etc.
  22451. //
  22452. // 3. Actually pull the requested chunks out of the buffer and return.
  22453. // if we need a readable event, then we need to do some reading.
  22454. var doRead = state.needReadable;
  22455. debug('need readable', doRead);
  22456. // if we currently have less than the highWaterMark, then also read some
  22457. if (state.length === 0 || state.length - n < state.highWaterMark) {
  22458. doRead = true;
  22459. debug('length less than watermark', doRead);
  22460. }
  22461. // however, if we've ended, then there's no point, and if we're already
  22462. // reading, then it's unnecessary.
  22463. if (state.ended || state.reading) {
  22464. doRead = false;
  22465. debug('reading or ended', doRead);
  22466. } else if (doRead) {
  22467. debug('do read');
  22468. state.reading = true;
  22469. state.sync = true;
  22470. // if the length is currently zero, then we *need* a readable event.
  22471. if (state.length === 0) state.needReadable = true;
  22472. // call internal read method
  22473. this._read(state.highWaterMark);
  22474. state.sync = false;
  22475. // If _read pushed data synchronously, then `reading` will be false,
  22476. // and we need to re-evaluate how much data we can return to the user.
  22477. if (!state.reading) n = howMuchToRead(nOrig, state);
  22478. }
  22479. var ret;
  22480. if (n > 0) ret = fromList(n, state);else ret = null;
  22481. if (ret === null) {
  22482. state.needReadable = true;
  22483. n = 0;
  22484. } else {
  22485. state.length -= n;
  22486. }
  22487. if (state.length === 0) {
  22488. // If we have nothing in the buffer, then we want to know
  22489. // as soon as we *do* get something into the buffer.
  22490. if (!state.ended) state.needReadable = true;
  22491. // If we tried to read() past the EOF, then emit end on the next tick.
  22492. if (nOrig !== n && state.ended) endReadable(this);
  22493. }
  22494. if (ret !== null) this.emit('data', ret);
  22495. return ret;
  22496. };
  22497. function onEofChunk(stream, state) {
  22498. if (state.ended) return;
  22499. if (state.decoder) {
  22500. var chunk = state.decoder.end();
  22501. if (chunk && chunk.length) {
  22502. state.buffer.push(chunk);
  22503. state.length += state.objectMode ? 1 : chunk.length;
  22504. }
  22505. }
  22506. state.ended = true;
  22507. // emit 'readable' now to make sure it gets picked up.
  22508. emitReadable(stream);
  22509. }
  22510. // Don't emit readable right away in sync mode, because this can trigger
  22511. // another read() call => stack overflow. This way, it might trigger
  22512. // a nextTick recursion warning, but that's not so bad.
  22513. function emitReadable(stream) {
  22514. var state = stream._readableState;
  22515. state.needReadable = false;
  22516. if (!state.emittedReadable) {
  22517. debug('emitReadable', state.flowing);
  22518. state.emittedReadable = true;
  22519. if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
  22520. }
  22521. }
  22522. function emitReadable_(stream) {
  22523. debug('emit readable');
  22524. stream.emit('readable');
  22525. flow(stream);
  22526. }
  22527. // at this point, the user has presumably seen the 'readable' event,
  22528. // and called read() to consume some data. that may have triggered
  22529. // in turn another _read(n) call, in which case reading = true if
  22530. // it's in progress.
  22531. // However, if we're not ended, or reading, and the length < hwm,
  22532. // then go ahead and try to read some more preemptively.
  22533. function maybeReadMore(stream, state) {
  22534. if (!state.readingMore) {
  22535. state.readingMore = true;
  22536. processNextTick(maybeReadMore_, stream, state);
  22537. }
  22538. }
  22539. function maybeReadMore_(stream, state) {
  22540. var len = state.length;
  22541. while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
  22542. debug('maybeReadMore read 0');
  22543. stream.read(0);
  22544. if (len === state.length)
  22545. // didn't get any data, stop spinning.
  22546. break;else len = state.length;
  22547. }
  22548. state.readingMore = false;
  22549. }
  22550. // abstract method. to be overridden in specific implementation classes.
  22551. // call cb(er, data) where data is <= n in length.
  22552. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  22553. // arbitrary, and perhaps not very meaningful.
  22554. Readable.prototype._read = function (n) {
  22555. this.emit('error', new Error('_read() is not implemented'));
  22556. };
  22557. Readable.prototype.pipe = function (dest, pipeOpts) {
  22558. var src = this;
  22559. var state = this._readableState;
  22560. switch (state.pipesCount) {
  22561. case 0:
  22562. state.pipes = dest;
  22563. break;
  22564. case 1:
  22565. state.pipes = [state.pipes, dest];
  22566. break;
  22567. default:
  22568. state.pipes.push(dest);
  22569. break;
  22570. }
  22571. state.pipesCount += 1;
  22572. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  22573. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  22574. var endFn = doEnd ? onend : unpipe;
  22575. if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
  22576. dest.on('unpipe', onunpipe);
  22577. function onunpipe(readable, unpipeInfo) {
  22578. debug('onunpipe');
  22579. if (readable === src) {
  22580. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  22581. unpipeInfo.hasUnpiped = true;
  22582. cleanup();
  22583. }
  22584. }
  22585. }
  22586. function onend() {
  22587. debug('onend');
  22588. dest.end();
  22589. }
  22590. // when the dest drains, it reduces the awaitDrain counter
  22591. // on the source. This would be more elegant with a .once()
  22592. // handler in flow(), but adding and removing repeatedly is
  22593. // too slow.
  22594. var ondrain = pipeOnDrain(src);
  22595. dest.on('drain', ondrain);
  22596. var cleanedUp = false;
  22597. function cleanup() {
  22598. debug('cleanup');
  22599. // cleanup event handlers once the pipe is broken
  22600. dest.removeListener('close', onclose);
  22601. dest.removeListener('finish', onfinish);
  22602. dest.removeListener('drain', ondrain);
  22603. dest.removeListener('error', onerror);
  22604. dest.removeListener('unpipe', onunpipe);
  22605. src.removeListener('end', onend);
  22606. src.removeListener('end', unpipe);
  22607. src.removeListener('data', ondata);
  22608. cleanedUp = true;
  22609. // if the reader is waiting for a drain event from this
  22610. // specific writer, then it would cause it to never start
  22611. // flowing again.
  22612. // So, if this is awaiting a drain, then we just call it now.
  22613. // If we don't know, then assume that we are waiting for one.
  22614. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  22615. }
  22616. // If the user pushes more data while we're writing to dest then we'll end up
  22617. // in ondata again. However, we only want to increase awaitDrain once because
  22618. // dest will only emit one 'drain' event for the multiple writes.
  22619. // => Introduce a guard on increasing awaitDrain.
  22620. var increasedAwaitDrain = false;
  22621. src.on('data', ondata);
  22622. function ondata(chunk) {
  22623. debug('ondata');
  22624. increasedAwaitDrain = false;
  22625. var ret = dest.write(chunk);
  22626. if (false === ret && !increasedAwaitDrain) {
  22627. // If the user unpiped during `dest.write()`, it is possible
  22628. // to get stuck in a permanently paused state if that write
  22629. // also returned false.
  22630. // => Check whether `dest` is still a piping destination.
  22631. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  22632. debug('false write response, pause', src._readableState.awaitDrain);
  22633. src._readableState.awaitDrain++;
  22634. increasedAwaitDrain = true;
  22635. }
  22636. src.pause();
  22637. }
  22638. }
  22639. // if the dest has an error, then stop piping into it.
  22640. // however, don't suppress the throwing behavior for this.
  22641. function onerror(er) {
  22642. debug('onerror', er);
  22643. unpipe();
  22644. dest.removeListener('error', onerror);
  22645. if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  22646. }
  22647. // Make sure our error handler is attached before userland ones.
  22648. prependListener(dest, 'error', onerror);
  22649. // Both close and finish should trigger unpipe, but only once.
  22650. function onclose() {
  22651. dest.removeListener('finish', onfinish);
  22652. unpipe();
  22653. }
  22654. dest.once('close', onclose);
  22655. function onfinish() {
  22656. debug('onfinish');
  22657. dest.removeListener('close', onclose);
  22658. unpipe();
  22659. }
  22660. dest.once('finish', onfinish);
  22661. function unpipe() {
  22662. debug('unpipe');
  22663. src.unpipe(dest);
  22664. }
  22665. // tell the dest that it's being piped to
  22666. dest.emit('pipe', src);
  22667. // start the flow if it hasn't been started already.
  22668. if (!state.flowing) {
  22669. debug('pipe resume');
  22670. src.resume();
  22671. }
  22672. return dest;
  22673. };
  22674. function pipeOnDrain(src) {
  22675. return function () {
  22676. var state = src._readableState;
  22677. debug('pipeOnDrain', state.awaitDrain);
  22678. if (state.awaitDrain) state.awaitDrain--;
  22679. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  22680. state.flowing = true;
  22681. flow(src);
  22682. }
  22683. };
  22684. }
  22685. Readable.prototype.unpipe = function (dest) {
  22686. var state = this._readableState;
  22687. var unpipeInfo = { hasUnpiped: false };
  22688. // if we're not piping anywhere, then do nothing.
  22689. if (state.pipesCount === 0) return this;
  22690. // just one destination. most common case.
  22691. if (state.pipesCount === 1) {
  22692. // passed in one, but it's not the right one.
  22693. if (dest && dest !== state.pipes) return this;
  22694. if (!dest) dest = state.pipes;
  22695. // got a match.
  22696. state.pipes = null;
  22697. state.pipesCount = 0;
  22698. state.flowing = false;
  22699. if (dest) dest.emit('unpipe', this, unpipeInfo);
  22700. return this;
  22701. }
  22702. // slow case. multiple pipe destinations.
  22703. if (!dest) {
  22704. // remove all.
  22705. var dests = state.pipes;
  22706. var len = state.pipesCount;
  22707. state.pipes = null;
  22708. state.pipesCount = 0;
  22709. state.flowing = false;
  22710. for (var i = 0; i < len; i++) {
  22711. dests[i].emit('unpipe', this, unpipeInfo);
  22712. }return this;
  22713. }
  22714. // try to find the right one.
  22715. var index = indexOf(state.pipes, dest);
  22716. if (index === -1) return this;
  22717. state.pipes.splice(index, 1);
  22718. state.pipesCount -= 1;
  22719. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  22720. dest.emit('unpipe', this, unpipeInfo);
  22721. return this;
  22722. };
  22723. // set up data events if they are asked for
  22724. // Ensure readable listeners eventually get something
  22725. Readable.prototype.on = function (ev, fn) {
  22726. var res = Stream.prototype.on.call(this, ev, fn);
  22727. if (ev === 'data') {
  22728. // Start flowing on next tick if stream isn't explicitly paused
  22729. if (this._readableState.flowing !== false) this.resume();
  22730. } else if (ev === 'readable') {
  22731. var state = this._readableState;
  22732. if (!state.endEmitted && !state.readableListening) {
  22733. state.readableListening = state.needReadable = true;
  22734. state.emittedReadable = false;
  22735. if (!state.reading) {
  22736. processNextTick(nReadingNextTick, this);
  22737. } else if (state.length) {
  22738. emitReadable(this);
  22739. }
  22740. }
  22741. }
  22742. return res;
  22743. };
  22744. Readable.prototype.addListener = Readable.prototype.on;
  22745. function nReadingNextTick(self) {
  22746. debug('readable nexttick read 0');
  22747. self.read(0);
  22748. }
  22749. // pause() and resume() are remnants of the legacy readable stream API
  22750. // If the user uses them, then switch into old mode.
  22751. Readable.prototype.resume = function () {
  22752. var state = this._readableState;
  22753. if (!state.flowing) {
  22754. debug('resume');
  22755. state.flowing = true;
  22756. resume(this, state);
  22757. }
  22758. return this;
  22759. };
  22760. function resume(stream, state) {
  22761. if (!state.resumeScheduled) {
  22762. state.resumeScheduled = true;
  22763. processNextTick(resume_, stream, state);
  22764. }
  22765. }
  22766. function resume_(stream, state) {
  22767. if (!state.reading) {
  22768. debug('resume read 0');
  22769. stream.read(0);
  22770. }
  22771. state.resumeScheduled = false;
  22772. state.awaitDrain = 0;
  22773. stream.emit('resume');
  22774. flow(stream);
  22775. if (state.flowing && !state.reading) stream.read(0);
  22776. }
  22777. Readable.prototype.pause = function () {
  22778. debug('call pause flowing=%j', this._readableState.flowing);
  22779. if (false !== this._readableState.flowing) {
  22780. debug('pause');
  22781. this._readableState.flowing = false;
  22782. this.emit('pause');
  22783. }
  22784. return this;
  22785. };
  22786. function flow(stream) {
  22787. var state = stream._readableState;
  22788. debug('flow', state.flowing);
  22789. while (state.flowing && stream.read() !== null) {}
  22790. }
  22791. // wrap an old-style stream as the async data source.
  22792. // This is *not* part of the readable stream interface.
  22793. // It is an ugly unfortunate mess of history.
  22794. Readable.prototype.wrap = function (stream) {
  22795. var state = this._readableState;
  22796. var paused = false;
  22797. var self = this;
  22798. stream.on('end', function () {
  22799. debug('wrapped end');
  22800. if (state.decoder && !state.ended) {
  22801. var chunk = state.decoder.end();
  22802. if (chunk && chunk.length) self.push(chunk);
  22803. }
  22804. self.push(null);
  22805. });
  22806. stream.on('data', function (chunk) {
  22807. debug('wrapped data');
  22808. if (state.decoder) chunk = state.decoder.write(chunk);
  22809. // don't skip over falsy values in objectMode
  22810. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  22811. var ret = self.push(chunk);
  22812. if (!ret) {
  22813. paused = true;
  22814. stream.pause();
  22815. }
  22816. });
  22817. // proxy all the other methods.
  22818. // important when wrapping filters and duplexes.
  22819. for (var i in stream) {
  22820. if (this[i] === undefined && typeof stream[i] === 'function') {
  22821. this[i] = function (method) {
  22822. return function () {
  22823. return stream[method].apply(stream, arguments);
  22824. };
  22825. }(i);
  22826. }
  22827. }
  22828. // proxy certain important events.
  22829. for (var n = 0; n < kProxyEvents.length; n++) {
  22830. stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n]));
  22831. }
  22832. // when we try to consume some more bytes, simply unpause the
  22833. // underlying stream.
  22834. self._read = function (n) {
  22835. debug('wrapped _read', n);
  22836. if (paused) {
  22837. paused = false;
  22838. stream.resume();
  22839. }
  22840. };
  22841. return self;
  22842. };
  22843. // exposed for testing purposes only.
  22844. Readable._fromList = fromList;
  22845. // Pluck off n bytes from an array of buffers.
  22846. // Length is the combined lengths of all the buffers in the list.
  22847. // This function is designed to be inlinable, so please take care when making
  22848. // changes to the function body.
  22849. function fromList(n, state) {
  22850. // nothing buffered
  22851. if (state.length === 0) return null;
  22852. var ret;
  22853. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  22854. // read it all, truncate the list
  22855. if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
  22856. state.buffer.clear();
  22857. } else {
  22858. // read part of list
  22859. ret = fromListPartial(n, state.buffer, state.decoder);
  22860. }
  22861. return ret;
  22862. }
  22863. // Extracts only enough buffered data to satisfy the amount requested.
  22864. // This function is designed to be inlinable, so please take care when making
  22865. // changes to the function body.
  22866. function fromListPartial(n, list, hasStrings) {
  22867. var ret;
  22868. if (n < list.head.data.length) {
  22869. // slice is the same for buffers and strings
  22870. ret = list.head.data.slice(0, n);
  22871. list.head.data = list.head.data.slice(n);
  22872. } else if (n === list.head.data.length) {
  22873. // first chunk is a perfect match
  22874. ret = list.shift();
  22875. } else {
  22876. // result spans more than one buffer
  22877. ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  22878. }
  22879. return ret;
  22880. }
  22881. // Copies a specified amount of characters from the list of buffered data
  22882. // chunks.
  22883. // This function is designed to be inlinable, so please take care when making
  22884. // changes to the function body.
  22885. function copyFromBufferString(n, list) {
  22886. var p = list.head;
  22887. var c = 1;
  22888. var ret = p.data;
  22889. n -= ret.length;
  22890. while (p = p.next) {
  22891. var str = p.data;
  22892. var nb = n > str.length ? str.length : n;
  22893. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  22894. n -= nb;
  22895. if (n === 0) {
  22896. if (nb === str.length) {
  22897. ++c;
  22898. if (p.next) list.head = p.next;else list.head = list.tail = null;
  22899. } else {
  22900. list.head = p;
  22901. p.data = str.slice(nb);
  22902. }
  22903. break;
  22904. }
  22905. ++c;
  22906. }
  22907. list.length -= c;
  22908. return ret;
  22909. }
  22910. // Copies a specified amount of bytes from the list of buffered data chunks.
  22911. // This function is designed to be inlinable, so please take care when making
  22912. // changes to the function body.
  22913. function copyFromBuffer(n, list) {
  22914. var ret = Buffer.allocUnsafe(n);
  22915. var p = list.head;
  22916. var c = 1;
  22917. p.data.copy(ret);
  22918. n -= p.data.length;
  22919. while (p = p.next) {
  22920. var buf = p.data;
  22921. var nb = n > buf.length ? buf.length : n;
  22922. buf.copy(ret, ret.length - n, 0, nb);
  22923. n -= nb;
  22924. if (n === 0) {
  22925. if (nb === buf.length) {
  22926. ++c;
  22927. if (p.next) list.head = p.next;else list.head = list.tail = null;
  22928. } else {
  22929. list.head = p;
  22930. p.data = buf.slice(nb);
  22931. }
  22932. break;
  22933. }
  22934. ++c;
  22935. }
  22936. list.length -= c;
  22937. return ret;
  22938. }
  22939. function endReadable(stream) {
  22940. var state = stream._readableState;
  22941. // If we get here before consuming all the bytes, then that is a
  22942. // bug in node. Should never happen.
  22943. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  22944. if (!state.endEmitted) {
  22945. state.ended = true;
  22946. processNextTick(endReadableNT, state, stream);
  22947. }
  22948. }
  22949. function endReadableNT(state, stream) {
  22950. // Check that we didn't get one last unshift.
  22951. if (!state.endEmitted && state.length === 0) {
  22952. state.endEmitted = true;
  22953. stream.readable = false;
  22954. stream.emit('end');
  22955. }
  22956. }
  22957. function forEach(xs, f) {
  22958. for (var i = 0, l = xs.length; i < l; i++) {
  22959. f(xs[i], i);
  22960. }
  22961. }
  22962. function indexOf(xs, x) {
  22963. for (var i = 0, l = xs.length; i < l; i++) {
  22964. if (xs[i] === x) return i;
  22965. }
  22966. return -1;
  22967. }
  22968. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  22969. },{"./_stream_duplex":144,"./internal/streams/BufferList":149,"./internal/streams/destroy":150,"./internal/streams/stream":151,"_process":134,"core-util-is":52,"events":86,"inherits":104,"isarray":106,"process-nextick-args":133,"safe-buffer":157,"string_decoder/":167,"util":19}],147:[function(require,module,exports){
  22970. // Copyright Joyent, Inc. and other Node contributors.
  22971. //
  22972. // Permission is hereby granted, free of charge, to any person obtaining a
  22973. // copy of this software and associated documentation files (the
  22974. // "Software"), to deal in the Software without restriction, including
  22975. // without limitation the rights to use, copy, modify, merge, publish,
  22976. // distribute, sublicense, and/or sell copies of the Software, and to permit
  22977. // persons to whom the Software is furnished to do so, subject to the
  22978. // following conditions:
  22979. //
  22980. // The above copyright notice and this permission notice shall be included
  22981. // in all copies or substantial portions of the Software.
  22982. //
  22983. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  22984. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22985. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  22986. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  22987. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22988. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  22989. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  22990. // a transform stream is a readable/writable stream where you do
  22991. // something with the data. Sometimes it's called a "filter",
  22992. // but that's not a great name for it, since that implies a thing where
  22993. // some bits pass through, and others are simply ignored. (That would
  22994. // be a valid example of a transform, of course.)
  22995. //
  22996. // While the output is causally related to the input, it's not a
  22997. // necessarily symmetric or synchronous transformation. For example,
  22998. // a zlib stream might take multiple plain-text writes(), and then
  22999. // emit a single compressed chunk some time in the future.
  23000. //
  23001. // Here's how this works:
  23002. //
  23003. // The Transform stream has all the aspects of the readable and writable
  23004. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  23005. // internally, and returns false if there's a lot of pending writes
  23006. // buffered up. When you call read(), that calls _read(n) until
  23007. // there's enough pending readable data buffered up.
  23008. //
  23009. // In a transform stream, the written data is placed in a buffer. When
  23010. // _read(n) is called, it transforms the queued up data, calling the
  23011. // buffered _write cb's as it consumes chunks. If consuming a single
  23012. // written chunk would result in multiple output chunks, then the first
  23013. // outputted bit calls the readcb, and subsequent chunks just go into
  23014. // the read buffer, and will cause it to emit 'readable' if necessary.
  23015. //
  23016. // This way, back-pressure is actually determined by the reading side,
  23017. // since _read has to be called to start processing a new chunk. However,
  23018. // a pathological inflate type of transform can cause excessive buffering
  23019. // here. For example, imagine a stream where every byte of input is
  23020. // interpreted as an integer from 0-255, and then results in that many
  23021. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  23022. // 1kb of data being output. In this case, you could write a very small
  23023. // amount of input, and end up with a very large amount of output. In
  23024. // such a pathological inflating mechanism, there'd be no way to tell
  23025. // the system to stop doing the transform. A single 4MB write could
  23026. // cause the system to run out of memory.
  23027. //
  23028. // However, even in such a pathological case, only a single written chunk
  23029. // would be consumed, and then the rest would wait (un-transformed) until
  23030. // the results of the previous transformed chunk were consumed.
  23031. 'use strict';
  23032. module.exports = Transform;
  23033. var Duplex = require('./_stream_duplex');
  23034. /*<replacement>*/
  23035. var util = require('core-util-is');
  23036. util.inherits = require('inherits');
  23037. /*</replacement>*/
  23038. util.inherits(Transform, Duplex);
  23039. function TransformState(stream) {
  23040. this.afterTransform = function (er, data) {
  23041. return afterTransform(stream, er, data);
  23042. };
  23043. this.needTransform = false;
  23044. this.transforming = false;
  23045. this.writecb = null;
  23046. this.writechunk = null;
  23047. this.writeencoding = null;
  23048. }
  23049. function afterTransform(stream, er, data) {
  23050. var ts = stream._transformState;
  23051. ts.transforming = false;
  23052. var cb = ts.writecb;
  23053. if (!cb) {
  23054. return stream.emit('error', new Error('write callback called multiple times'));
  23055. }
  23056. ts.writechunk = null;
  23057. ts.writecb = null;
  23058. if (data !== null && data !== undefined) stream.push(data);
  23059. cb(er);
  23060. var rs = stream._readableState;
  23061. rs.reading = false;
  23062. if (rs.needReadable || rs.length < rs.highWaterMark) {
  23063. stream._read(rs.highWaterMark);
  23064. }
  23065. }
  23066. function Transform(options) {
  23067. if (!(this instanceof Transform)) return new Transform(options);
  23068. Duplex.call(this, options);
  23069. this._transformState = new TransformState(this);
  23070. var stream = this;
  23071. // start out asking for a readable event once data is transformed.
  23072. this._readableState.needReadable = true;
  23073. // we have implemented the _read method, and done the other things
  23074. // that Readable wants before the first _read call, so unset the
  23075. // sync guard flag.
  23076. this._readableState.sync = false;
  23077. if (options) {
  23078. if (typeof options.transform === 'function') this._transform = options.transform;
  23079. if (typeof options.flush === 'function') this._flush = options.flush;
  23080. }
  23081. // When the writable side finishes, then flush out anything remaining.
  23082. this.once('prefinish', function () {
  23083. if (typeof this._flush === 'function') this._flush(function (er, data) {
  23084. done(stream, er, data);
  23085. });else done(stream);
  23086. });
  23087. }
  23088. Transform.prototype.push = function (chunk, encoding) {
  23089. this._transformState.needTransform = false;
  23090. return Duplex.prototype.push.call(this, chunk, encoding);
  23091. };
  23092. // This is the part where you do stuff!
  23093. // override this function in implementation classes.
  23094. // 'chunk' is an input chunk.
  23095. //
  23096. // Call `push(newChunk)` to pass along transformed output
  23097. // to the readable side. You may call 'push' zero or more times.
  23098. //
  23099. // Call `cb(err)` when you are done with this chunk. If you pass
  23100. // an error, then that'll put the hurt on the whole operation. If you
  23101. // never call cb(), then you'll never get another chunk.
  23102. Transform.prototype._transform = function (chunk, encoding, cb) {
  23103. throw new Error('_transform() is not implemented');
  23104. };
  23105. Transform.prototype._write = function (chunk, encoding, cb) {
  23106. var ts = this._transformState;
  23107. ts.writecb = cb;
  23108. ts.writechunk = chunk;
  23109. ts.writeencoding = encoding;
  23110. if (!ts.transforming) {
  23111. var rs = this._readableState;
  23112. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  23113. }
  23114. };
  23115. // Doesn't matter what the args are here.
  23116. // _transform does all the work.
  23117. // That we got here means that the readable side wants more data.
  23118. Transform.prototype._read = function (n) {
  23119. var ts = this._transformState;
  23120. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  23121. ts.transforming = true;
  23122. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  23123. } else {
  23124. // mark that we need a transform, so that any data that comes in
  23125. // will get processed, now that we've asked for it.
  23126. ts.needTransform = true;
  23127. }
  23128. };
  23129. Transform.prototype._destroy = function (err, cb) {
  23130. var _this = this;
  23131. Duplex.prototype._destroy.call(this, err, function (err2) {
  23132. cb(err2);
  23133. _this.emit('close');
  23134. });
  23135. };
  23136. function done(stream, er, data) {
  23137. if (er) return stream.emit('error', er);
  23138. if (data !== null && data !== undefined) stream.push(data);
  23139. // if there's nothing in the write buffer, then that means
  23140. // that nothing more will ever be provided
  23141. var ws = stream._writableState;
  23142. var ts = stream._transformState;
  23143. if (ws.length) throw new Error('Calling transform done when ws.length != 0');
  23144. if (ts.transforming) throw new Error('Calling transform done when still transforming');
  23145. return stream.push(null);
  23146. }
  23147. },{"./_stream_duplex":144,"core-util-is":52,"inherits":104}],148:[function(require,module,exports){
  23148. (function (process,global){
  23149. // Copyright Joyent, Inc. and other Node contributors.
  23150. //
  23151. // Permission is hereby granted, free of charge, to any person obtaining a
  23152. // copy of this software and associated documentation files (the
  23153. // "Software"), to deal in the Software without restriction, including
  23154. // without limitation the rights to use, copy, modify, merge, publish,
  23155. // distribute, sublicense, and/or sell copies of the Software, and to permit
  23156. // persons to whom the Software is furnished to do so, subject to the
  23157. // following conditions:
  23158. //
  23159. // The above copyright notice and this permission notice shall be included
  23160. // in all copies or substantial portions of the Software.
  23161. //
  23162. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  23163. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23164. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  23165. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  23166. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  23167. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  23168. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  23169. // A bit simpler than readable streams.
  23170. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  23171. // the drain event emission and buffering.
  23172. 'use strict';
  23173. /*<replacement>*/
  23174. var processNextTick = require('process-nextick-args');
  23175. /*</replacement>*/
  23176. module.exports = Writable;
  23177. /* <replacement> */
  23178. function WriteReq(chunk, encoding, cb) {
  23179. this.chunk = chunk;
  23180. this.encoding = encoding;
  23181. this.callback = cb;
  23182. this.next = null;
  23183. }
  23184. // It seems a linked list but it is not
  23185. // there will be only 2 of these for each stream
  23186. function CorkedRequest(state) {
  23187. var _this = this;
  23188. this.next = null;
  23189. this.entry = null;
  23190. this.finish = function () {
  23191. onCorkedFinish(_this, state);
  23192. };
  23193. }
  23194. /* </replacement> */
  23195. /*<replacement>*/
  23196. var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
  23197. /*</replacement>*/
  23198. /*<replacement>*/
  23199. var Duplex;
  23200. /*</replacement>*/
  23201. Writable.WritableState = WritableState;
  23202. /*<replacement>*/
  23203. var util = require('core-util-is');
  23204. util.inherits = require('inherits');
  23205. /*</replacement>*/
  23206. /*<replacement>*/
  23207. var internalUtil = {
  23208. deprecate: require('util-deprecate')
  23209. };
  23210. /*</replacement>*/
  23211. /*<replacement>*/
  23212. var Stream = require('./internal/streams/stream');
  23213. /*</replacement>*/
  23214. /*<replacement>*/
  23215. var Buffer = require('safe-buffer').Buffer;
  23216. var OurUint8Array = global.Uint8Array || function () {};
  23217. function _uint8ArrayToBuffer(chunk) {
  23218. return Buffer.from(chunk);
  23219. }
  23220. function _isUint8Array(obj) {
  23221. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  23222. }
  23223. /*</replacement>*/
  23224. var destroyImpl = require('./internal/streams/destroy');
  23225. util.inherits(Writable, Stream);
  23226. function nop() {}
  23227. function WritableState(options, stream) {
  23228. Duplex = Duplex || require('./_stream_duplex');
  23229. options = options || {};
  23230. // object stream flag to indicate whether or not this stream
  23231. // contains buffers or objects.
  23232. this.objectMode = !!options.objectMode;
  23233. if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  23234. // the point at which write() starts returning false
  23235. // Note: 0 is a valid value, means that we always return false if
  23236. // the entire buffer is not flushed immediately on write()
  23237. var hwm = options.highWaterMark;
  23238. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  23239. this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
  23240. // cast to ints.
  23241. this.highWaterMark = Math.floor(this.highWaterMark);
  23242. // if _final has been called
  23243. this.finalCalled = false;
  23244. // drain event flag.
  23245. this.needDrain = false;
  23246. // at the start of calling end()
  23247. this.ending = false;
  23248. // when end() has been called, and returned
  23249. this.ended = false;
  23250. // when 'finish' is emitted
  23251. this.finished = false;
  23252. // has it been destroyed
  23253. this.destroyed = false;
  23254. // should we decode strings into buffers before passing to _write?
  23255. // this is here so that some node-core streams can optimize string
  23256. // handling at a lower level.
  23257. var noDecode = options.decodeStrings === false;
  23258. this.decodeStrings = !noDecode;
  23259. // Crypto is kind of old and crusty. Historically, its default string
  23260. // encoding is 'binary' so we have to make this configurable.
  23261. // Everything else in the universe uses 'utf8', though.
  23262. this.defaultEncoding = options.defaultEncoding || 'utf8';
  23263. // not an actual buffer we keep track of, but a measurement
  23264. // of how much we're waiting to get pushed to some underlying
  23265. // socket or file.
  23266. this.length = 0;
  23267. // a flag to see when we're in the middle of a write.
  23268. this.writing = false;
  23269. // when true all writes will be buffered until .uncork() call
  23270. this.corked = 0;
  23271. // a flag to be able to tell if the onwrite cb is called immediately,
  23272. // or on a later tick. We set this to true at first, because any
  23273. // actions that shouldn't happen until "later" should generally also
  23274. // not happen before the first write call.
  23275. this.sync = true;
  23276. // a flag to know if we're processing previously buffered items, which
  23277. // may call the _write() callback in the same tick, so that we don't
  23278. // end up in an overlapped onwrite situation.
  23279. this.bufferProcessing = false;
  23280. // the callback that's passed to _write(chunk,cb)
  23281. this.onwrite = function (er) {
  23282. onwrite(stream, er);
  23283. };
  23284. // the callback that the user supplies to write(chunk,encoding,cb)
  23285. this.writecb = null;
  23286. // the amount that is being written when _write is called.
  23287. this.writelen = 0;
  23288. this.bufferedRequest = null;
  23289. this.lastBufferedRequest = null;
  23290. // number of pending user-supplied write callbacks
  23291. // this must be 0 before 'finish' can be emitted
  23292. this.pendingcb = 0;
  23293. // emit prefinish if the only thing we're waiting for is _write cbs
  23294. // This is relevant for synchronous Transform streams
  23295. this.prefinished = false;
  23296. // True if the error was already emitted and should not be thrown again
  23297. this.errorEmitted = false;
  23298. // count buffered requests
  23299. this.bufferedRequestCount = 0;
  23300. // allocate the first CorkedRequest, there is always
  23301. // one allocated and free to use, and we maintain at most two
  23302. this.corkedRequestsFree = new CorkedRequest(this);
  23303. }
  23304. WritableState.prototype.getBuffer = function getBuffer() {
  23305. var current = this.bufferedRequest;
  23306. var out = [];
  23307. while (current) {
  23308. out.push(current);
  23309. current = current.next;
  23310. }
  23311. return out;
  23312. };
  23313. (function () {
  23314. try {
  23315. Object.defineProperty(WritableState.prototype, 'buffer', {
  23316. get: internalUtil.deprecate(function () {
  23317. return this.getBuffer();
  23318. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  23319. });
  23320. } catch (_) {}
  23321. })();
  23322. // Test _writableState for inheritance to account for Duplex streams,
  23323. // whose prototype chain only points to Readable.
  23324. var realHasInstance;
  23325. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  23326. realHasInstance = Function.prototype[Symbol.hasInstance];
  23327. Object.defineProperty(Writable, Symbol.hasInstance, {
  23328. value: function (object) {
  23329. if (realHasInstance.call(this, object)) return true;
  23330. return object && object._writableState instanceof WritableState;
  23331. }
  23332. });
  23333. } else {
  23334. realHasInstance = function (object) {
  23335. return object instanceof this;
  23336. };
  23337. }
  23338. function Writable(options) {
  23339. Duplex = Duplex || require('./_stream_duplex');
  23340. // Writable ctor is applied to Duplexes, too.
  23341. // `realHasInstance` is necessary because using plain `instanceof`
  23342. // would return false, as no `_writableState` property is attached.
  23343. // Trying to use the custom `instanceof` for Writable here will also break the
  23344. // Node.js LazyTransform implementation, which has a non-trivial getter for
  23345. // `_writableState` that would lead to infinite recursion.
  23346. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
  23347. return new Writable(options);
  23348. }
  23349. this._writableState = new WritableState(options, this);
  23350. // legacy.
  23351. this.writable = true;
  23352. if (options) {
  23353. if (typeof options.write === 'function') this._write = options.write;
  23354. if (typeof options.writev === 'function') this._writev = options.writev;
  23355. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  23356. if (typeof options.final === 'function') this._final = options.final;
  23357. }
  23358. Stream.call(this);
  23359. }
  23360. // Otherwise people can pipe Writable streams, which is just wrong.
  23361. Writable.prototype.pipe = function () {
  23362. this.emit('error', new Error('Cannot pipe, not readable'));
  23363. };
  23364. function writeAfterEnd(stream, cb) {
  23365. var er = new Error('write after end');
  23366. // TODO: defer error events consistently everywhere, not just the cb
  23367. stream.emit('error', er);
  23368. processNextTick(cb, er);
  23369. }
  23370. // Checks that a user-supplied chunk is valid, especially for the particular
  23371. // mode the stream is in. Currently this means that `null` is never accepted
  23372. // and undefined/non-string values are only allowed in object mode.
  23373. function validChunk(stream, state, chunk, cb) {
  23374. var valid = true;
  23375. var er = false;
  23376. if (chunk === null) {
  23377. er = new TypeError('May not write null values to stream');
  23378. } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  23379. er = new TypeError('Invalid non-string/buffer chunk');
  23380. }
  23381. if (er) {
  23382. stream.emit('error', er);
  23383. processNextTick(cb, er);
  23384. valid = false;
  23385. }
  23386. return valid;
  23387. }
  23388. Writable.prototype.write = function (chunk, encoding, cb) {
  23389. var state = this._writableState;
  23390. var ret = false;
  23391. var isBuf = _isUint8Array(chunk) && !state.objectMode;
  23392. if (isBuf && !Buffer.isBuffer(chunk)) {
  23393. chunk = _uint8ArrayToBuffer(chunk);
  23394. }
  23395. if (typeof encoding === 'function') {
  23396. cb = encoding;
  23397. encoding = null;
  23398. }
  23399. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  23400. if (typeof cb !== 'function') cb = nop;
  23401. if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  23402. state.pendingcb++;
  23403. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  23404. }
  23405. return ret;
  23406. };
  23407. Writable.prototype.cork = function () {
  23408. var state = this._writableState;
  23409. state.corked++;
  23410. };
  23411. Writable.prototype.uncork = function () {
  23412. var state = this._writableState;
  23413. if (state.corked) {
  23414. state.corked--;
  23415. if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  23416. }
  23417. };
  23418. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  23419. // node::ParseEncoding() requires lower case.
  23420. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  23421. if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
  23422. this._writableState.defaultEncoding = encoding;
  23423. return this;
  23424. };
  23425. function decodeChunk(state, chunk, encoding) {
  23426. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  23427. chunk = Buffer.from(chunk, encoding);
  23428. }
  23429. return chunk;
  23430. }
  23431. // if we're already writing something, then just put this
  23432. // in the queue, and wait our turn. Otherwise, call _write
  23433. // If we return false, then we need a drain event, so set that flag.
  23434. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  23435. if (!isBuf) {
  23436. var newChunk = decodeChunk(state, chunk, encoding);
  23437. if (chunk !== newChunk) {
  23438. isBuf = true;
  23439. encoding = 'buffer';
  23440. chunk = newChunk;
  23441. }
  23442. }
  23443. var len = state.objectMode ? 1 : chunk.length;
  23444. state.length += len;
  23445. var ret = state.length < state.highWaterMark;
  23446. // we must ensure that previous needDrain will not be reset to false.
  23447. if (!ret) state.needDrain = true;
  23448. if (state.writing || state.corked) {
  23449. var last = state.lastBufferedRequest;
  23450. state.lastBufferedRequest = {
  23451. chunk: chunk,
  23452. encoding: encoding,
  23453. isBuf: isBuf,
  23454. callback: cb,
  23455. next: null
  23456. };
  23457. if (last) {
  23458. last.next = state.lastBufferedRequest;
  23459. } else {
  23460. state.bufferedRequest = state.lastBufferedRequest;
  23461. }
  23462. state.bufferedRequestCount += 1;
  23463. } else {
  23464. doWrite(stream, state, false, len, chunk, encoding, cb);
  23465. }
  23466. return ret;
  23467. }
  23468. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  23469. state.writelen = len;
  23470. state.writecb = cb;
  23471. state.writing = true;
  23472. state.sync = true;
  23473. if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  23474. state.sync = false;
  23475. }
  23476. function onwriteError(stream, state, sync, er, cb) {
  23477. --state.pendingcb;
  23478. if (sync) {
  23479. // defer the callback if we are being called synchronously
  23480. // to avoid piling up things on the stack
  23481. processNextTick(cb, er);
  23482. // this can emit finish, and it will always happen
  23483. // after error
  23484. processNextTick(finishMaybe, stream, state);
  23485. stream._writableState.errorEmitted = true;
  23486. stream.emit('error', er);
  23487. } else {
  23488. // the caller expect this to happen before if
  23489. // it is async
  23490. cb(er);
  23491. stream._writableState.errorEmitted = true;
  23492. stream.emit('error', er);
  23493. // this can emit finish, but finish must
  23494. // always follow error
  23495. finishMaybe(stream, state);
  23496. }
  23497. }
  23498. function onwriteStateUpdate(state) {
  23499. state.writing = false;
  23500. state.writecb = null;
  23501. state.length -= state.writelen;
  23502. state.writelen = 0;
  23503. }
  23504. function onwrite(stream, er) {
  23505. var state = stream._writableState;
  23506. var sync = state.sync;
  23507. var cb = state.writecb;
  23508. onwriteStateUpdate(state);
  23509. if (er) onwriteError(stream, state, sync, er, cb);else {
  23510. // Check if we're actually ready to finish, but don't emit yet
  23511. var finished = needFinish(state);
  23512. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  23513. clearBuffer(stream, state);
  23514. }
  23515. if (sync) {
  23516. /*<replacement>*/
  23517. asyncWrite(afterWrite, stream, state, finished, cb);
  23518. /*</replacement>*/
  23519. } else {
  23520. afterWrite(stream, state, finished, cb);
  23521. }
  23522. }
  23523. }
  23524. function afterWrite(stream, state, finished, cb) {
  23525. if (!finished) onwriteDrain(stream, state);
  23526. state.pendingcb--;
  23527. cb();
  23528. finishMaybe(stream, state);
  23529. }
  23530. // Must force callback to be called on nextTick, so that we don't
  23531. // emit 'drain' before the write() consumer gets the 'false' return
  23532. // value, and has a chance to attach a 'drain' listener.
  23533. function onwriteDrain(stream, state) {
  23534. if (state.length === 0 && state.needDrain) {
  23535. state.needDrain = false;
  23536. stream.emit('drain');
  23537. }
  23538. }
  23539. // if there's something in the buffer waiting, then process it
  23540. function clearBuffer(stream, state) {
  23541. state.bufferProcessing = true;
  23542. var entry = state.bufferedRequest;
  23543. if (stream._writev && entry && entry.next) {
  23544. // Fast case, write everything using _writev()
  23545. var l = state.bufferedRequestCount;
  23546. var buffer = new Array(l);
  23547. var holder = state.corkedRequestsFree;
  23548. holder.entry = entry;
  23549. var count = 0;
  23550. var allBuffers = true;
  23551. while (entry) {
  23552. buffer[count] = entry;
  23553. if (!entry.isBuf) allBuffers = false;
  23554. entry = entry.next;
  23555. count += 1;
  23556. }
  23557. buffer.allBuffers = allBuffers;
  23558. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  23559. // doWrite is almost always async, defer these to save a bit of time
  23560. // as the hot path ends with doWrite
  23561. state.pendingcb++;
  23562. state.lastBufferedRequest = null;
  23563. if (holder.next) {
  23564. state.corkedRequestsFree = holder.next;
  23565. holder.next = null;
  23566. } else {
  23567. state.corkedRequestsFree = new CorkedRequest(state);
  23568. }
  23569. } else {
  23570. // Slow case, write chunks one-by-one
  23571. while (entry) {
  23572. var chunk = entry.chunk;
  23573. var encoding = entry.encoding;
  23574. var cb = entry.callback;
  23575. var len = state.objectMode ? 1 : chunk.length;
  23576. doWrite(stream, state, false, len, chunk, encoding, cb);
  23577. entry = entry.next;
  23578. // if we didn't call the onwrite immediately, then
  23579. // it means that we need to wait until it does.
  23580. // also, that means that the chunk and cb are currently
  23581. // being processed, so move the buffer counter past them.
  23582. if (state.writing) {
  23583. break;
  23584. }
  23585. }
  23586. if (entry === null) state.lastBufferedRequest = null;
  23587. }
  23588. state.bufferedRequestCount = 0;
  23589. state.bufferedRequest = entry;
  23590. state.bufferProcessing = false;
  23591. }
  23592. Writable.prototype._write = function (chunk, encoding, cb) {
  23593. cb(new Error('_write() is not implemented'));
  23594. };
  23595. Writable.prototype._writev = null;
  23596. Writable.prototype.end = function (chunk, encoding, cb) {
  23597. var state = this._writableState;
  23598. if (typeof chunk === 'function') {
  23599. cb = chunk;
  23600. chunk = null;
  23601. encoding = null;
  23602. } else if (typeof encoding === 'function') {
  23603. cb = encoding;
  23604. encoding = null;
  23605. }
  23606. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  23607. // .end() fully uncorks
  23608. if (state.corked) {
  23609. state.corked = 1;
  23610. this.uncork();
  23611. }
  23612. // ignore unnecessary end() calls.
  23613. if (!state.ending && !state.finished) endWritable(this, state, cb);
  23614. };
  23615. function needFinish(state) {
  23616. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  23617. }
  23618. function callFinal(stream, state) {
  23619. stream._final(function (err) {
  23620. state.pendingcb--;
  23621. if (err) {
  23622. stream.emit('error', err);
  23623. }
  23624. state.prefinished = true;
  23625. stream.emit('prefinish');
  23626. finishMaybe(stream, state);
  23627. });
  23628. }
  23629. function prefinish(stream, state) {
  23630. if (!state.prefinished && !state.finalCalled) {
  23631. if (typeof stream._final === 'function') {
  23632. state.pendingcb++;
  23633. state.finalCalled = true;
  23634. processNextTick(callFinal, stream, state);
  23635. } else {
  23636. state.prefinished = true;
  23637. stream.emit('prefinish');
  23638. }
  23639. }
  23640. }
  23641. function finishMaybe(stream, state) {
  23642. var need = needFinish(state);
  23643. if (need) {
  23644. prefinish(stream, state);
  23645. if (state.pendingcb === 0) {
  23646. state.finished = true;
  23647. stream.emit('finish');
  23648. }
  23649. }
  23650. return need;
  23651. }
  23652. function endWritable(stream, state, cb) {
  23653. state.ending = true;
  23654. finishMaybe(stream, state);
  23655. if (cb) {
  23656. if (state.finished) processNextTick(cb);else stream.once('finish', cb);
  23657. }
  23658. state.ended = true;
  23659. stream.writable = false;
  23660. }
  23661. function onCorkedFinish(corkReq, state, err) {
  23662. var entry = corkReq.entry;
  23663. corkReq.entry = null;
  23664. while (entry) {
  23665. var cb = entry.callback;
  23666. state.pendingcb--;
  23667. cb(err);
  23668. entry = entry.next;
  23669. }
  23670. if (state.corkedRequestsFree) {
  23671. state.corkedRequestsFree.next = corkReq;
  23672. } else {
  23673. state.corkedRequestsFree = corkReq;
  23674. }
  23675. }
  23676. Object.defineProperty(Writable.prototype, 'destroyed', {
  23677. get: function () {
  23678. if (this._writableState === undefined) {
  23679. return false;
  23680. }
  23681. return this._writableState.destroyed;
  23682. },
  23683. set: function (value) {
  23684. // we ignore the value if the stream
  23685. // has not been initialized yet
  23686. if (!this._writableState) {
  23687. return;
  23688. }
  23689. // backward compatibility, the user is explicitly
  23690. // managing destroyed
  23691. this._writableState.destroyed = value;
  23692. }
  23693. });
  23694. Writable.prototype.destroy = destroyImpl.destroy;
  23695. Writable.prototype._undestroy = destroyImpl.undestroy;
  23696. Writable.prototype._destroy = function (err, cb) {
  23697. this.end();
  23698. cb(err);
  23699. };
  23700. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  23701. },{"./_stream_duplex":144,"./internal/streams/destroy":150,"./internal/streams/stream":151,"_process":134,"core-util-is":52,"inherits":104,"process-nextick-args":133,"safe-buffer":157,"util-deprecate":168}],149:[function(require,module,exports){
  23702. 'use strict';
  23703. /*<replacement>*/
  23704. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  23705. var Buffer = require('safe-buffer').Buffer;
  23706. /*</replacement>*/
  23707. function copyBuffer(src, target, offset) {
  23708. src.copy(target, offset);
  23709. }
  23710. module.exports = function () {
  23711. function BufferList() {
  23712. _classCallCheck(this, BufferList);
  23713. this.head = null;
  23714. this.tail = null;
  23715. this.length = 0;
  23716. }
  23717. BufferList.prototype.push = function push(v) {
  23718. var entry = { data: v, next: null };
  23719. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  23720. this.tail = entry;
  23721. ++this.length;
  23722. };
  23723. BufferList.prototype.unshift = function unshift(v) {
  23724. var entry = { data: v, next: this.head };
  23725. if (this.length === 0) this.tail = entry;
  23726. this.head = entry;
  23727. ++this.length;
  23728. };
  23729. BufferList.prototype.shift = function shift() {
  23730. if (this.length === 0) return;
  23731. var ret = this.head.data;
  23732. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  23733. --this.length;
  23734. return ret;
  23735. };
  23736. BufferList.prototype.clear = function clear() {
  23737. this.head = this.tail = null;
  23738. this.length = 0;
  23739. };
  23740. BufferList.prototype.join = function join(s) {
  23741. if (this.length === 0) return '';
  23742. var p = this.head;
  23743. var ret = '' + p.data;
  23744. while (p = p.next) {
  23745. ret += s + p.data;
  23746. }return ret;
  23747. };
  23748. BufferList.prototype.concat = function concat(n) {
  23749. if (this.length === 0) return Buffer.alloc(0);
  23750. if (this.length === 1) return this.head.data;
  23751. var ret = Buffer.allocUnsafe(n >>> 0);
  23752. var p = this.head;
  23753. var i = 0;
  23754. while (p) {
  23755. copyBuffer(p.data, ret, i);
  23756. i += p.data.length;
  23757. p = p.next;
  23758. }
  23759. return ret;
  23760. };
  23761. return BufferList;
  23762. }();
  23763. },{"safe-buffer":157}],150:[function(require,module,exports){
  23764. 'use strict';
  23765. /*<replacement>*/
  23766. var processNextTick = require('process-nextick-args');
  23767. /*</replacement>*/
  23768. // undocumented cb() API, needed for core, not for public API
  23769. function destroy(err, cb) {
  23770. var _this = this;
  23771. var readableDestroyed = this._readableState && this._readableState.destroyed;
  23772. var writableDestroyed = this._writableState && this._writableState.destroyed;
  23773. if (readableDestroyed || writableDestroyed) {
  23774. if (cb) {
  23775. cb(err);
  23776. } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
  23777. processNextTick(emitErrorNT, this, err);
  23778. }
  23779. return;
  23780. }
  23781. // we set destroyed to true before firing error callbacks in order
  23782. // to make it re-entrance safe in case destroy() is called within callbacks
  23783. if (this._readableState) {
  23784. this._readableState.destroyed = true;
  23785. }
  23786. // if this is a duplex stream mark the writable part as destroyed as well
  23787. if (this._writableState) {
  23788. this._writableState.destroyed = true;
  23789. }
  23790. this._destroy(err || null, function (err) {
  23791. if (!cb && err) {
  23792. processNextTick(emitErrorNT, _this, err);
  23793. if (_this._writableState) {
  23794. _this._writableState.errorEmitted = true;
  23795. }
  23796. } else if (cb) {
  23797. cb(err);
  23798. }
  23799. });
  23800. }
  23801. function undestroy() {
  23802. if (this._readableState) {
  23803. this._readableState.destroyed = false;
  23804. this._readableState.reading = false;
  23805. this._readableState.ended = false;
  23806. this._readableState.endEmitted = false;
  23807. }
  23808. if (this._writableState) {
  23809. this._writableState.destroyed = false;
  23810. this._writableState.ended = false;
  23811. this._writableState.ending = false;
  23812. this._writableState.finished = false;
  23813. this._writableState.errorEmitted = false;
  23814. }
  23815. }
  23816. function emitErrorNT(self, err) {
  23817. self.emit('error', err);
  23818. }
  23819. module.exports = {
  23820. destroy: destroy,
  23821. undestroy: undestroy
  23822. };
  23823. },{"process-nextick-args":133}],151:[function(require,module,exports){
  23824. module.exports = require('events').EventEmitter;
  23825. },{"events":86}],152:[function(require,module,exports){
  23826. module.exports = require('./readable').PassThrough
  23827. },{"./readable":153}],153:[function(require,module,exports){
  23828. exports = module.exports = require('./lib/_stream_readable.js');
  23829. exports.Stream = exports;
  23830. exports.Readable = exports;
  23831. exports.Writable = require('./lib/_stream_writable.js');
  23832. exports.Duplex = require('./lib/_stream_duplex.js');
  23833. exports.Transform = require('./lib/_stream_transform.js');
  23834. exports.PassThrough = require('./lib/_stream_passthrough.js');
  23835. },{"./lib/_stream_duplex.js":144,"./lib/_stream_passthrough.js":145,"./lib/_stream_readable.js":146,"./lib/_stream_transform.js":147,"./lib/_stream_writable.js":148}],154:[function(require,module,exports){
  23836. module.exports = require('./readable').Transform
  23837. },{"./readable":153}],155:[function(require,module,exports){
  23838. module.exports = require('./lib/_stream_writable.js');
  23839. },{"./lib/_stream_writable.js":148}],156:[function(require,module,exports){
  23840. (function (Buffer){
  23841. 'use strict'
  23842. var inherits = require('inherits')
  23843. var HashBase = require('hash-base')
  23844. function RIPEMD160 () {
  23845. HashBase.call(this, 64)
  23846. // state
  23847. this._a = 0x67452301
  23848. this._b = 0xefcdab89
  23849. this._c = 0x98badcfe
  23850. this._d = 0x10325476
  23851. this._e = 0xc3d2e1f0
  23852. }
  23853. inherits(RIPEMD160, HashBase)
  23854. RIPEMD160.prototype._update = function () {
  23855. var m = new Array(16)
  23856. for (var i = 0; i < 16; ++i) m[i] = this._block.readInt32LE(i * 4)
  23857. var al = this._a
  23858. var bl = this._b
  23859. var cl = this._c
  23860. var dl = this._d
  23861. var el = this._e
  23862. // Mj = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
  23863. // K = 0x00000000
  23864. // Sj = 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8
  23865. al = fn1(al, bl, cl, dl, el, m[0], 0x00000000, 11); cl = rotl(cl, 10)
  23866. el = fn1(el, al, bl, cl, dl, m[1], 0x00000000, 14); bl = rotl(bl, 10)
  23867. dl = fn1(dl, el, al, bl, cl, m[2], 0x00000000, 15); al = rotl(al, 10)
  23868. cl = fn1(cl, dl, el, al, bl, m[3], 0x00000000, 12); el = rotl(el, 10)
  23869. bl = fn1(bl, cl, dl, el, al, m[4], 0x00000000, 5); dl = rotl(dl, 10)
  23870. al = fn1(al, bl, cl, dl, el, m[5], 0x00000000, 8); cl = rotl(cl, 10)
  23871. el = fn1(el, al, bl, cl, dl, m[6], 0x00000000, 7); bl = rotl(bl, 10)
  23872. dl = fn1(dl, el, al, bl, cl, m[7], 0x00000000, 9); al = rotl(al, 10)
  23873. cl = fn1(cl, dl, el, al, bl, m[8], 0x00000000, 11); el = rotl(el, 10)
  23874. bl = fn1(bl, cl, dl, el, al, m[9], 0x00000000, 13); dl = rotl(dl, 10)
  23875. al = fn1(al, bl, cl, dl, el, m[10], 0x00000000, 14); cl = rotl(cl, 10)
  23876. el = fn1(el, al, bl, cl, dl, m[11], 0x00000000, 15); bl = rotl(bl, 10)
  23877. dl = fn1(dl, el, al, bl, cl, m[12], 0x00000000, 6); al = rotl(al, 10)
  23878. cl = fn1(cl, dl, el, al, bl, m[13], 0x00000000, 7); el = rotl(el, 10)
  23879. bl = fn1(bl, cl, dl, el, al, m[14], 0x00000000, 9); dl = rotl(dl, 10)
  23880. al = fn1(al, bl, cl, dl, el, m[15], 0x00000000, 8); cl = rotl(cl, 10)
  23881. // Mj = 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8
  23882. // K = 0x5a827999
  23883. // Sj = 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12
  23884. el = fn2(el, al, bl, cl, dl, m[7], 0x5a827999, 7); bl = rotl(bl, 10)
  23885. dl = fn2(dl, el, al, bl, cl, m[4], 0x5a827999, 6); al = rotl(al, 10)
  23886. cl = fn2(cl, dl, el, al, bl, m[13], 0x5a827999, 8); el = rotl(el, 10)
  23887. bl = fn2(bl, cl, dl, el, al, m[1], 0x5a827999, 13); dl = rotl(dl, 10)
  23888. al = fn2(al, bl, cl, dl, el, m[10], 0x5a827999, 11); cl = rotl(cl, 10)
  23889. el = fn2(el, al, bl, cl, dl, m[6], 0x5a827999, 9); bl = rotl(bl, 10)
  23890. dl = fn2(dl, el, al, bl, cl, m[15], 0x5a827999, 7); al = rotl(al, 10)
  23891. cl = fn2(cl, dl, el, al, bl, m[3], 0x5a827999, 15); el = rotl(el, 10)
  23892. bl = fn2(bl, cl, dl, el, al, m[12], 0x5a827999, 7); dl = rotl(dl, 10)
  23893. al = fn2(al, bl, cl, dl, el, m[0], 0x5a827999, 12); cl = rotl(cl, 10)
  23894. el = fn2(el, al, bl, cl, dl, m[9], 0x5a827999, 15); bl = rotl(bl, 10)
  23895. dl = fn2(dl, el, al, bl, cl, m[5], 0x5a827999, 9); al = rotl(al, 10)
  23896. cl = fn2(cl, dl, el, al, bl, m[2], 0x5a827999, 11); el = rotl(el, 10)
  23897. bl = fn2(bl, cl, dl, el, al, m[14], 0x5a827999, 7); dl = rotl(dl, 10)
  23898. al = fn2(al, bl, cl, dl, el, m[11], 0x5a827999, 13); cl = rotl(cl, 10)
  23899. el = fn2(el, al, bl, cl, dl, m[8], 0x5a827999, 12); bl = rotl(bl, 10)
  23900. // Mj = 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12
  23901. // K = 0x6ed9eba1
  23902. // Sj = 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5
  23903. dl = fn3(dl, el, al, bl, cl, m[3], 0x6ed9eba1, 11); al = rotl(al, 10)
  23904. cl = fn3(cl, dl, el, al, bl, m[10], 0x6ed9eba1, 13); el = rotl(el, 10)
  23905. bl = fn3(bl, cl, dl, el, al, m[14], 0x6ed9eba1, 6); dl = rotl(dl, 10)
  23906. al = fn3(al, bl, cl, dl, el, m[4], 0x6ed9eba1, 7); cl = rotl(cl, 10)
  23907. el = fn3(el, al, bl, cl, dl, m[9], 0x6ed9eba1, 14); bl = rotl(bl, 10)
  23908. dl = fn3(dl, el, al, bl, cl, m[15], 0x6ed9eba1, 9); al = rotl(al, 10)
  23909. cl = fn3(cl, dl, el, al, bl, m[8], 0x6ed9eba1, 13); el = rotl(el, 10)
  23910. bl = fn3(bl, cl, dl, el, al, m[1], 0x6ed9eba1, 15); dl = rotl(dl, 10)
  23911. al = fn3(al, bl, cl, dl, el, m[2], 0x6ed9eba1, 14); cl = rotl(cl, 10)
  23912. el = fn3(el, al, bl, cl, dl, m[7], 0x6ed9eba1, 8); bl = rotl(bl, 10)
  23913. dl = fn3(dl, el, al, bl, cl, m[0], 0x6ed9eba1, 13); al = rotl(al, 10)
  23914. cl = fn3(cl, dl, el, al, bl, m[6], 0x6ed9eba1, 6); el = rotl(el, 10)
  23915. bl = fn3(bl, cl, dl, el, al, m[13], 0x6ed9eba1, 5); dl = rotl(dl, 10)
  23916. al = fn3(al, bl, cl, dl, el, m[11], 0x6ed9eba1, 12); cl = rotl(cl, 10)
  23917. el = fn3(el, al, bl, cl, dl, m[5], 0x6ed9eba1, 7); bl = rotl(bl, 10)
  23918. dl = fn3(dl, el, al, bl, cl, m[12], 0x6ed9eba1, 5); al = rotl(al, 10)
  23919. // Mj = 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2
  23920. // K = 0x8f1bbcdc
  23921. // Sj = 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12
  23922. cl = fn4(cl, dl, el, al, bl, m[1], 0x8f1bbcdc, 11); el = rotl(el, 10)
  23923. bl = fn4(bl, cl, dl, el, al, m[9], 0x8f1bbcdc, 12); dl = rotl(dl, 10)
  23924. al = fn4(al, bl, cl, dl, el, m[11], 0x8f1bbcdc, 14); cl = rotl(cl, 10)
  23925. el = fn4(el, al, bl, cl, dl, m[10], 0x8f1bbcdc, 15); bl = rotl(bl, 10)
  23926. dl = fn4(dl, el, al, bl, cl, m[0], 0x8f1bbcdc, 14); al = rotl(al, 10)
  23927. cl = fn4(cl, dl, el, al, bl, m[8], 0x8f1bbcdc, 15); el = rotl(el, 10)
  23928. bl = fn4(bl, cl, dl, el, al, m[12], 0x8f1bbcdc, 9); dl = rotl(dl, 10)
  23929. al = fn4(al, bl, cl, dl, el, m[4], 0x8f1bbcdc, 8); cl = rotl(cl, 10)
  23930. el = fn4(el, al, bl, cl, dl, m[13], 0x8f1bbcdc, 9); bl = rotl(bl, 10)
  23931. dl = fn4(dl, el, al, bl, cl, m[3], 0x8f1bbcdc, 14); al = rotl(al, 10)
  23932. cl = fn4(cl, dl, el, al, bl, m[7], 0x8f1bbcdc, 5); el = rotl(el, 10)
  23933. bl = fn4(bl, cl, dl, el, al, m[15], 0x8f1bbcdc, 6); dl = rotl(dl, 10)
  23934. al = fn4(al, bl, cl, dl, el, m[14], 0x8f1bbcdc, 8); cl = rotl(cl, 10)
  23935. el = fn4(el, al, bl, cl, dl, m[5], 0x8f1bbcdc, 6); bl = rotl(bl, 10)
  23936. dl = fn4(dl, el, al, bl, cl, m[6], 0x8f1bbcdc, 5); al = rotl(al, 10)
  23937. cl = fn4(cl, dl, el, al, bl, m[2], 0x8f1bbcdc, 12); el = rotl(el, 10)
  23938. // Mj = 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
  23939. // K = 0xa953fd4e
  23940. // Sj = 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
  23941. bl = fn5(bl, cl, dl, el, al, m[4], 0xa953fd4e, 9); dl = rotl(dl, 10)
  23942. al = fn5(al, bl, cl, dl, el, m[0], 0xa953fd4e, 15); cl = rotl(cl, 10)
  23943. el = fn5(el, al, bl, cl, dl, m[5], 0xa953fd4e, 5); bl = rotl(bl, 10)
  23944. dl = fn5(dl, el, al, bl, cl, m[9], 0xa953fd4e, 11); al = rotl(al, 10)
  23945. cl = fn5(cl, dl, el, al, bl, m[7], 0xa953fd4e, 6); el = rotl(el, 10)
  23946. bl = fn5(bl, cl, dl, el, al, m[12], 0xa953fd4e, 8); dl = rotl(dl, 10)
  23947. al = fn5(al, bl, cl, dl, el, m[2], 0xa953fd4e, 13); cl = rotl(cl, 10)
  23948. el = fn5(el, al, bl, cl, dl, m[10], 0xa953fd4e, 12); bl = rotl(bl, 10)
  23949. dl = fn5(dl, el, al, bl, cl, m[14], 0xa953fd4e, 5); al = rotl(al, 10)
  23950. cl = fn5(cl, dl, el, al, bl, m[1], 0xa953fd4e, 12); el = rotl(el, 10)
  23951. bl = fn5(bl, cl, dl, el, al, m[3], 0xa953fd4e, 13); dl = rotl(dl, 10)
  23952. al = fn5(al, bl, cl, dl, el, m[8], 0xa953fd4e, 14); cl = rotl(cl, 10)
  23953. el = fn5(el, al, bl, cl, dl, m[11], 0xa953fd4e, 11); bl = rotl(bl, 10)
  23954. dl = fn5(dl, el, al, bl, cl, m[6], 0xa953fd4e, 8); al = rotl(al, 10)
  23955. cl = fn5(cl, dl, el, al, bl, m[15], 0xa953fd4e, 5); el = rotl(el, 10)
  23956. bl = fn5(bl, cl, dl, el, al, m[13], 0xa953fd4e, 6); dl = rotl(dl, 10)
  23957. var ar = this._a
  23958. var br = this._b
  23959. var cr = this._c
  23960. var dr = this._d
  23961. var er = this._e
  23962. // M'j = 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12
  23963. // K' = 0x50a28be6
  23964. // S'j = 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6
  23965. ar = fn5(ar, br, cr, dr, er, m[5], 0x50a28be6, 8); cr = rotl(cr, 10)
  23966. er = fn5(er, ar, br, cr, dr, m[14], 0x50a28be6, 9); br = rotl(br, 10)
  23967. dr = fn5(dr, er, ar, br, cr, m[7], 0x50a28be6, 9); ar = rotl(ar, 10)
  23968. cr = fn5(cr, dr, er, ar, br, m[0], 0x50a28be6, 11); er = rotl(er, 10)
  23969. br = fn5(br, cr, dr, er, ar, m[9], 0x50a28be6, 13); dr = rotl(dr, 10)
  23970. ar = fn5(ar, br, cr, dr, er, m[2], 0x50a28be6, 15); cr = rotl(cr, 10)
  23971. er = fn5(er, ar, br, cr, dr, m[11], 0x50a28be6, 15); br = rotl(br, 10)
  23972. dr = fn5(dr, er, ar, br, cr, m[4], 0x50a28be6, 5); ar = rotl(ar, 10)
  23973. cr = fn5(cr, dr, er, ar, br, m[13], 0x50a28be6, 7); er = rotl(er, 10)
  23974. br = fn5(br, cr, dr, er, ar, m[6], 0x50a28be6, 7); dr = rotl(dr, 10)
  23975. ar = fn5(ar, br, cr, dr, er, m[15], 0x50a28be6, 8); cr = rotl(cr, 10)
  23976. er = fn5(er, ar, br, cr, dr, m[8], 0x50a28be6, 11); br = rotl(br, 10)
  23977. dr = fn5(dr, er, ar, br, cr, m[1], 0x50a28be6, 14); ar = rotl(ar, 10)
  23978. cr = fn5(cr, dr, er, ar, br, m[10], 0x50a28be6, 14); er = rotl(er, 10)
  23979. br = fn5(br, cr, dr, er, ar, m[3], 0x50a28be6, 12); dr = rotl(dr, 10)
  23980. ar = fn5(ar, br, cr, dr, er, m[12], 0x50a28be6, 6); cr = rotl(cr, 10)
  23981. // M'j = 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2
  23982. // K' = 0x5c4dd124
  23983. // S'j = 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11
  23984. er = fn4(er, ar, br, cr, dr, m[6], 0x5c4dd124, 9); br = rotl(br, 10)
  23985. dr = fn4(dr, er, ar, br, cr, m[11], 0x5c4dd124, 13); ar = rotl(ar, 10)
  23986. cr = fn4(cr, dr, er, ar, br, m[3], 0x5c4dd124, 15); er = rotl(er, 10)
  23987. br = fn4(br, cr, dr, er, ar, m[7], 0x5c4dd124, 7); dr = rotl(dr, 10)
  23988. ar = fn4(ar, br, cr, dr, er, m[0], 0x5c4dd124, 12); cr = rotl(cr, 10)
  23989. er = fn4(er, ar, br, cr, dr, m[13], 0x5c4dd124, 8); br = rotl(br, 10)
  23990. dr = fn4(dr, er, ar, br, cr, m[5], 0x5c4dd124, 9); ar = rotl(ar, 10)
  23991. cr = fn4(cr, dr, er, ar, br, m[10], 0x5c4dd124, 11); er = rotl(er, 10)
  23992. br = fn4(br, cr, dr, er, ar, m[14], 0x5c4dd124, 7); dr = rotl(dr, 10)
  23993. ar = fn4(ar, br, cr, dr, er, m[15], 0x5c4dd124, 7); cr = rotl(cr, 10)
  23994. er = fn4(er, ar, br, cr, dr, m[8], 0x5c4dd124, 12); br = rotl(br, 10)
  23995. dr = fn4(dr, er, ar, br, cr, m[12], 0x5c4dd124, 7); ar = rotl(ar, 10)
  23996. cr = fn4(cr, dr, er, ar, br, m[4], 0x5c4dd124, 6); er = rotl(er, 10)
  23997. br = fn4(br, cr, dr, er, ar, m[9], 0x5c4dd124, 15); dr = rotl(dr, 10)
  23998. ar = fn4(ar, br, cr, dr, er, m[1], 0x5c4dd124, 13); cr = rotl(cr, 10)
  23999. er = fn4(er, ar, br, cr, dr, m[2], 0x5c4dd124, 11); br = rotl(br, 10)
  24000. // M'j = 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13
  24001. // K' = 0x6d703ef3
  24002. // S'j = 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5
  24003. dr = fn3(dr, er, ar, br, cr, m[15], 0x6d703ef3, 9); ar = rotl(ar, 10)
  24004. cr = fn3(cr, dr, er, ar, br, m[5], 0x6d703ef3, 7); er = rotl(er, 10)
  24005. br = fn3(br, cr, dr, er, ar, m[1], 0x6d703ef3, 15); dr = rotl(dr, 10)
  24006. ar = fn3(ar, br, cr, dr, er, m[3], 0x6d703ef3, 11); cr = rotl(cr, 10)
  24007. er = fn3(er, ar, br, cr, dr, m[7], 0x6d703ef3, 8); br = rotl(br, 10)
  24008. dr = fn3(dr, er, ar, br, cr, m[14], 0x6d703ef3, 6); ar = rotl(ar, 10)
  24009. cr = fn3(cr, dr, er, ar, br, m[6], 0x6d703ef3, 6); er = rotl(er, 10)
  24010. br = fn3(br, cr, dr, er, ar, m[9], 0x6d703ef3, 14); dr = rotl(dr, 10)
  24011. ar = fn3(ar, br, cr, dr, er, m[11], 0x6d703ef3, 12); cr = rotl(cr, 10)
  24012. er = fn3(er, ar, br, cr, dr, m[8], 0x6d703ef3, 13); br = rotl(br, 10)
  24013. dr = fn3(dr, er, ar, br, cr, m[12], 0x6d703ef3, 5); ar = rotl(ar, 10)
  24014. cr = fn3(cr, dr, er, ar, br, m[2], 0x6d703ef3, 14); er = rotl(er, 10)
  24015. br = fn3(br, cr, dr, er, ar, m[10], 0x6d703ef3, 13); dr = rotl(dr, 10)
  24016. ar = fn3(ar, br, cr, dr, er, m[0], 0x6d703ef3, 13); cr = rotl(cr, 10)
  24017. er = fn3(er, ar, br, cr, dr, m[4], 0x6d703ef3, 7); br = rotl(br, 10)
  24018. dr = fn3(dr, er, ar, br, cr, m[13], 0x6d703ef3, 5); ar = rotl(ar, 10)
  24019. // M'j = 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14
  24020. // K' = 0x7a6d76e9
  24021. // S'j = 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8
  24022. cr = fn2(cr, dr, er, ar, br, m[8], 0x7a6d76e9, 15); er = rotl(er, 10)
  24023. br = fn2(br, cr, dr, er, ar, m[6], 0x7a6d76e9, 5); dr = rotl(dr, 10)
  24024. ar = fn2(ar, br, cr, dr, er, m[4], 0x7a6d76e9, 8); cr = rotl(cr, 10)
  24025. er = fn2(er, ar, br, cr, dr, m[1], 0x7a6d76e9, 11); br = rotl(br, 10)
  24026. dr = fn2(dr, er, ar, br, cr, m[3], 0x7a6d76e9, 14); ar = rotl(ar, 10)
  24027. cr = fn2(cr, dr, er, ar, br, m[11], 0x7a6d76e9, 14); er = rotl(er, 10)
  24028. br = fn2(br, cr, dr, er, ar, m[15], 0x7a6d76e9, 6); dr = rotl(dr, 10)
  24029. ar = fn2(ar, br, cr, dr, er, m[0], 0x7a6d76e9, 14); cr = rotl(cr, 10)
  24030. er = fn2(er, ar, br, cr, dr, m[5], 0x7a6d76e9, 6); br = rotl(br, 10)
  24031. dr = fn2(dr, er, ar, br, cr, m[12], 0x7a6d76e9, 9); ar = rotl(ar, 10)
  24032. cr = fn2(cr, dr, er, ar, br, m[2], 0x7a6d76e9, 12); er = rotl(er, 10)
  24033. br = fn2(br, cr, dr, er, ar, m[13], 0x7a6d76e9, 9); dr = rotl(dr, 10)
  24034. ar = fn2(ar, br, cr, dr, er, m[9], 0x7a6d76e9, 12); cr = rotl(cr, 10)
  24035. er = fn2(er, ar, br, cr, dr, m[7], 0x7a6d76e9, 5); br = rotl(br, 10)
  24036. dr = fn2(dr, er, ar, br, cr, m[10], 0x7a6d76e9, 15); ar = rotl(ar, 10)
  24037. cr = fn2(cr, dr, er, ar, br, m[14], 0x7a6d76e9, 8); er = rotl(er, 10)
  24038. // M'j = 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
  24039. // K' = 0x00000000
  24040. // S'j = 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
  24041. br = fn1(br, cr, dr, er, ar, m[12], 0x00000000, 8); dr = rotl(dr, 10)
  24042. ar = fn1(ar, br, cr, dr, er, m[15], 0x00000000, 5); cr = rotl(cr, 10)
  24043. er = fn1(er, ar, br, cr, dr, m[10], 0x00000000, 12); br = rotl(br, 10)
  24044. dr = fn1(dr, er, ar, br, cr, m[4], 0x00000000, 9); ar = rotl(ar, 10)
  24045. cr = fn1(cr, dr, er, ar, br, m[1], 0x00000000, 12); er = rotl(er, 10)
  24046. br = fn1(br, cr, dr, er, ar, m[5], 0x00000000, 5); dr = rotl(dr, 10)
  24047. ar = fn1(ar, br, cr, dr, er, m[8], 0x00000000, 14); cr = rotl(cr, 10)
  24048. er = fn1(er, ar, br, cr, dr, m[7], 0x00000000, 6); br = rotl(br, 10)
  24049. dr = fn1(dr, er, ar, br, cr, m[6], 0x00000000, 8); ar = rotl(ar, 10)
  24050. cr = fn1(cr, dr, er, ar, br, m[2], 0x00000000, 13); er = rotl(er, 10)
  24051. br = fn1(br, cr, dr, er, ar, m[13], 0x00000000, 6); dr = rotl(dr, 10)
  24052. ar = fn1(ar, br, cr, dr, er, m[14], 0x00000000, 5); cr = rotl(cr, 10)
  24053. er = fn1(er, ar, br, cr, dr, m[0], 0x00000000, 15); br = rotl(br, 10)
  24054. dr = fn1(dr, er, ar, br, cr, m[3], 0x00000000, 13); ar = rotl(ar, 10)
  24055. cr = fn1(cr, dr, er, ar, br, m[9], 0x00000000, 11); er = rotl(er, 10)
  24056. br = fn1(br, cr, dr, er, ar, m[11], 0x00000000, 11); dr = rotl(dr, 10)
  24057. // change state
  24058. var t = (this._b + cl + dr) | 0
  24059. this._b = (this._c + dl + er) | 0
  24060. this._c = (this._d + el + ar) | 0
  24061. this._d = (this._e + al + br) | 0
  24062. this._e = (this._a + bl + cr) | 0
  24063. this._a = t
  24064. }
  24065. RIPEMD160.prototype._digest = function () {
  24066. // create padding and handle blocks
  24067. this._block[this._blockOffset++] = 0x80
  24068. if (this._blockOffset > 56) {
  24069. this._block.fill(0, this._blockOffset, 64)
  24070. this._update()
  24071. this._blockOffset = 0
  24072. }
  24073. this._block.fill(0, this._blockOffset, 56)
  24074. this._block.writeUInt32LE(this._length[0], 56)
  24075. this._block.writeUInt32LE(this._length[1], 60)
  24076. this._update()
  24077. // produce result
  24078. var buffer = new Buffer(20)
  24079. buffer.writeInt32LE(this._a, 0)
  24080. buffer.writeInt32LE(this._b, 4)
  24081. buffer.writeInt32LE(this._c, 8)
  24082. buffer.writeInt32LE(this._d, 12)
  24083. buffer.writeInt32LE(this._e, 16)
  24084. return buffer
  24085. }
  24086. function rotl (x, n) {
  24087. return (x << n) | (x >>> (32 - n))
  24088. }
  24089. function fn1 (a, b, c, d, e, m, k, s) {
  24090. return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0
  24091. }
  24092. function fn2 (a, b, c, d, e, m, k, s) {
  24093. return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0
  24094. }
  24095. function fn3 (a, b, c, d, e, m, k, s) {
  24096. return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0
  24097. }
  24098. function fn4 (a, b, c, d, e, m, k, s) {
  24099. return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0
  24100. }
  24101. function fn5 (a, b, c, d, e, m, k, s) {
  24102. return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0
  24103. }
  24104. module.exports = RIPEMD160
  24105. }).call(this,require("buffer").Buffer)
  24106. },{"buffer":50,"hash-base":88,"inherits":104}],157:[function(require,module,exports){
  24107. /* eslint-disable node/no-deprecated-api */
  24108. var buffer = require('buffer')
  24109. var Buffer = buffer.Buffer
  24110. // alternative to using Object.keys for old browsers
  24111. function copyProps (src, dst) {
  24112. for (var key in src) {
  24113. dst[key] = src[key]
  24114. }
  24115. }
  24116. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  24117. module.exports = buffer
  24118. } else {
  24119. // Copy properties from require('buffer')
  24120. copyProps(buffer, exports)
  24121. exports.Buffer = SafeBuffer
  24122. }
  24123. function SafeBuffer (arg, encodingOrOffset, length) {
  24124. return Buffer(arg, encodingOrOffset, length)
  24125. }
  24126. // Copy static methods from Buffer
  24127. copyProps(Buffer, SafeBuffer)
  24128. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  24129. if (typeof arg === 'number') {
  24130. throw new TypeError('Argument must not be a number')
  24131. }
  24132. return Buffer(arg, encodingOrOffset, length)
  24133. }
  24134. SafeBuffer.alloc = function (size, fill, encoding) {
  24135. if (typeof size !== 'number') {
  24136. throw new TypeError('Argument must be a number')
  24137. }
  24138. var buf = Buffer(size)
  24139. if (fill !== undefined) {
  24140. if (typeof encoding === 'string') {
  24141. buf.fill(fill, encoding)
  24142. } else {
  24143. buf.fill(fill)
  24144. }
  24145. } else {
  24146. buf.fill(0)
  24147. }
  24148. return buf
  24149. }
  24150. SafeBuffer.allocUnsafe = function (size) {
  24151. if (typeof size !== 'number') {
  24152. throw new TypeError('Argument must be a number')
  24153. }
  24154. return Buffer(size)
  24155. }
  24156. SafeBuffer.allocUnsafeSlow = function (size) {
  24157. if (typeof size !== 'number') {
  24158. throw new TypeError('Argument must be a number')
  24159. }
  24160. return buffer.SlowBuffer(size)
  24161. }
  24162. },{"buffer":50}],158:[function(require,module,exports){
  24163. var Buffer = require('safe-buffer').Buffer
  24164. // prototype class for hash functions
  24165. function Hash (blockSize, finalSize) {
  24166. this._block = Buffer.alloc(blockSize)
  24167. this._finalSize = finalSize
  24168. this._blockSize = blockSize
  24169. this._len = 0
  24170. }
  24171. Hash.prototype.update = function (data, enc) {
  24172. if (typeof data === 'string') {
  24173. enc = enc || 'utf8'
  24174. data = Buffer.from(data, enc)
  24175. }
  24176. var block = this._block
  24177. var blockSize = this._blockSize
  24178. var length = data.length
  24179. var accum = this._len
  24180. for (var offset = 0; offset < length;) {
  24181. var assigned = accum % blockSize
  24182. var remainder = Math.min(length - offset, blockSize - assigned)
  24183. for (var i = 0; i < remainder; i++) {
  24184. block[assigned + i] = data[offset + i]
  24185. }
  24186. accum += remainder
  24187. offset += remainder
  24188. if ((accum % blockSize) === 0) {
  24189. this._update(block)
  24190. }
  24191. }
  24192. this._len += length
  24193. return this
  24194. }
  24195. Hash.prototype.digest = function (enc) {
  24196. var rem = this._len % this._blockSize
  24197. this._block[rem] = 0x80
  24198. // zero (rem + 1) trailing bits, where (rem + 1) is the smallest
  24199. // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
  24200. this._block.fill(0, rem + 1)
  24201. if (rem >= this._finalSize) {
  24202. this._update(this._block)
  24203. this._block.fill(0)
  24204. }
  24205. var bits = this._len * 8
  24206. // uint32
  24207. if (bits <= 0xffffffff) {
  24208. this._block.writeUInt32BE(bits, this._blockSize - 4)
  24209. // uint64
  24210. } else {
  24211. var lowBits = (bits & 0xffffffff) >>> 0
  24212. var highBits = (bits - lowBits) / 0x100000000
  24213. this._block.writeUInt32BE(highBits, this._blockSize - 8)
  24214. this._block.writeUInt32BE(lowBits, this._blockSize - 4)
  24215. }
  24216. this._update(this._block)
  24217. var hash = this._hash()
  24218. return enc ? hash.toString(enc) : hash
  24219. }
  24220. Hash.prototype._update = function () {
  24221. throw new Error('_update must be implemented by subclass')
  24222. }
  24223. module.exports = Hash
  24224. },{"safe-buffer":157}],159:[function(require,module,exports){
  24225. var exports = module.exports = function SHA (algorithm) {
  24226. algorithm = algorithm.toLowerCase()
  24227. var Algorithm = exports[algorithm]
  24228. if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
  24229. return new Algorithm()
  24230. }
  24231. exports.sha = require('./sha')
  24232. exports.sha1 = require('./sha1')
  24233. exports.sha224 = require('./sha224')
  24234. exports.sha256 = require('./sha256')
  24235. exports.sha384 = require('./sha384')
  24236. exports.sha512 = require('./sha512')
  24237. },{"./sha":160,"./sha1":161,"./sha224":162,"./sha256":163,"./sha384":164,"./sha512":165}],160:[function(require,module,exports){
  24238. /*
  24239. * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
  24240. * in FIPS PUB 180-1
  24241. * This source code is derived from sha1.js of the same repository.
  24242. * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
  24243. * operation was added.
  24244. */
  24245. var inherits = require('inherits')
  24246. var Hash = require('./hash')
  24247. var Buffer = require('safe-buffer').Buffer
  24248. var K = [
  24249. 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
  24250. ]
  24251. var W = new Array(80)
  24252. function Sha () {
  24253. this.init()
  24254. this._w = W
  24255. Hash.call(this, 64, 56)
  24256. }
  24257. inherits(Sha, Hash)
  24258. Sha.prototype.init = function () {
  24259. this._a = 0x67452301
  24260. this._b = 0xefcdab89
  24261. this._c = 0x98badcfe
  24262. this._d = 0x10325476
  24263. this._e = 0xc3d2e1f0
  24264. return this
  24265. }
  24266. function rotl5 (num) {
  24267. return (num << 5) | (num >>> 27)
  24268. }
  24269. function rotl30 (num) {
  24270. return (num << 30) | (num >>> 2)
  24271. }
  24272. function ft (s, b, c, d) {
  24273. if (s === 0) return (b & c) | ((~b) & d)
  24274. if (s === 2) return (b & c) | (b & d) | (c & d)
  24275. return b ^ c ^ d
  24276. }
  24277. Sha.prototype._update = function (M) {
  24278. var W = this._w
  24279. var a = this._a | 0
  24280. var b = this._b | 0
  24281. var c = this._c | 0
  24282. var d = this._d | 0
  24283. var e = this._e | 0
  24284. for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
  24285. for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]
  24286. for (var j = 0; j < 80; ++j) {
  24287. var s = ~~(j / 20)
  24288. var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
  24289. e = d
  24290. d = c
  24291. c = rotl30(b)
  24292. b = a
  24293. a = t
  24294. }
  24295. this._a = (a + this._a) | 0
  24296. this._b = (b + this._b) | 0
  24297. this._c = (c + this._c) | 0
  24298. this._d = (d + this._d) | 0
  24299. this._e = (e + this._e) | 0
  24300. }
  24301. Sha.prototype._hash = function () {
  24302. var H = Buffer.allocUnsafe(20)
  24303. H.writeInt32BE(this._a | 0, 0)
  24304. H.writeInt32BE(this._b | 0, 4)
  24305. H.writeInt32BE(this._c | 0, 8)
  24306. H.writeInt32BE(this._d | 0, 12)
  24307. H.writeInt32BE(this._e | 0, 16)
  24308. return H
  24309. }
  24310. module.exports = Sha
  24311. },{"./hash":158,"inherits":104,"safe-buffer":157}],161:[function(require,module,exports){
  24312. /*
  24313. * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
  24314. * in FIPS PUB 180-1
  24315. * Version 2.1a Copyright Paul Johnston 2000 - 2002.
  24316. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  24317. * Distributed under the BSD License
  24318. * See http://pajhome.org.uk/crypt/md5 for details.
  24319. */
  24320. var inherits = require('inherits')
  24321. var Hash = require('./hash')
  24322. var Buffer = require('safe-buffer').Buffer
  24323. var K = [
  24324. 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
  24325. ]
  24326. var W = new Array(80)
  24327. function Sha1 () {
  24328. this.init()
  24329. this._w = W
  24330. Hash.call(this, 64, 56)
  24331. }
  24332. inherits(Sha1, Hash)
  24333. Sha1.prototype.init = function () {
  24334. this._a = 0x67452301
  24335. this._b = 0xefcdab89
  24336. this._c = 0x98badcfe
  24337. this._d = 0x10325476
  24338. this._e = 0xc3d2e1f0
  24339. return this
  24340. }
  24341. function rotl1 (num) {
  24342. return (num << 1) | (num >>> 31)
  24343. }
  24344. function rotl5 (num) {
  24345. return (num << 5) | (num >>> 27)
  24346. }
  24347. function rotl30 (num) {
  24348. return (num << 30) | (num >>> 2)
  24349. }
  24350. function ft (s, b, c, d) {
  24351. if (s === 0) return (b & c) | ((~b) & d)
  24352. if (s === 2) return (b & c) | (b & d) | (c & d)
  24353. return b ^ c ^ d
  24354. }
  24355. Sha1.prototype._update = function (M) {
  24356. var W = this._w
  24357. var a = this._a | 0
  24358. var b = this._b | 0
  24359. var c = this._c | 0
  24360. var d = this._d | 0
  24361. var e = this._e | 0
  24362. for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
  24363. for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])
  24364. for (var j = 0; j < 80; ++j) {
  24365. var s = ~~(j / 20)
  24366. var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
  24367. e = d
  24368. d = c
  24369. c = rotl30(b)
  24370. b = a
  24371. a = t
  24372. }
  24373. this._a = (a + this._a) | 0
  24374. this._b = (b + this._b) | 0
  24375. this._c = (c + this._c) | 0
  24376. this._d = (d + this._d) | 0
  24377. this._e = (e + this._e) | 0
  24378. }
  24379. Sha1.prototype._hash = function () {
  24380. var H = Buffer.allocUnsafe(20)
  24381. H.writeInt32BE(this._a | 0, 0)
  24382. H.writeInt32BE(this._b | 0, 4)
  24383. H.writeInt32BE(this._c | 0, 8)
  24384. H.writeInt32BE(this._d | 0, 12)
  24385. H.writeInt32BE(this._e | 0, 16)
  24386. return H
  24387. }
  24388. module.exports = Sha1
  24389. },{"./hash":158,"inherits":104,"safe-buffer":157}],162:[function(require,module,exports){
  24390. /**
  24391. * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
  24392. * in FIPS 180-2
  24393. * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
  24394. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  24395. *
  24396. */
  24397. var inherits = require('inherits')
  24398. var Sha256 = require('./sha256')
  24399. var Hash = require('./hash')
  24400. var Buffer = require('safe-buffer').Buffer
  24401. var W = new Array(64)
  24402. function Sha224 () {
  24403. this.init()
  24404. this._w = W // new Array(64)
  24405. Hash.call(this, 64, 56)
  24406. }
  24407. inherits(Sha224, Sha256)
  24408. Sha224.prototype.init = function () {
  24409. this._a = 0xc1059ed8
  24410. this._b = 0x367cd507
  24411. this._c = 0x3070dd17
  24412. this._d = 0xf70e5939
  24413. this._e = 0xffc00b31
  24414. this._f = 0x68581511
  24415. this._g = 0x64f98fa7
  24416. this._h = 0xbefa4fa4
  24417. return this
  24418. }
  24419. Sha224.prototype._hash = function () {
  24420. var H = Buffer.allocUnsafe(28)
  24421. H.writeInt32BE(this._a, 0)
  24422. H.writeInt32BE(this._b, 4)
  24423. H.writeInt32BE(this._c, 8)
  24424. H.writeInt32BE(this._d, 12)
  24425. H.writeInt32BE(this._e, 16)
  24426. H.writeInt32BE(this._f, 20)
  24427. H.writeInt32BE(this._g, 24)
  24428. return H
  24429. }
  24430. module.exports = Sha224
  24431. },{"./hash":158,"./sha256":163,"inherits":104,"safe-buffer":157}],163:[function(require,module,exports){
  24432. /**
  24433. * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
  24434. * in FIPS 180-2
  24435. * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
  24436. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  24437. *
  24438. */
  24439. var inherits = require('inherits')
  24440. var Hash = require('./hash')
  24441. var Buffer = require('safe-buffer').Buffer
  24442. var K = [
  24443. 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
  24444. 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
  24445. 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
  24446. 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
  24447. 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
  24448. 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
  24449. 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
  24450. 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
  24451. 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
  24452. 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
  24453. 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
  24454. 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
  24455. 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
  24456. 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
  24457. 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
  24458. 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
  24459. ]
  24460. var W = new Array(64)
  24461. function Sha256 () {
  24462. this.init()
  24463. this._w = W // new Array(64)
  24464. Hash.call(this, 64, 56)
  24465. }
  24466. inherits(Sha256, Hash)
  24467. Sha256.prototype.init = function () {
  24468. this._a = 0x6a09e667
  24469. this._b = 0xbb67ae85
  24470. this._c = 0x3c6ef372
  24471. this._d = 0xa54ff53a
  24472. this._e = 0x510e527f
  24473. this._f = 0x9b05688c
  24474. this._g = 0x1f83d9ab
  24475. this._h = 0x5be0cd19
  24476. return this
  24477. }
  24478. function ch (x, y, z) {
  24479. return z ^ (x & (y ^ z))
  24480. }
  24481. function maj (x, y, z) {
  24482. return (x & y) | (z & (x | y))
  24483. }
  24484. function sigma0 (x) {
  24485. return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
  24486. }
  24487. function sigma1 (x) {
  24488. return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
  24489. }
  24490. function gamma0 (x) {
  24491. return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
  24492. }
  24493. function gamma1 (x) {
  24494. return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
  24495. }
  24496. Sha256.prototype._update = function (M) {
  24497. var W = this._w
  24498. var a = this._a | 0
  24499. var b = this._b | 0
  24500. var c = this._c | 0
  24501. var d = this._d | 0
  24502. var e = this._e | 0
  24503. var f = this._f | 0
  24504. var g = this._g | 0
  24505. var h = this._h | 0
  24506. for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
  24507. for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0
  24508. for (var j = 0; j < 64; ++j) {
  24509. var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
  24510. var T2 = (sigma0(a) + maj(a, b, c)) | 0
  24511. h = g
  24512. g = f
  24513. f = e
  24514. e = (d + T1) | 0
  24515. d = c
  24516. c = b
  24517. b = a
  24518. a = (T1 + T2) | 0
  24519. }
  24520. this._a = (a + this._a) | 0
  24521. this._b = (b + this._b) | 0
  24522. this._c = (c + this._c) | 0
  24523. this._d = (d + this._d) | 0
  24524. this._e = (e + this._e) | 0
  24525. this._f = (f + this._f) | 0
  24526. this._g = (g + this._g) | 0
  24527. this._h = (h + this._h) | 0
  24528. }
  24529. Sha256.prototype._hash = function () {
  24530. var H = Buffer.allocUnsafe(32)
  24531. H.writeInt32BE(this._a, 0)
  24532. H.writeInt32BE(this._b, 4)
  24533. H.writeInt32BE(this._c, 8)
  24534. H.writeInt32BE(this._d, 12)
  24535. H.writeInt32BE(this._e, 16)
  24536. H.writeInt32BE(this._f, 20)
  24537. H.writeInt32BE(this._g, 24)
  24538. H.writeInt32BE(this._h, 28)
  24539. return H
  24540. }
  24541. module.exports = Sha256
  24542. },{"./hash":158,"inherits":104,"safe-buffer":157}],164:[function(require,module,exports){
  24543. var inherits = require('inherits')
  24544. var SHA512 = require('./sha512')
  24545. var Hash = require('./hash')
  24546. var Buffer = require('safe-buffer').Buffer
  24547. var W = new Array(160)
  24548. function Sha384 () {
  24549. this.init()
  24550. this._w = W
  24551. Hash.call(this, 128, 112)
  24552. }
  24553. inherits(Sha384, SHA512)
  24554. Sha384.prototype.init = function () {
  24555. this._ah = 0xcbbb9d5d
  24556. this._bh = 0x629a292a
  24557. this._ch = 0x9159015a
  24558. this._dh = 0x152fecd8
  24559. this._eh = 0x67332667
  24560. this._fh = 0x8eb44a87
  24561. this._gh = 0xdb0c2e0d
  24562. this._hh = 0x47b5481d
  24563. this._al = 0xc1059ed8
  24564. this._bl = 0x367cd507
  24565. this._cl = 0x3070dd17
  24566. this._dl = 0xf70e5939
  24567. this._el = 0xffc00b31
  24568. this._fl = 0x68581511
  24569. this._gl = 0x64f98fa7
  24570. this._hl = 0xbefa4fa4
  24571. return this
  24572. }
  24573. Sha384.prototype._hash = function () {
  24574. var H = Buffer.allocUnsafe(48)
  24575. function writeInt64BE (h, l, offset) {
  24576. H.writeInt32BE(h, offset)
  24577. H.writeInt32BE(l, offset + 4)
  24578. }
  24579. writeInt64BE(this._ah, this._al, 0)
  24580. writeInt64BE(this._bh, this._bl, 8)
  24581. writeInt64BE(this._ch, this._cl, 16)
  24582. writeInt64BE(this._dh, this._dl, 24)
  24583. writeInt64BE(this._eh, this._el, 32)
  24584. writeInt64BE(this._fh, this._fl, 40)
  24585. return H
  24586. }
  24587. module.exports = Sha384
  24588. },{"./hash":158,"./sha512":165,"inherits":104,"safe-buffer":157}],165:[function(require,module,exports){
  24589. var inherits = require('inherits')
  24590. var Hash = require('./hash')
  24591. var Buffer = require('safe-buffer').Buffer
  24592. var K = [
  24593. 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
  24594. 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
  24595. 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
  24596. 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
  24597. 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
  24598. 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
  24599. 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
  24600. 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
  24601. 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
  24602. 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
  24603. 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
  24604. 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
  24605. 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
  24606. 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
  24607. 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
  24608. 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
  24609. 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
  24610. 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
  24611. 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
  24612. 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
  24613. 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
  24614. 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
  24615. 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
  24616. 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
  24617. 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
  24618. 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
  24619. 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
  24620. 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
  24621. 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
  24622. 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
  24623. 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
  24624. 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
  24625. 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
  24626. 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
  24627. 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
  24628. 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
  24629. 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
  24630. 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
  24631. 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
  24632. 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
  24633. ]
  24634. var W = new Array(160)
  24635. function Sha512 () {
  24636. this.init()
  24637. this._w = W
  24638. Hash.call(this, 128, 112)
  24639. }
  24640. inherits(Sha512, Hash)
  24641. Sha512.prototype.init = function () {
  24642. this._ah = 0x6a09e667
  24643. this._bh = 0xbb67ae85
  24644. this._ch = 0x3c6ef372
  24645. this._dh = 0xa54ff53a
  24646. this._eh = 0x510e527f
  24647. this._fh = 0x9b05688c
  24648. this._gh = 0x1f83d9ab
  24649. this._hh = 0x5be0cd19
  24650. this._al = 0xf3bcc908
  24651. this._bl = 0x84caa73b
  24652. this._cl = 0xfe94f82b
  24653. this._dl = 0x5f1d36f1
  24654. this._el = 0xade682d1
  24655. this._fl = 0x2b3e6c1f
  24656. this._gl = 0xfb41bd6b
  24657. this._hl = 0x137e2179
  24658. return this
  24659. }
  24660. function Ch (x, y, z) {
  24661. return z ^ (x & (y ^ z))
  24662. }
  24663. function maj (x, y, z) {
  24664. return (x & y) | (z & (x | y))
  24665. }
  24666. function sigma0 (x, xl) {
  24667. return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
  24668. }
  24669. function sigma1 (x, xl) {
  24670. return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
  24671. }
  24672. function Gamma0 (x, xl) {
  24673. return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
  24674. }
  24675. function Gamma0l (x, xl) {
  24676. return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
  24677. }
  24678. function Gamma1 (x, xl) {
  24679. return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
  24680. }
  24681. function Gamma1l (x, xl) {
  24682. return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
  24683. }
  24684. function getCarry (a, b) {
  24685. return (a >>> 0) < (b >>> 0) ? 1 : 0
  24686. }
  24687. Sha512.prototype._update = function (M) {
  24688. var W = this._w
  24689. var ah = this._ah | 0
  24690. var bh = this._bh | 0
  24691. var ch = this._ch | 0
  24692. var dh = this._dh | 0
  24693. var eh = this._eh | 0
  24694. var fh = this._fh | 0
  24695. var gh = this._gh | 0
  24696. var hh = this._hh | 0
  24697. var al = this._al | 0
  24698. var bl = this._bl | 0
  24699. var cl = this._cl | 0
  24700. var dl = this._dl | 0
  24701. var el = this._el | 0
  24702. var fl = this._fl | 0
  24703. var gl = this._gl | 0
  24704. var hl = this._hl | 0
  24705. for (var i = 0; i < 32; i += 2) {
  24706. W[i] = M.readInt32BE(i * 4)
  24707. W[i + 1] = M.readInt32BE(i * 4 + 4)
  24708. }
  24709. for (; i < 160; i += 2) {
  24710. var xh = W[i - 15 * 2]
  24711. var xl = W[i - 15 * 2 + 1]
  24712. var gamma0 = Gamma0(xh, xl)
  24713. var gamma0l = Gamma0l(xl, xh)
  24714. xh = W[i - 2 * 2]
  24715. xl = W[i - 2 * 2 + 1]
  24716. var gamma1 = Gamma1(xh, xl)
  24717. var gamma1l = Gamma1l(xl, xh)
  24718. // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
  24719. var Wi7h = W[i - 7 * 2]
  24720. var Wi7l = W[i - 7 * 2 + 1]
  24721. var Wi16h = W[i - 16 * 2]
  24722. var Wi16l = W[i - 16 * 2 + 1]
  24723. var Wil = (gamma0l + Wi7l) | 0
  24724. var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
  24725. Wil = (Wil + gamma1l) | 0
  24726. Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
  24727. Wil = (Wil + Wi16l) | 0
  24728. Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0
  24729. W[i] = Wih
  24730. W[i + 1] = Wil
  24731. }
  24732. for (var j = 0; j < 160; j += 2) {
  24733. Wih = W[j]
  24734. Wil = W[j + 1]
  24735. var majh = maj(ah, bh, ch)
  24736. var majl = maj(al, bl, cl)
  24737. var sigma0h = sigma0(ah, al)
  24738. var sigma0l = sigma0(al, ah)
  24739. var sigma1h = sigma1(eh, el)
  24740. var sigma1l = sigma1(el, eh)
  24741. // t1 = h + sigma1 + ch + K[j] + W[j]
  24742. var Kih = K[j]
  24743. var Kil = K[j + 1]
  24744. var chh = Ch(eh, fh, gh)
  24745. var chl = Ch(el, fl, gl)
  24746. var t1l = (hl + sigma1l) | 0
  24747. var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
  24748. t1l = (t1l + chl) | 0
  24749. t1h = (t1h + chh + getCarry(t1l, chl)) | 0
  24750. t1l = (t1l + Kil) | 0
  24751. t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
  24752. t1l = (t1l + Wil) | 0
  24753. t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0
  24754. // t2 = sigma0 + maj
  24755. var t2l = (sigma0l + majl) | 0
  24756. var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0
  24757. hh = gh
  24758. hl = gl
  24759. gh = fh
  24760. gl = fl
  24761. fh = eh
  24762. fl = el
  24763. el = (dl + t1l) | 0
  24764. eh = (dh + t1h + getCarry(el, dl)) | 0
  24765. dh = ch
  24766. dl = cl
  24767. ch = bh
  24768. cl = bl
  24769. bh = ah
  24770. bl = al
  24771. al = (t1l + t2l) | 0
  24772. ah = (t1h + t2h + getCarry(al, t1l)) | 0
  24773. }
  24774. this._al = (this._al + al) | 0
  24775. this._bl = (this._bl + bl) | 0
  24776. this._cl = (this._cl + cl) | 0
  24777. this._dl = (this._dl + dl) | 0
  24778. this._el = (this._el + el) | 0
  24779. this._fl = (this._fl + fl) | 0
  24780. this._gl = (this._gl + gl) | 0
  24781. this._hl = (this._hl + hl) | 0
  24782. this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
  24783. this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
  24784. this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
  24785. this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
  24786. this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
  24787. this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
  24788. this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
  24789. this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
  24790. }
  24791. Sha512.prototype._hash = function () {
  24792. var H = Buffer.allocUnsafe(64)
  24793. function writeInt64BE (h, l, offset) {
  24794. H.writeInt32BE(h, offset)
  24795. H.writeInt32BE(l, offset + 4)
  24796. }
  24797. writeInt64BE(this._ah, this._al, 0)
  24798. writeInt64BE(this._bh, this._bl, 8)
  24799. writeInt64BE(this._ch, this._cl, 16)
  24800. writeInt64BE(this._dh, this._dl, 24)
  24801. writeInt64BE(this._eh, this._el, 32)
  24802. writeInt64BE(this._fh, this._fl, 40)
  24803. writeInt64BE(this._gh, this._gl, 48)
  24804. writeInt64BE(this._hh, this._hl, 56)
  24805. return H
  24806. }
  24807. module.exports = Sha512
  24808. },{"./hash":158,"inherits":104,"safe-buffer":157}],166:[function(require,module,exports){
  24809. // Copyright Joyent, Inc. and other Node contributors.
  24810. //
  24811. // Permission is hereby granted, free of charge, to any person obtaining a
  24812. // copy of this software and associated documentation files (the
  24813. // "Software"), to deal in the Software without restriction, including
  24814. // without limitation the rights to use, copy, modify, merge, publish,
  24815. // distribute, sublicense, and/or sell copies of the Software, and to permit
  24816. // persons to whom the Software is furnished to do so, subject to the
  24817. // following conditions:
  24818. //
  24819. // The above copyright notice and this permission notice shall be included
  24820. // in all copies or substantial portions of the Software.
  24821. //
  24822. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  24823. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24824. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  24825. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  24826. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  24827. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  24828. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  24829. module.exports = Stream;
  24830. var EE = require('events').EventEmitter;
  24831. var inherits = require('inherits');
  24832. inherits(Stream, EE);
  24833. Stream.Readable = require('readable-stream/readable.js');
  24834. Stream.Writable = require('readable-stream/writable.js');
  24835. Stream.Duplex = require('readable-stream/duplex.js');
  24836. Stream.Transform = require('readable-stream/transform.js');
  24837. Stream.PassThrough = require('readable-stream/passthrough.js');
  24838. // Backwards-compat with node 0.4.x
  24839. Stream.Stream = Stream;
  24840. // old-style streams. Note that the pipe method (the only relevant
  24841. // part of this class) is overridden in the Readable class.
  24842. function Stream() {
  24843. EE.call(this);
  24844. }
  24845. Stream.prototype.pipe = function(dest, options) {
  24846. var source = this;
  24847. function ondata(chunk) {
  24848. if (dest.writable) {
  24849. if (false === dest.write(chunk) && source.pause) {
  24850. source.pause();
  24851. }
  24852. }
  24853. }
  24854. source.on('data', ondata);
  24855. function ondrain() {
  24856. if (source.readable && source.resume) {
  24857. source.resume();
  24858. }
  24859. }
  24860. dest.on('drain', ondrain);
  24861. // If the 'end' option is not supplied, dest.end() will be called when
  24862. // source gets the 'end' or 'close' events. Only dest.end() once.
  24863. if (!dest._isStdio && (!options || options.end !== false)) {
  24864. source.on('end', onend);
  24865. source.on('close', onclose);
  24866. }
  24867. var didOnEnd = false;
  24868. function onend() {
  24869. if (didOnEnd) return;
  24870. didOnEnd = true;
  24871. dest.end();
  24872. }
  24873. function onclose() {
  24874. if (didOnEnd) return;
  24875. didOnEnd = true;
  24876. if (typeof dest.destroy === 'function') dest.destroy();
  24877. }
  24878. // don't leave dangling pipes when there are errors.
  24879. function onerror(er) {
  24880. cleanup();
  24881. if (EE.listenerCount(this, 'error') === 0) {
  24882. throw er; // Unhandled stream error in pipe.
  24883. }
  24884. }
  24885. source.on('error', onerror);
  24886. dest.on('error', onerror);
  24887. // remove all the event listeners that were added.
  24888. function cleanup() {
  24889. source.removeListener('data', ondata);
  24890. dest.removeListener('drain', ondrain);
  24891. source.removeListener('end', onend);
  24892. source.removeListener('close', onclose);
  24893. source.removeListener('error', onerror);
  24894. dest.removeListener('error', onerror);
  24895. source.removeListener('end', cleanup);
  24896. source.removeListener('close', cleanup);
  24897. dest.removeListener('close', cleanup);
  24898. }
  24899. source.on('end', cleanup);
  24900. source.on('close', cleanup);
  24901. dest.on('close', cleanup);
  24902. dest.emit('pipe', source);
  24903. // Allow for unix-like usage: A.pipe(B).pipe(C)
  24904. return dest;
  24905. };
  24906. },{"events":86,"inherits":104,"readable-stream/duplex.js":143,"readable-stream/passthrough.js":152,"readable-stream/readable.js":153,"readable-stream/transform.js":154,"readable-stream/writable.js":155}],167:[function(require,module,exports){
  24907. 'use strict';
  24908. var Buffer = require('safe-buffer').Buffer;
  24909. var isEncoding = Buffer.isEncoding || function (encoding) {
  24910. encoding = '' + encoding;
  24911. switch (encoding && encoding.toLowerCase()) {
  24912. case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
  24913. return true;
  24914. default:
  24915. return false;
  24916. }
  24917. };
  24918. function _normalizeEncoding(enc) {
  24919. if (!enc) return 'utf8';
  24920. var retried;
  24921. while (true) {
  24922. switch (enc) {
  24923. case 'utf8':
  24924. case 'utf-8':
  24925. return 'utf8';
  24926. case 'ucs2':
  24927. case 'ucs-2':
  24928. case 'utf16le':
  24929. case 'utf-16le':
  24930. return 'utf16le';
  24931. case 'latin1':
  24932. case 'binary':
  24933. return 'latin1';
  24934. case 'base64':
  24935. case 'ascii':
  24936. case 'hex':
  24937. return enc;
  24938. default:
  24939. if (retried) return; // undefined
  24940. enc = ('' + enc).toLowerCase();
  24941. retried = true;
  24942. }
  24943. }
  24944. };
  24945. // Do not cache `Buffer.isEncoding` when checking encoding names as some
  24946. // modules monkey-patch it to support additional encodings
  24947. function normalizeEncoding(enc) {
  24948. var nenc = _normalizeEncoding(enc);
  24949. if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  24950. return nenc || enc;
  24951. }
  24952. // StringDecoder provides an interface for efficiently splitting a series of
  24953. // buffers into a series of JS strings without breaking apart multi-byte
  24954. // characters.
  24955. exports.StringDecoder = StringDecoder;
  24956. function StringDecoder(encoding) {
  24957. this.encoding = normalizeEncoding(encoding);
  24958. var nb;
  24959. switch (this.encoding) {
  24960. case 'utf16le':
  24961. this.text = utf16Text;
  24962. this.end = utf16End;
  24963. nb = 4;
  24964. break;
  24965. case 'utf8':
  24966. this.fillLast = utf8FillLast;
  24967. nb = 4;
  24968. break;
  24969. case 'base64':
  24970. this.text = base64Text;
  24971. this.end = base64End;
  24972. nb = 3;
  24973. break;
  24974. default:
  24975. this.write = simpleWrite;
  24976. this.end = simpleEnd;
  24977. return;
  24978. }
  24979. this.lastNeed = 0;
  24980. this.lastTotal = 0;
  24981. this.lastChar = Buffer.allocUnsafe(nb);
  24982. }
  24983. StringDecoder.prototype.write = function (buf) {
  24984. if (buf.length === 0) return '';
  24985. var r;
  24986. var i;
  24987. if (this.lastNeed) {
  24988. r = this.fillLast(buf);
  24989. if (r === undefined) return '';
  24990. i = this.lastNeed;
  24991. this.lastNeed = 0;
  24992. } else {
  24993. i = 0;
  24994. }
  24995. if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  24996. return r || '';
  24997. };
  24998. StringDecoder.prototype.end = utf8End;
  24999. // Returns only complete characters in a Buffer
  25000. StringDecoder.prototype.text = utf8Text;
  25001. // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
  25002. StringDecoder.prototype.fillLast = function (buf) {
  25003. if (this.lastNeed <= buf.length) {
  25004. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
  25005. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  25006. }
  25007. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  25008. this.lastNeed -= buf.length;
  25009. };
  25010. // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
  25011. // continuation byte.
  25012. function utf8CheckByte(byte) {
  25013. if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
  25014. return -1;
  25015. }
  25016. // Checks at most 3 bytes at the end of a Buffer in order to detect an
  25017. // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
  25018. // needed to complete the UTF-8 character (if applicable) are returned.
  25019. function utf8CheckIncomplete(self, buf, i) {
  25020. var j = buf.length - 1;
  25021. if (j < i) return 0;
  25022. var nb = utf8CheckByte(buf[j]);
  25023. if (nb >= 0) {
  25024. if (nb > 0) self.lastNeed = nb - 1;
  25025. return nb;
  25026. }
  25027. if (--j < i) return 0;
  25028. nb = utf8CheckByte(buf[j]);
  25029. if (nb >= 0) {
  25030. if (nb > 0) self.lastNeed = nb - 2;
  25031. return nb;
  25032. }
  25033. if (--j < i) return 0;
  25034. nb = utf8CheckByte(buf[j]);
  25035. if (nb >= 0) {
  25036. if (nb > 0) {
  25037. if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
  25038. }
  25039. return nb;
  25040. }
  25041. return 0;
  25042. }
  25043. // Validates as many continuation bytes for a multi-byte UTF-8 character as
  25044. // needed or are available. If we see a non-continuation byte where we expect
  25045. // one, we "replace" the validated continuation bytes we've seen so far with
  25046. // UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding
  25047. // behavior. The continuation byte check is included three times in the case
  25048. // where all of the continuation bytes for a character exist in the same buffer.
  25049. // It is also done this way as a slight performance increase instead of using a
  25050. // loop.
  25051. function utf8CheckExtraBytes(self, buf, p) {
  25052. if ((buf[0] & 0xC0) !== 0x80) {
  25053. self.lastNeed = 0;
  25054. return '\ufffd'.repeat(p);
  25055. }
  25056. if (self.lastNeed > 1 && buf.length > 1) {
  25057. if ((buf[1] & 0xC0) !== 0x80) {
  25058. self.lastNeed = 1;
  25059. return '\ufffd'.repeat(p + 1);
  25060. }
  25061. if (self.lastNeed > 2 && buf.length > 2) {
  25062. if ((buf[2] & 0xC0) !== 0x80) {
  25063. self.lastNeed = 2;
  25064. return '\ufffd'.repeat(p + 2);
  25065. }
  25066. }
  25067. }
  25068. }
  25069. // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
  25070. function utf8FillLast(buf) {
  25071. var p = this.lastTotal - this.lastNeed;
  25072. var r = utf8CheckExtraBytes(this, buf, p);
  25073. if (r !== undefined) return r;
  25074. if (this.lastNeed <= buf.length) {
  25075. buf.copy(this.lastChar, p, 0, this.lastNeed);
  25076. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  25077. }
  25078. buf.copy(this.lastChar, p, 0, buf.length);
  25079. this.lastNeed -= buf.length;
  25080. }
  25081. // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
  25082. // partial character, the character's bytes are buffered until the required
  25083. // number of bytes are available.
  25084. function utf8Text(buf, i) {
  25085. var total = utf8CheckIncomplete(this, buf, i);
  25086. if (!this.lastNeed) return buf.toString('utf8', i);
  25087. this.lastTotal = total;
  25088. var end = buf.length - (total - this.lastNeed);
  25089. buf.copy(this.lastChar, 0, end);
  25090. return buf.toString('utf8', i, end);
  25091. }
  25092. // For UTF-8, a replacement character for each buffered byte of a (partial)
  25093. // character needs to be added to the output.
  25094. function utf8End(buf) {
  25095. var r = buf && buf.length ? this.write(buf) : '';
  25096. if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed);
  25097. return r;
  25098. }
  25099. // UTF-16LE typically needs two bytes per character, but even if we have an even
  25100. // number of bytes available, we need to check if we end on a leading/high
  25101. // surrogate. In that case, we need to wait for the next two bytes in order to
  25102. // decode the last character properly.
  25103. function utf16Text(buf, i) {
  25104. if ((buf.length - i) % 2 === 0) {
  25105. var r = buf.toString('utf16le', i);
  25106. if (r) {
  25107. var c = r.charCodeAt(r.length - 1);
  25108. if (c >= 0xD800 && c <= 0xDBFF) {
  25109. this.lastNeed = 2;
  25110. this.lastTotal = 4;
  25111. this.lastChar[0] = buf[buf.length - 2];
  25112. this.lastChar[1] = buf[buf.length - 1];
  25113. return r.slice(0, -1);
  25114. }
  25115. }
  25116. return r;
  25117. }
  25118. this.lastNeed = 1;
  25119. this.lastTotal = 2;
  25120. this.lastChar[0] = buf[buf.length - 1];
  25121. return buf.toString('utf16le', i, buf.length - 1);
  25122. }
  25123. // For UTF-16LE we do not explicitly append special replacement characters if we
  25124. // end on a partial character, we simply let v8 handle that.
  25125. function utf16End(buf) {
  25126. var r = buf && buf.length ? this.write(buf) : '';
  25127. if (this.lastNeed) {
  25128. var end = this.lastTotal - this.lastNeed;
  25129. return r + this.lastChar.toString('utf16le', 0, end);
  25130. }
  25131. return r;
  25132. }
  25133. function base64Text(buf, i) {
  25134. var n = (buf.length - i) % 3;
  25135. if (n === 0) return buf.toString('base64', i);
  25136. this.lastNeed = 3 - n;
  25137. this.lastTotal = 3;
  25138. if (n === 1) {
  25139. this.lastChar[0] = buf[buf.length - 1];
  25140. } else {
  25141. this.lastChar[0] = buf[buf.length - 2];
  25142. this.lastChar[1] = buf[buf.length - 1];
  25143. }
  25144. return buf.toString('base64', i, buf.length - n);
  25145. }
  25146. function base64End(buf) {
  25147. var r = buf && buf.length ? this.write(buf) : '';
  25148. if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  25149. return r;
  25150. }
  25151. // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
  25152. function simpleWrite(buf) {
  25153. return buf.toString(this.encoding);
  25154. }
  25155. function simpleEnd(buf) {
  25156. return buf && buf.length ? this.write(buf) : '';
  25157. }
  25158. },{"safe-buffer":157}],168:[function(require,module,exports){
  25159. (function (global){
  25160. /**
  25161. * Module exports.
  25162. */
  25163. module.exports = deprecate;
  25164. /**
  25165. * Mark that a method should not be used.
  25166. * Returns a modified function which warns once by default.
  25167. *
  25168. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  25169. *
  25170. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  25171. * will throw an Error when invoked.
  25172. *
  25173. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  25174. * will invoke `console.trace()` instead of `console.error()`.
  25175. *
  25176. * @param {Function} fn - the function to deprecate
  25177. * @param {String} msg - the string to print to the console when `fn` is invoked
  25178. * @returns {Function} a new "deprecated" version of `fn`
  25179. * @api public
  25180. */
  25181. function deprecate (fn, msg) {
  25182. if (config('noDeprecation')) {
  25183. return fn;
  25184. }
  25185. var warned = false;
  25186. function deprecated() {
  25187. if (!warned) {
  25188. if (config('throwDeprecation')) {
  25189. throw new Error(msg);
  25190. } else if (config('traceDeprecation')) {
  25191. console.trace(msg);
  25192. } else {
  25193. console.warn(msg);
  25194. }
  25195. warned = true;
  25196. }
  25197. return fn.apply(this, arguments);
  25198. }
  25199. return deprecated;
  25200. }
  25201. /**
  25202. * Checks `localStorage` for boolean values for the given `name`.
  25203. *
  25204. * @param {String} name
  25205. * @returns {Boolean}
  25206. * @api private
  25207. */
  25208. function config (name) {
  25209. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  25210. try {
  25211. if (!global.localStorage) return false;
  25212. } catch (_) {
  25213. return false;
  25214. }
  25215. var val = global.localStorage[name];
  25216. if (null == val) return false;
  25217. return String(val).toLowerCase() === 'true';
  25218. }
  25219. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25220. },{}],169:[function(require,module,exports){
  25221. arguments[4][104][0].apply(exports,arguments)
  25222. },{"dup":104}],170:[function(require,module,exports){
  25223. module.exports = function isBuffer(arg) {
  25224. return arg && typeof arg === 'object'
  25225. && typeof arg.copy === 'function'
  25226. && typeof arg.fill === 'function'
  25227. && typeof arg.readUInt8 === 'function';
  25228. }
  25229. },{}],171:[function(require,module,exports){
  25230. (function (process,global){
  25231. // Copyright Joyent, Inc. and other Node contributors.
  25232. //
  25233. // Permission is hereby granted, free of charge, to any person obtaining a
  25234. // copy of this software and associated documentation files (the
  25235. // "Software"), to deal in the Software without restriction, including
  25236. // without limitation the rights to use, copy, modify, merge, publish,
  25237. // distribute, sublicense, and/or sell copies of the Software, and to permit
  25238. // persons to whom the Software is furnished to do so, subject to the
  25239. // following conditions:
  25240. //
  25241. // The above copyright notice and this permission notice shall be included
  25242. // in all copies or substantial portions of the Software.
  25243. //
  25244. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  25245. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25246. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  25247. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  25248. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  25249. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  25250. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  25251. var formatRegExp = /%[sdj%]/g;
  25252. exports.format = function(f) {
  25253. if (!isString(f)) {
  25254. var objects = [];
  25255. for (var i = 0; i < arguments.length; i++) {
  25256. objects.push(inspect(arguments[i]));
  25257. }
  25258. return objects.join(' ');
  25259. }
  25260. var i = 1;
  25261. var args = arguments;
  25262. var len = args.length;
  25263. var str = String(f).replace(formatRegExp, function(x) {
  25264. if (x === '%%') return '%';
  25265. if (i >= len) return x;
  25266. switch (x) {
  25267. case '%s': return String(args[i++]);
  25268. case '%d': return Number(args[i++]);
  25269. case '%j':
  25270. try {
  25271. return JSON.stringify(args[i++]);
  25272. } catch (_) {
  25273. return '[Circular]';
  25274. }
  25275. default:
  25276. return x;
  25277. }
  25278. });
  25279. for (var x = args[i]; i < len; x = args[++i]) {
  25280. if (isNull(x) || !isObject(x)) {
  25281. str += ' ' + x;
  25282. } else {
  25283. str += ' ' + inspect(x);
  25284. }
  25285. }
  25286. return str;
  25287. };
  25288. // Mark that a method should not be used.
  25289. // Returns a modified function which warns once by default.
  25290. // If --no-deprecation is set, then it is a no-op.
  25291. exports.deprecate = function(fn, msg) {
  25292. // Allow for deprecating things in the process of starting up.
  25293. if (isUndefined(global.process)) {
  25294. return function() {
  25295. return exports.deprecate(fn, msg).apply(this, arguments);
  25296. };
  25297. }
  25298. if (process.noDeprecation === true) {
  25299. return fn;
  25300. }
  25301. var warned = false;
  25302. function deprecated() {
  25303. if (!warned) {
  25304. if (process.throwDeprecation) {
  25305. throw new Error(msg);
  25306. } else if (process.traceDeprecation) {
  25307. console.trace(msg);
  25308. } else {
  25309. console.error(msg);
  25310. }
  25311. warned = true;
  25312. }
  25313. return fn.apply(this, arguments);
  25314. }
  25315. return deprecated;
  25316. };
  25317. var debugs = {};
  25318. var debugEnviron;
  25319. exports.debuglog = function(set) {
  25320. if (isUndefined(debugEnviron))
  25321. debugEnviron = process.env.NODE_DEBUG || '';
  25322. set = set.toUpperCase();
  25323. if (!debugs[set]) {
  25324. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  25325. var pid = process.pid;
  25326. debugs[set] = function() {
  25327. var msg = exports.format.apply(exports, arguments);
  25328. console.error('%s %d: %s', set, pid, msg);
  25329. };
  25330. } else {
  25331. debugs[set] = function() {};
  25332. }
  25333. }
  25334. return debugs[set];
  25335. };
  25336. /**
  25337. * Echos the value of a value. Trys to print the value out
  25338. * in the best way possible given the different types.
  25339. *
  25340. * @param {Object} obj The object to print out.
  25341. * @param {Object} opts Optional options object that alters the output.
  25342. */
  25343. /* legacy: obj, showHidden, depth, colors*/
  25344. function inspect(obj, opts) {
  25345. // default options
  25346. var ctx = {
  25347. seen: [],
  25348. stylize: stylizeNoColor
  25349. };
  25350. // legacy...
  25351. if (arguments.length >= 3) ctx.depth = arguments[2];
  25352. if (arguments.length >= 4) ctx.colors = arguments[3];
  25353. if (isBoolean(opts)) {
  25354. // legacy...
  25355. ctx.showHidden = opts;
  25356. } else if (opts) {
  25357. // got an "options" object
  25358. exports._extend(ctx, opts);
  25359. }
  25360. // set default options
  25361. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  25362. if (isUndefined(ctx.depth)) ctx.depth = 2;
  25363. if (isUndefined(ctx.colors)) ctx.colors = false;
  25364. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  25365. if (ctx.colors) ctx.stylize = stylizeWithColor;
  25366. return formatValue(ctx, obj, ctx.depth);
  25367. }
  25368. exports.inspect = inspect;
  25369. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  25370. inspect.colors = {
  25371. 'bold' : [1, 22],
  25372. 'italic' : [3, 23],
  25373. 'underline' : [4, 24],
  25374. 'inverse' : [7, 27],
  25375. 'white' : [37, 39],
  25376. 'grey' : [90, 39],
  25377. 'black' : [30, 39],
  25378. 'blue' : [34, 39],
  25379. 'cyan' : [36, 39],
  25380. 'green' : [32, 39],
  25381. 'magenta' : [35, 39],
  25382. 'red' : [31, 39],
  25383. 'yellow' : [33, 39]
  25384. };
  25385. // Don't use 'blue' not visible on cmd.exe
  25386. inspect.styles = {
  25387. 'special': 'cyan',
  25388. 'number': 'yellow',
  25389. 'boolean': 'yellow',
  25390. 'undefined': 'grey',
  25391. 'null': 'bold',
  25392. 'string': 'green',
  25393. 'date': 'magenta',
  25394. // "name": intentionally not styling
  25395. 'regexp': 'red'
  25396. };
  25397. function stylizeWithColor(str, styleType) {
  25398. var style = inspect.styles[styleType];
  25399. if (style) {
  25400. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  25401. '\u001b[' + inspect.colors[style][1] + 'm';
  25402. } else {
  25403. return str;
  25404. }
  25405. }
  25406. function stylizeNoColor(str, styleType) {
  25407. return str;
  25408. }
  25409. function arrayToHash(array) {
  25410. var hash = {};
  25411. array.forEach(function(val, idx) {
  25412. hash[val] = true;
  25413. });
  25414. return hash;
  25415. }
  25416. function formatValue(ctx, value, recurseTimes) {
  25417. // Provide a hook for user-specified inspect functions.
  25418. // Check that value is an object with an inspect function on it
  25419. if (ctx.customInspect &&
  25420. value &&
  25421. isFunction(value.inspect) &&
  25422. // Filter out the util module, it's inspect function is special
  25423. value.inspect !== exports.inspect &&
  25424. // Also filter out any prototype objects using the circular check.
  25425. !(value.constructor && value.constructor.prototype === value)) {
  25426. var ret = value.inspect(recurseTimes, ctx);
  25427. if (!isString(ret)) {
  25428. ret = formatValue(ctx, ret, recurseTimes);
  25429. }
  25430. return ret;
  25431. }
  25432. // Primitive types cannot have properties
  25433. var primitive = formatPrimitive(ctx, value);
  25434. if (primitive) {
  25435. return primitive;
  25436. }
  25437. // Look up the keys of the object.
  25438. var keys = Object.keys(value);
  25439. var visibleKeys = arrayToHash(keys);
  25440. if (ctx.showHidden) {
  25441. keys = Object.getOwnPropertyNames(value);
  25442. }
  25443. // IE doesn't make error fields non-enumerable
  25444. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  25445. if (isError(value)
  25446. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  25447. return formatError(value);
  25448. }
  25449. // Some type of object without properties can be shortcutted.
  25450. if (keys.length === 0) {
  25451. if (isFunction(value)) {
  25452. var name = value.name ? ': ' + value.name : '';
  25453. return ctx.stylize('[Function' + name + ']', 'special');
  25454. }
  25455. if (isRegExp(value)) {
  25456. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  25457. }
  25458. if (isDate(value)) {
  25459. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  25460. }
  25461. if (isError(value)) {
  25462. return formatError(value);
  25463. }
  25464. }
  25465. var base = '', array = false, braces = ['{', '}'];
  25466. // Make Array say that they are Array
  25467. if (isArray(value)) {
  25468. array = true;
  25469. braces = ['[', ']'];
  25470. }
  25471. // Make functions say that they are functions
  25472. if (isFunction(value)) {
  25473. var n = value.name ? ': ' + value.name : '';
  25474. base = ' [Function' + n + ']';
  25475. }
  25476. // Make RegExps say that they are RegExps
  25477. if (isRegExp(value)) {
  25478. base = ' ' + RegExp.prototype.toString.call(value);
  25479. }
  25480. // Make dates with properties first say the date
  25481. if (isDate(value)) {
  25482. base = ' ' + Date.prototype.toUTCString.call(value);
  25483. }
  25484. // Make error with message first say the error
  25485. if (isError(value)) {
  25486. base = ' ' + formatError(value);
  25487. }
  25488. if (keys.length === 0 && (!array || value.length == 0)) {
  25489. return braces[0] + base + braces[1];
  25490. }
  25491. if (recurseTimes < 0) {
  25492. if (isRegExp(value)) {
  25493. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  25494. } else {
  25495. return ctx.stylize('[Object]', 'special');
  25496. }
  25497. }
  25498. ctx.seen.push(value);
  25499. var output;
  25500. if (array) {
  25501. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  25502. } else {
  25503. output = keys.map(function(key) {
  25504. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  25505. });
  25506. }
  25507. ctx.seen.pop();
  25508. return reduceToSingleString(output, base, braces);
  25509. }
  25510. function formatPrimitive(ctx, value) {
  25511. if (isUndefined(value))
  25512. return ctx.stylize('undefined', 'undefined');
  25513. if (isString(value)) {
  25514. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  25515. .replace(/'/g, "\\'")
  25516. .replace(/\\"/g, '"') + '\'';
  25517. return ctx.stylize(simple, 'string');
  25518. }
  25519. if (isNumber(value))
  25520. return ctx.stylize('' + value, 'number');
  25521. if (isBoolean(value))
  25522. return ctx.stylize('' + value, 'boolean');
  25523. // For some reason typeof null is "object", so special case here.
  25524. if (isNull(value))
  25525. return ctx.stylize('null', 'null');
  25526. }
  25527. function formatError(value) {
  25528. return '[' + Error.prototype.toString.call(value) + ']';
  25529. }
  25530. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  25531. var output = [];
  25532. for (var i = 0, l = value.length; i < l; ++i) {
  25533. if (hasOwnProperty(value, String(i))) {
  25534. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  25535. String(i), true));
  25536. } else {
  25537. output.push('');
  25538. }
  25539. }
  25540. keys.forEach(function(key) {
  25541. if (!key.match(/^\d+$/)) {
  25542. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  25543. key, true));
  25544. }
  25545. });
  25546. return output;
  25547. }
  25548. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  25549. var name, str, desc;
  25550. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  25551. if (desc.get) {
  25552. if (desc.set) {
  25553. str = ctx.stylize('[Getter/Setter]', 'special');
  25554. } else {
  25555. str = ctx.stylize('[Getter]', 'special');
  25556. }
  25557. } else {
  25558. if (desc.set) {
  25559. str = ctx.stylize('[Setter]', 'special');
  25560. }
  25561. }
  25562. if (!hasOwnProperty(visibleKeys, key)) {
  25563. name = '[' + key + ']';
  25564. }
  25565. if (!str) {
  25566. if (ctx.seen.indexOf(desc.value) < 0) {
  25567. if (isNull(recurseTimes)) {
  25568. str = formatValue(ctx, desc.value, null);
  25569. } else {
  25570. str = formatValue(ctx, desc.value, recurseTimes - 1);
  25571. }
  25572. if (str.indexOf('\n') > -1) {
  25573. if (array) {
  25574. str = str.split('\n').map(function(line) {
  25575. return ' ' + line;
  25576. }).join('\n').substr(2);
  25577. } else {
  25578. str = '\n' + str.split('\n').map(function(line) {
  25579. return ' ' + line;
  25580. }).join('\n');
  25581. }
  25582. }
  25583. } else {
  25584. str = ctx.stylize('[Circular]', 'special');
  25585. }
  25586. }
  25587. if (isUndefined(name)) {
  25588. if (array && key.match(/^\d+$/)) {
  25589. return str;
  25590. }
  25591. name = JSON.stringify('' + key);
  25592. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  25593. name = name.substr(1, name.length - 2);
  25594. name = ctx.stylize(name, 'name');
  25595. } else {
  25596. name = name.replace(/'/g, "\\'")
  25597. .replace(/\\"/g, '"')
  25598. .replace(/(^"|"$)/g, "'");
  25599. name = ctx.stylize(name, 'string');
  25600. }
  25601. }
  25602. return name + ': ' + str;
  25603. }
  25604. function reduceToSingleString(output, base, braces) {
  25605. var numLinesEst = 0;
  25606. var length = output.reduce(function(prev, cur) {
  25607. numLinesEst++;
  25608. if (cur.indexOf('\n') >= 0) numLinesEst++;
  25609. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  25610. }, 0);
  25611. if (length > 60) {
  25612. return braces[0] +
  25613. (base === '' ? '' : base + '\n ') +
  25614. ' ' +
  25615. output.join(',\n ') +
  25616. ' ' +
  25617. braces[1];
  25618. }
  25619. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  25620. }
  25621. // NOTE: These type checking functions intentionally don't use `instanceof`
  25622. // because it is fragile and can be easily faked with `Object.create()`.
  25623. function isArray(ar) {
  25624. return Array.isArray(ar);
  25625. }
  25626. exports.isArray = isArray;
  25627. function isBoolean(arg) {
  25628. return typeof arg === 'boolean';
  25629. }
  25630. exports.isBoolean = isBoolean;
  25631. function isNull(arg) {
  25632. return arg === null;
  25633. }
  25634. exports.isNull = isNull;
  25635. function isNullOrUndefined(arg) {
  25636. return arg == null;
  25637. }
  25638. exports.isNullOrUndefined = isNullOrUndefined;
  25639. function isNumber(arg) {
  25640. return typeof arg === 'number';
  25641. }
  25642. exports.isNumber = isNumber;
  25643. function isString(arg) {
  25644. return typeof arg === 'string';
  25645. }
  25646. exports.isString = isString;
  25647. function isSymbol(arg) {
  25648. return typeof arg === 'symbol';
  25649. }
  25650. exports.isSymbol = isSymbol;
  25651. function isUndefined(arg) {
  25652. return arg === void 0;
  25653. }
  25654. exports.isUndefined = isUndefined;
  25655. function isRegExp(re) {
  25656. return isObject(re) && objectToString(re) === '[object RegExp]';
  25657. }
  25658. exports.isRegExp = isRegExp;
  25659. function isObject(arg) {
  25660. return typeof arg === 'object' && arg !== null;
  25661. }
  25662. exports.isObject = isObject;
  25663. function isDate(d) {
  25664. return isObject(d) && objectToString(d) === '[object Date]';
  25665. }
  25666. exports.isDate = isDate;
  25667. function isError(e) {
  25668. return isObject(e) &&
  25669. (objectToString(e) === '[object Error]' || e instanceof Error);
  25670. }
  25671. exports.isError = isError;
  25672. function isFunction(arg) {
  25673. return typeof arg === 'function';
  25674. }
  25675. exports.isFunction = isFunction;
  25676. function isPrimitive(arg) {
  25677. return arg === null ||
  25678. typeof arg === 'boolean' ||
  25679. typeof arg === 'number' ||
  25680. typeof arg === 'string' ||
  25681. typeof arg === 'symbol' || // ES6 symbol
  25682. typeof arg === 'undefined';
  25683. }
  25684. exports.isPrimitive = isPrimitive;
  25685. exports.isBuffer = require('./support/isBuffer');
  25686. function objectToString(o) {
  25687. return Object.prototype.toString.call(o);
  25688. }
  25689. function pad(n) {
  25690. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  25691. }
  25692. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  25693. 'Oct', 'Nov', 'Dec'];
  25694. // 26 Feb 16:19:34
  25695. function timestamp() {
  25696. var d = new Date();
  25697. var time = [pad(d.getHours()),
  25698. pad(d.getMinutes()),
  25699. pad(d.getSeconds())].join(':');
  25700. return [d.getDate(), months[d.getMonth()], time].join(' ');
  25701. }
  25702. // log is just a thin wrapper to console.log that prepends a timestamp
  25703. exports.log = function() {
  25704. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  25705. };
  25706. /**
  25707. * Inherit the prototype methods from one constructor into another.
  25708. *
  25709. * The Function.prototype.inherits from lang.js rewritten as a standalone
  25710. * function (not on Function.prototype). NOTE: If this file is to be loaded
  25711. * during bootstrapping this function needs to be rewritten using some native
  25712. * functions as prototype setup using normal JavaScript does not work as
  25713. * expected during bootstrapping (see mirror.js in r114903).
  25714. *
  25715. * @param {function} ctor Constructor function which needs to inherit the
  25716. * prototype.
  25717. * @param {function} superCtor Constructor function to inherit prototype from.
  25718. */
  25719. exports.inherits = require('inherits');
  25720. exports._extend = function(origin, add) {
  25721. // Don't do anything if add isn't an object
  25722. if (!add || !isObject(add)) return origin;
  25723. var keys = Object.keys(add);
  25724. var i = keys.length;
  25725. while (i--) {
  25726. origin[keys[i]] = add[keys[i]];
  25727. }
  25728. return origin;
  25729. };
  25730. function hasOwnProperty(obj, prop) {
  25731. return Object.prototype.hasOwnProperty.call(obj, prop);
  25732. }
  25733. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25734. },{"./support/isBuffer":170,"_process":134,"inherits":169}],172:[function(require,module,exports){
  25735. var indexOf = require('indexof');
  25736. var Object_keys = function (obj) {
  25737. if (Object.keys) return Object.keys(obj)
  25738. else {
  25739. var res = [];
  25740. for (var key in obj) res.push(key)
  25741. return res;
  25742. }
  25743. };
  25744. var forEach = function (xs, fn) {
  25745. if (xs.forEach) return xs.forEach(fn)
  25746. else for (var i = 0; i < xs.length; i++) {
  25747. fn(xs[i], i, xs);
  25748. }
  25749. };
  25750. var defineProp = (function() {
  25751. try {
  25752. Object.defineProperty({}, '_', {});
  25753. return function(obj, name, value) {
  25754. Object.defineProperty(obj, name, {
  25755. writable: true,
  25756. enumerable: false,
  25757. configurable: true,
  25758. value: value
  25759. })
  25760. };
  25761. } catch(e) {
  25762. return function(obj, name, value) {
  25763. obj[name] = value;
  25764. };
  25765. }
  25766. }());
  25767. var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function',
  25768. 'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError',
  25769. 'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError',
  25770. 'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape',
  25771. 'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape'];
  25772. function Context() {}
  25773. Context.prototype = {};
  25774. var Script = exports.Script = function NodeScript (code) {
  25775. if (!(this instanceof Script)) return new Script(code);
  25776. this.code = code;
  25777. };
  25778. Script.prototype.runInContext = function (context) {
  25779. if (!(context instanceof Context)) {
  25780. throw new TypeError("needs a 'context' argument.");
  25781. }
  25782. var iframe = document.createElement('iframe');
  25783. if (!iframe.style) iframe.style = {};
  25784. iframe.style.display = 'none';
  25785. document.body.appendChild(iframe);
  25786. var win = iframe.contentWindow;
  25787. var wEval = win.eval, wExecScript = win.execScript;
  25788. if (!wEval && wExecScript) {
  25789. // win.eval() magically appears when this is called in IE:
  25790. wExecScript.call(win, 'null');
  25791. wEval = win.eval;
  25792. }
  25793. forEach(Object_keys(context), function (key) {
  25794. win[key] = context[key];
  25795. });
  25796. forEach(globals, function (key) {
  25797. if (context[key]) {
  25798. win[key] = context[key];
  25799. }
  25800. });
  25801. var winKeys = Object_keys(win);
  25802. var res = wEval.call(win, this.code);
  25803. forEach(Object_keys(win), function (key) {
  25804. // Avoid copying circular objects like `top` and `window` by only
  25805. // updating existing context properties or new properties in the `win`
  25806. // that was only introduced after the eval.
  25807. if (key in context || indexOf(winKeys, key) === -1) {
  25808. context[key] = win[key];
  25809. }
  25810. });
  25811. forEach(globals, function (key) {
  25812. if (!(key in context)) {
  25813. defineProp(context, key, win[key]);
  25814. }
  25815. });
  25816. document.body.removeChild(iframe);
  25817. return res;
  25818. };
  25819. Script.prototype.runInThisContext = function () {
  25820. return eval(this.code); // maybe...
  25821. };
  25822. Script.prototype.runInNewContext = function (context) {
  25823. var ctx = Script.createContext(context);
  25824. var res = this.runInContext(ctx);
  25825. forEach(Object_keys(ctx), function (key) {
  25826. context[key] = ctx[key];
  25827. });
  25828. return res;
  25829. };
  25830. forEach(Object_keys(Script.prototype), function (name) {
  25831. exports[name] = Script[name] = function (code) {
  25832. var s = Script(code);
  25833. return s[name].apply(s, [].slice.call(arguments, 1));
  25834. };
  25835. });
  25836. exports.createScript = function (code) {
  25837. return exports.Script(code);
  25838. };
  25839. exports.createContext = Script.createContext = function (context) {
  25840. var copy = new Context();
  25841. if(typeof context === 'object') {
  25842. forEach(Object_keys(context), function (key) {
  25843. copy[key] = context[key];
  25844. });
  25845. }
  25846. return copy;
  25847. };
  25848. },{"indexof":103}],173:[function(require,module,exports){
  25849. (function (Buffer){
  25850. module.exports = {
  25851. "opath": require("./opath"),
  25852. "nb": require("./buffa"),
  25853. "rand": require("./random"),
  25854. "zlib": require("zlib"),
  25855. "Buffer": Buffer
  25856. }
  25857. }).call(this,require("buffer").Buffer)
  25858. },{"./buffa":176,"./opath":180,"./random":181,"buffer":50,"zlib":48}],174:[function(require,module,exports){
  25859. ////////////////////////////////////////////////////////////////////////////////////////
  25860. // Big Integer Library v. 5.5
  25861. // Created 2000, last modified 2013
  25862. // Leemon Baird
  25863. // www.leemon.com
  25864. //
  25865. // Version history:
  25866. // v 5.5 17 Mar 2013
  25867. // - two lines of a form like "if (x<0) x+=n" had the "if" changed to "while" to
  25868. // handle the case when x<-n. (Thanks to James Ansell for finding that bug)
  25869. // v 5.4 3 Oct 2009
  25870. // - added "var i" to greaterShift() so i is not global. (Thanks to PŽter Szab— for finding that bug)
  25871. //
  25872. // v 5.3 21 Sep 2009
  25873. // - added randProbPrime(k) for probable primes
  25874. // - unrolled loop in mont_ (slightly faster)
  25875. // - millerRabin now takes a bigInt parameter rather than an int
  25876. //
  25877. // v 5.2 15 Sep 2009
  25878. // - fixed capitalization in call to int2bigInt in randBigInt
  25879. // (thanks to Emili Evripidou, Reinhold Behringer, and Samuel Macaleese for finding that bug)
  25880. //
  25881. // v 5.1 8 Oct 2007
  25882. // - renamed inverseModInt_ to inverseModInt since it doesn't change its parameters
  25883. // - added functions GCD and randBigInt, which call GCD_ and randBigInt_
  25884. // - fixed a bug found by Rob Visser (see comment with his name below)
  25885. // - improved comments
  25886. //
  25887. // This file is public domain. You can use it for any purpose without restriction.
  25888. // I do not guarantee that it is correct, so use it at your own risk. If you use
  25889. // it for something interesting, I'd appreciate hearing about it. If you find
  25890. // any bugs or make any improvements, I'd appreciate hearing about those too.
  25891. // It would also be nice if my name and URL were left in the comments. But none
  25892. // of that is required.
  25893. //
  25894. // This code defines a bigInt library for arbitrary-precision integers.
  25895. // A bigInt is an array of integers storing the value in chunks of bpe bits,
  25896. // little endian (buff[0] is the least significant word).
  25897. // Negative bigInts are stored two's complement. Almost all the functions treat
  25898. // bigInts as nonnegative. The few that view them as two's complement say so
  25899. // in their comments. Some functions assume their parameters have at least one
  25900. // leading zero element. Functions with an underscore at the end of the name put
  25901. // their answer into one of the arrays passed in, and have unpredictable behavior
  25902. // in case of overflow, so the caller must make sure the arrays are big enough to
  25903. // hold the answer. But the average user should never have to call any of the
  25904. // underscored functions. Each important underscored function has a wrapper function
  25905. // of the same name without the underscore that takes care of the details for you.
  25906. // For each underscored function where a parameter is modified, that same variable
  25907. // must not be used as another argument too. So, you cannot square x by doing
  25908. // multMod_(x,x,n). You must use squareMod_(x,n) instead, or do y=dup(x); multMod_(x,y,n).
  25909. // Or simply use the multMod(x,x,n) function without the underscore, where
  25910. // such issues never arise, because non-underscored functions never change
  25911. // their parameters; they always allocate new memory for the answer that is returned.
  25912. //
  25913. // These functions are designed to avoid frequent dynamic memory allocation in the inner loop.
  25914. // For most functions, if it needs a BigInt as a local variable it will actually use
  25915. // a global, and will only allocate to it only when it's not the right size. This ensures
  25916. // that when a function is called repeatedly with same-sized parameters, it only allocates
  25917. // memory on the first call.
  25918. //
  25919. // Note that for cryptographic purposes, the calls to Math.random() must
  25920. // be replaced with calls to a better pseudorandom number generator.
  25921. //
  25922. // In the following, "bigInt" means a bigInt with at least one leading zero element,
  25923. // and "integer" means a nonnegative integer less than radix. In some cases, integer
  25924. // can be negative. Negative bigInts are 2s complement.
  25925. //
  25926. // The following functions do not modify their inputs.
  25927. // Those returning a bigInt, string, or Array will dynamically allocate memory for that value.
  25928. // Those returning a boolean will return the integer 0 (false) or 1 (true).
  25929. // Those returning boolean or int will not allocate memory except possibly on the first
  25930. // time they're called with a given parameter size.
  25931. //
  25932. // bigInt add(x,y) //return (x+y) for bigInts x and y.
  25933. // bigInt addInt(x,n) //return (x+n) where x is a bigInt and n is an integer.
  25934. // string bigInt2str(x,base) //return a string form of bigInt x in a given base, with 2 <= base <= 95
  25935. // int bitSize(x) //return how many bits long the bigInt x is, not counting leading zeros
  25936. // bigInt dup(x) //return a copy of bigInt x
  25937. // boolean equals(x,y) //is the bigInt x equal to the bigint y?
  25938. // boolean equalsInt(x,y) //is bigint x equal to integer y?
  25939. // bigInt expand(x,n) //return a copy of x with at least n elements, adding leading zeros if needed
  25940. // Array findPrimes(n) //return array of all primes less than integer n
  25941. // bigInt GCD(x,y) //return greatest common divisor of bigInts x and y (each with same number of elements).
  25942. // boolean greater(x,y) //is x>y? (x and y are nonnegative bigInts)
  25943. // boolean greaterShift(x,y,shift)//is (x <<(shift*bpe)) > y?
  25944. // bigInt int2bigInt(t,n,m) //return a bigInt equal to integer t, with at least n bits and m array elements
  25945. // bigInt inverseMod(x,n) //return (x**(-1) mod n) for bigInts x and n. If no inverse exists, it returns null
  25946. // int inverseModInt(x,n) //return x**(-1) mod n, for integers x and n. Return 0 if there is no inverse
  25947. // boolean isZero(x) //is the bigInt x equal to zero?
  25948. // boolean millerRabin(x,b) //does one round of Miller-Rabin base integer b say that bigInt x is possibly prime? (b is bigInt, 1<b<x)
  25949. // boolean millerRabinInt(x,b) //does one round of Miller-Rabin base integer b say that bigInt x is possibly prime? (b is int, 1<b<x)
  25950. // bigInt mod(x,n) //return a new bigInt equal to (x mod n) for bigInts x and n.
  25951. // int modInt(x,n) //return x mod n for bigInt x and integer n.
  25952. // bigInt mult(x,y) //return x*y for bigInts x and y. This is faster when y<x.
  25953. // bigInt multMod(x,y,n) //return (x*y mod n) for bigInts x,y,n. For greater speed, let y<x.
  25954. // boolean negative(x) //is bigInt x negative?
  25955. // bigInt powMod(x,y,n) //return (x**y mod n) where x,y,n are bigInts and ** is exponentiation. 0**0=1. Faster for odd n.
  25956. // bigInt randBigInt(n,s) //return an n-bit random BigInt (n>=1). If s=1, then the most significant of those n bits is set to 1.
  25957. // bigInt randTruePrime(k) //return a new, random, k-bit, true prime bigInt using Maurer's algorithm.
  25958. // bigInt randProbPrime(k) //return a new, random, k-bit, probable prime bigInt (probability it's composite less than 2^-80).
  25959. // bigInt str2bigInt(s,b,n,m) //return a bigInt for number represented in string s in base b with at least n bits and m array elements
  25960. // bigInt sub(x,y) //return (x-y) for bigInts x and y. Negative answers will be 2s complement
  25961. // bigInt trim(x,k) //return a copy of x with exactly k leading zero elements
  25962. //
  25963. //
  25964. // The following functions each have a non-underscored version, which most users should call instead.
  25965. // These functions each write to a single parameter, and the caller is responsible for ensuring the array
  25966. // passed in is large enough to hold the result.
  25967. //
  25968. // void addInt_(x,n) //do x=x+n where x is a bigInt and n is an integer
  25969. // void add_(x,y) //do x=x+y for bigInts x and y
  25970. // void copy_(x,y) //do x=y on bigInts x and y
  25971. // void copyInt_(x,n) //do x=n on bigInt x and integer n
  25972. // void GCD_(x,y) //set x to the greatest common divisor of bigInts x and y, (y is destroyed). (This never overflows its array).
  25973. // boolean inverseMod_(x,n) //do x=x**(-1) mod n, for bigInts x and n. Returns 1 (0) if inverse does (doesn't) exist
  25974. // void mod_(x,n) //do x=x mod n for bigInts x and n. (This never overflows its array).
  25975. // void mult_(x,y) //do x=x*y for bigInts x and y.
  25976. // void multMod_(x,y,n) //do x=x*y mod n for bigInts x,y,n.
  25977. // void powMod_(x,y,n) //do x=x**y mod n, where x,y,n are bigInts (n is odd) and ** is exponentiation. 0**0=1.
  25978. // void randBigInt_(b,n,s) //do b = an n-bit random BigInt. if s=1, then nth bit (most significant bit) is set to 1. n>=1.
  25979. // void randTruePrime_(ans,k) //do ans = a random k-bit true random prime (not just probable prime) with 1 in the msb.
  25980. // void sub_(x,y) //do x=x-y for bigInts x and y. Negative answers will be 2s complement.
  25981. //
  25982. // The following functions do NOT have a non-underscored version.
  25983. // They each write a bigInt result to one or more parameters. The caller is responsible for
  25984. // ensuring the arrays passed in are large enough to hold the results.
  25985. //
  25986. // void addShift_(x,y,ys) //do x=x+(y<<(ys*bpe))
  25987. // void carry_(x) //do carries and borrows so each element of the bigInt x fits in bpe bits.
  25988. // void divide_(x,y,q,r) //divide x by y giving quotient q and remainder r
  25989. // int divInt_(x,n) //do x=floor(x/n) for bigInt x and integer n, and return the remainder. (This never overflows its array).
  25990. // int eGCD_(x,y,d,a,b) //sets a,b,d to positive bigInts such that d = GCD_(x,y) = a*x-b*y
  25991. // void halve_(x) //do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement. (This never overflows its array).
  25992. // void leftShift_(x,n) //left shift bigInt x by n bits. n<bpe.
  25993. // void linComb_(x,y,a,b) //do x=a*x+b*y for bigInts x and y and integers a and b
  25994. // void linCombShift_(x,y,b,ys) //do x=x+b*(y<<(ys*bpe)) for bigInts x and y, and integers b and ys
  25995. // void mont_(x,y,n,np) //Montgomery multiplication (see comments where the function is defined)
  25996. // void multInt_(x,n) //do x=x*n where x is a bigInt and n is an integer.
  25997. // void rightShift_(x,n) //right shift bigInt x by n bits. 0 <= n < bpe. (This never overflows its array).
  25998. // void squareMod_(x,n) //do x=x*x mod n for bigInts x,n
  25999. // void subShift_(x,y,ys) //do x=x-(y<<(ys*bpe)). Negative answers will be 2s complement.
  26000. //
  26001. // The following functions are based on algorithms from the _Handbook of Applied Cryptography_
  26002. // powMod_() = algorithm 14.94, Montgomery exponentiation
  26003. // eGCD_,inverseMod_() = algorithm 14.61, Binary extended GCD_
  26004. // GCD_() = algorothm 14.57, Lehmer's algorithm
  26005. // mont_() = algorithm 14.36, Montgomery multiplication
  26006. // divide_() = algorithm 14.20 Multiple-precision division
  26007. // squareMod_() = algorithm 14.16 Multiple-precision squaring
  26008. // randTruePrime_() = algorithm 4.62, Maurer's algorithm
  26009. // millerRabin() = algorithm 4.24, Miller-Rabin algorithm
  26010. //
  26011. // Profiling shows:
  26012. // randTruePrime_() spends:
  26013. // 10% of its time in calls to powMod_()
  26014. // 85% of its time in calls to millerRabin()
  26015. // millerRabin() spends:
  26016. // 99% of its time in calls to powMod_() (always with a base of 2)
  26017. // powMod_() spends:
  26018. // 94% of its time in calls to mont_() (almost always with x==y)
  26019. //
  26020. // This suggests there are several ways to speed up this library slightly:
  26021. // - convert powMod_ to use a Montgomery form of k-ary window (or maybe a Montgomery form of sliding window)
  26022. // -- this should especially focus on being fast when raising 2 to a power mod n
  26023. // - convert randTruePrime_() to use a minimum r of 1/3 instead of 1/2 with the appropriate change to the test
  26024. // - tune the parameters in randTruePrime_(), including c, m, and recLimit
  26025. // - speed up the single loop in mont_() that takes 95% of the runtime, perhaps by reducing checking
  26026. // within the loop when all the parameters are the same length.
  26027. //
  26028. // There are several ideas that look like they wouldn't help much at all:
  26029. // - replacing trial division in randTruePrime_() with a sieve (that speeds up something taking almost no time anyway)
  26030. // - increase bpe from 15 to 30 (that would help if we had a 32*32->64 multiplier, but not with JavaScript's 32*32->32)
  26031. // - speeding up mont_(x,y,n,np) when x==y by doing a non-modular, non-Montgomery square
  26032. // followed by a Montgomery reduction. The intermediate answer will be twice as long as x, so that
  26033. // method would be slower. This is unfortunate because the code currently spends almost all of its time
  26034. // doing mont_(x,x,...), both for randTruePrime_() and powMod_(). A faster method for Montgomery squaring
  26035. // would have a large impact on the speed of randTruePrime_() and powMod_(). HAC has a couple of poorly-worded
  26036. // sentences that seem to imply it's faster to do a non-modular square followed by a single
  26037. // Montgomery reduction, but that's obviously wrong.
  26038. ////////////////////////////////////////////////////////////////////////////////////////
  26039. //globals
  26040. bpe=0; //bits stored per array element
  26041. mask=0; //AND this with an array element to chop it down to bpe bits
  26042. radix=mask+1; //equals 2^bpe. A single 1 bit to the left of the last bit of mask.
  26043. //the digits for converting to different bases
  26044. digitsStr='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_=!@#$%^&*()[]{}|;:,.<>/?`~ \\\'\"+-';
  26045. digitsStr= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_=ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ!@#$%^&*()[]{}|;:,.<>/?`~+-¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿";
  26046. //initialize the global variables
  26047. for (bpe=0; (1<<(bpe+1)) > (1<<bpe); bpe++); //bpe=number of bits in the mantissa on this platform
  26048. bpe>>=1; //bpe=number of bits in one element of the array representing the bigInt
  26049. mask=(1<<bpe)-1; //AND the mask with an integer to get its bpe least significant bits
  26050. radix=mask+1; //2^bpe. a single 1 bit to the left of the first bit of mask
  26051. one=int2bigInt(1,1,1); //constant used in powMod_()
  26052. //the following global variables are scratchpad memory to
  26053. //reduce dynamic memory allocation in the inner loop
  26054. t=new Array(0);
  26055. ss=t; //used in mult_()
  26056. s0=t; //used in multMod_(), squareMod_()
  26057. s1=t; //used in powMod_(), multMod_(), squareMod_()
  26058. s2=t; //used in powMod_(), multMod_()
  26059. s3=t; //used in powMod_()
  26060. s4=t; s5=t; //used in mod_()
  26061. s6=t; //used in bigInt2str()
  26062. s7=t; //used in powMod_()
  26063. T=t; //used in GCD_()
  26064. sa=t; //used in mont_()
  26065. mr_x1=t; mr_r=t; mr_a=t; //used in millerRabin()
  26066. eg_v=t; eg_u=t; eg_A=t; eg_B=t; eg_C=t; eg_D=t; //used in eGCD_(), inverseMod_()
  26067. md_q1=t; md_q2=t; md_q3=t; md_r=t; md_r1=t; md_r2=t; md_tt=t; //used in mod_()
  26068. primes=t; pows=t; s_i=t; s_i2=t; s_R=t; s_rm=t; s_q=t; s_n1=t;
  26069. s_a=t; s_r2=t; s_n=t; s_b=t; s_d=t; s_x1=t; s_x2=t, s_aa=t; //used in randTruePrime_()
  26070. rpprb=t; //used in randProbPrimeRounds() (which also uses "primes")
  26071. ////////////////////////////////////////////////////////////////////////////////////////
  26072. //return array of all primes less than integer n
  26073. function findPrimes(n) {
  26074. var i,s,p,ans;
  26075. s=new Array(n);
  26076. for (i=0;i<n;i++)
  26077. s[i]=0;
  26078. s[0]=2;
  26079. p=0; //first p elements of s are primes, the rest are a sieve
  26080. for(;s[p]<n;) { //s[p] is the pth prime
  26081. for(i=s[p]*s[p]; i<n; i+=s[p]) //mark multiples of s[p]
  26082. s[i]=1;
  26083. p++;
  26084. s[p]=s[p-1]+1;
  26085. for(; s[p]<n && s[s[p]]; s[p]++); //find next prime (where s[p]==0)
  26086. }
  26087. ans=new Array(p);
  26088. for(i=0;i<p;i++)
  26089. ans[i]=s[i];
  26090. return ans;
  26091. }
  26092. //does a single round of Miller-Rabin base b consider x to be a possible prime?
  26093. //x is a bigInt, and b is an integer, with b<x
  26094. function millerRabinInt(x,b) {
  26095. if (mr_x1.length!=x.length) {
  26096. mr_x1=dup(x);
  26097. mr_r=dup(x);
  26098. mr_a=dup(x);
  26099. }
  26100. copyInt_(mr_a,b);
  26101. return millerRabin(x,mr_a);
  26102. }
  26103. //does a single round of Miller-Rabin base b consider x to be a possible prime?
  26104. //x and b are bigInts with b<x
  26105. function millerRabin(x,b) {
  26106. var i,j,k,s;
  26107. if (mr_x1.length!=x.length) {
  26108. mr_x1=dup(x);
  26109. mr_r=dup(x);
  26110. mr_a=dup(x);
  26111. }
  26112. copy_(mr_a,b);
  26113. copy_(mr_r,x);
  26114. copy_(mr_x1,x);
  26115. addInt_(mr_r,-1);
  26116. addInt_(mr_x1,-1);
  26117. //s=the highest power of two that divides mr_r
  26118. k=0;
  26119. for (i=0;i<mr_r.length;i++)
  26120. for (j=1;j<mask;j<<=1)
  26121. if (x[i] & j) {
  26122. s=(k<mr_r.length+bpe ? k : 0);
  26123. i=mr_r.length;
  26124. j=mask;
  26125. } else
  26126. k++;
  26127. if (s)
  26128. rightShift_(mr_r,s);
  26129. powMod_(mr_a,mr_r,x);
  26130. if (!equalsInt(mr_a,1) && !equals(mr_a,mr_x1)) {
  26131. j=1;
  26132. while (j<=s-1 && !equals(mr_a,mr_x1)) {
  26133. squareMod_(mr_a,x);
  26134. if (equalsInt(mr_a,1)) {
  26135. return 0;
  26136. }
  26137. j++;
  26138. }
  26139. if (!equals(mr_a,mr_x1)) {
  26140. return 0;
  26141. }
  26142. }
  26143. return 1;
  26144. }
  26145. //returns how many bits long the bigInt is, not counting leading zeros.
  26146. function bitSize(x) {
  26147. var j,z,w;
  26148. for (j=x.length-1; (x[j]==0) && (j>0); j--);
  26149. for (z=0,w=x[j]; w; (w>>=1),z++);
  26150. z+=bpe*j;
  26151. return z;
  26152. }
  26153. //return a copy of x with at least n elements, adding leading zeros if needed
  26154. function expand(x,n) {
  26155. var ans=int2bigInt(0,(x.length>n ? x.length : n)*bpe,0);
  26156. copy_(ans,x);
  26157. return ans;
  26158. }
  26159. //return a k-bit true random prime using Maurer's algorithm.
  26160. function randTruePrime(k) {
  26161. var ans=int2bigInt(0,k,0);
  26162. randTruePrime_(ans,k);
  26163. return trim(ans,1);
  26164. }
  26165. //return a k-bit random probable prime with probability of error < 2^-80
  26166. function randProbPrime(k) {
  26167. if (k>=600) return randProbPrimeRounds(k,2); //numbers from HAC table 4.3
  26168. if (k>=550) return randProbPrimeRounds(k,4);
  26169. if (k>=500) return randProbPrimeRounds(k,5);
  26170. if (k>=400) return randProbPrimeRounds(k,6);
  26171. if (k>=350) return randProbPrimeRounds(k,7);
  26172. if (k>=300) return randProbPrimeRounds(k,9);
  26173. if (k>=250) return randProbPrimeRounds(k,12); //numbers from HAC table 4.4
  26174. if (k>=200) return randProbPrimeRounds(k,15);
  26175. if (k>=150) return randProbPrimeRounds(k,18);
  26176. if (k>=100) return randProbPrimeRounds(k,27);
  26177. return randProbPrimeRounds(k,40); //number from HAC remark 4.26 (only an estimate)
  26178. }
  26179. //return a k-bit probable random prime using n rounds of Miller Rabin (after trial division with small primes)
  26180. function randProbPrimeRounds(k,n) {
  26181. var ans, i, divisible, B;
  26182. B=30000; //B is largest prime to use in trial division
  26183. ans=int2bigInt(0,k,0);
  26184. //optimization: try larger and smaller B to find the best limit.
  26185. if (primes.length==0)
  26186. primes=findPrimes(30000); //check for divisibility by primes <=30000
  26187. if (rpprb.length!=ans.length)
  26188. rpprb=dup(ans);
  26189. for (;;) { //keep trying random values for ans until one appears to be prime
  26190. //optimization: pick a random number times L=2*3*5*...*p, plus a
  26191. // random element of the list of all numbers in [0,L) not divisible by any prime up to p.
  26192. // This can reduce the amount of random number generation.
  26193. randBigInt_(ans,k,0); //ans = a random odd number to check
  26194. ans[0] |= 1;
  26195. divisible=0;
  26196. //check ans for divisibility by small primes up to B
  26197. for (i=0; (i<primes.length) && (primes[i]<=B); i++)
  26198. if (modInt(ans,primes[i])==0 && !equalsInt(ans,primes[i])) {
  26199. divisible=1;
  26200. break;
  26201. }
  26202. //optimization: change millerRabin so the base can be bigger than the number being checked, then eliminate the while here.
  26203. //do n rounds of Miller Rabin, with random bases less than ans
  26204. for (i=0; i<n && !divisible; i++) {
  26205. randBigInt_(rpprb,k,0);
  26206. while(!greater(ans,rpprb)) //pick a random rpprb that's < ans
  26207. randBigInt_(rpprb,k,0);
  26208. if (!millerRabin(ans,rpprb))
  26209. divisible=1;
  26210. }
  26211. if(!divisible)
  26212. return ans;
  26213. }
  26214. }
  26215. //return a new bigInt equal to (x mod n) for bigInts x and n.
  26216. function mod(x,n) {
  26217. var ans=dup(x);
  26218. mod_(ans,n);
  26219. return trim(ans,1);
  26220. }
  26221. //return (x+n) where x is a bigInt and n is an integer.
  26222. function addInt(x,n) {
  26223. var ans=expand(x,x.length+1);
  26224. addInt_(ans,n);
  26225. return trim(ans,1);
  26226. }
  26227. //return x*y for bigInts x and y. This is faster when y<x.
  26228. function mult(x,y) {
  26229. var ans=expand(x,x.length+y.length);
  26230. mult_(ans,y);
  26231. return trim(ans,1);
  26232. }
  26233. //return (x**y mod n) where x,y,n are bigInts and ** is exponentiation. 0**0=1. Faster for odd n.
  26234. function powMod(x,y,n) {
  26235. var ans=expand(x,n.length);
  26236. powMod_(ans,trim(y,2),trim(n,2),0); //this should work without the trim, but doesn't
  26237. return trim(ans,1);
  26238. }
  26239. //return (x-y) for bigInts x and y. Negative answers will be 2s complement
  26240. function sub(x,y) {
  26241. var ans=expand(x,(x.length>y.length ? x.length+1 : y.length+1));
  26242. sub_(ans,y);
  26243. return trim(ans,1);
  26244. }
  26245. //return (x+y) for bigInts x and y.
  26246. function add(x,y) {
  26247. var ans=expand(x,(x.length>y.length ? x.length+1 : y.length+1));
  26248. add_(ans,y);
  26249. return trim(ans,1);
  26250. }
  26251. //return (x**(-1) mod n) for bigInts x and n. If no inverse exists, it returns null
  26252. function inverseMod(x,n) {
  26253. var ans=expand(x,n.length);
  26254. var s;
  26255. s=inverseMod_(ans,n);
  26256. return s ? trim(ans,1) : null;
  26257. }
  26258. //return (x*y mod n) for bigInts x,y,n. For greater speed, let y<x.
  26259. function multMod(x,y,n) {
  26260. var ans=expand(x,n.length);
  26261. multMod_(ans,y,n);
  26262. return trim(ans,1);
  26263. }
  26264. //generate a k-bit true random prime using Maurer's algorithm,
  26265. //and put it into ans. The bigInt ans must be large enough to hold it.
  26266. function randTruePrime_(ans,k) {
  26267. var c,m,pm,dd,j,r,B,divisible,z,zz,recSize;
  26268. if (primes.length==0)
  26269. primes=findPrimes(30000); //check for divisibility by primes <=30000
  26270. if (pows.length==0) {
  26271. pows=new Array(512);
  26272. for (j=0;j<512;j++) {
  26273. pows[j]=Math.pow(2,j/511.-1.);
  26274. }
  26275. }
  26276. //c and m should be tuned for a particular machine and value of k, to maximize speed
  26277. c=0.1; //c=0.1 in HAC
  26278. m=20; //generate this k-bit number by first recursively generating a number that has between k/2 and k-m bits
  26279. recLimit=20; //stop recursion when k <=recLimit. Must have recLimit >= 2
  26280. if (s_i2.length!=ans.length) {
  26281. s_i2=dup(ans);
  26282. s_R =dup(ans);
  26283. s_n1=dup(ans);
  26284. s_r2=dup(ans);
  26285. s_d =dup(ans);
  26286. s_x1=dup(ans);
  26287. s_x2=dup(ans);
  26288. s_b =dup(ans);
  26289. s_n =dup(ans);
  26290. s_i =dup(ans);
  26291. s_rm=dup(ans);
  26292. s_q =dup(ans);
  26293. s_a =dup(ans);
  26294. s_aa=dup(ans);
  26295. }
  26296. if (k <= recLimit) { //generate small random primes by trial division up to its square root
  26297. pm=(1<<((k+2)>>1))-1; //pm is binary number with all ones, just over sqrt(2^k)
  26298. copyInt_(ans,0);
  26299. for (dd=1;dd;) {
  26300. dd=0;
  26301. ans[0]= 1 | (1<<(k-1)) | Math.floor(Math.random()*(1<<k)); //random, k-bit, odd integer, with msb 1
  26302. for (j=1;(j<primes.length) && ((primes[j]&pm)==primes[j]);j++) { //trial division by all primes 3...sqrt(2^k)
  26303. if (0==(ans[0]%primes[j])) {
  26304. dd=1;
  26305. break;
  26306. }
  26307. }
  26308. }
  26309. carry_(ans);
  26310. return;
  26311. }
  26312. B=c*k*k; //try small primes up to B (or all the primes[] array if the largest is less than B).
  26313. if (k>2*m) //generate this k-bit number by first recursively generating a number that has between k/2 and k-m bits
  26314. for (r=1; k-k*r<=m; )
  26315. r=pows[Math.floor(Math.random()*512)]; //r=Math.pow(2,Math.random()-1);
  26316. else
  26317. r=.5;
  26318. //simulation suggests the more complex algorithm using r=.333 is only slightly faster.
  26319. recSize=Math.floor(r*k)+1;
  26320. randTruePrime_(s_q,recSize);
  26321. copyInt_(s_i2,0);
  26322. s_i2[Math.floor((k-2)/bpe)] |= (1<<((k-2)%bpe)); //s_i2=2^(k-2)
  26323. divide_(s_i2,s_q,s_i,s_rm); //s_i=floor((2^(k-1))/(2q))
  26324. z=bitSize(s_i);
  26325. for (;;) {
  26326. for (;;) { //generate z-bit numbers until one falls in the range [0,s_i-1]
  26327. randBigInt_(s_R,z,0);
  26328. if (greater(s_i,s_R))
  26329. break;
  26330. } //now s_R is in the range [0,s_i-1]
  26331. addInt_(s_R,1); //now s_R is in the range [1,s_i]
  26332. add_(s_R,s_i); //now s_R is in the range [s_i+1,2*s_i]
  26333. copy_(s_n,s_q);
  26334. mult_(s_n,s_R);
  26335. multInt_(s_n,2);
  26336. addInt_(s_n,1); //s_n=2*s_R*s_q+1
  26337. copy_(s_r2,s_R);
  26338. multInt_(s_r2,2); //s_r2=2*s_R
  26339. //check s_n for divisibility by small primes up to B
  26340. for (divisible=0,j=0; (j<primes.length) && (primes[j]<B); j++)
  26341. if (modInt(s_n,primes[j])==0 && !equalsInt(s_n,primes[j])) {
  26342. divisible=1;
  26343. break;
  26344. }
  26345. if (!divisible) //if it passes small primes check, then try a single Miller-Rabin base 2
  26346. if (!millerRabinInt(s_n,2)) //this line represents 75% of the total runtime for randTruePrime_
  26347. divisible=1;
  26348. if (!divisible) { //if it passes that test, continue checking s_n
  26349. addInt_(s_n,-3);
  26350. for (j=s_n.length-1;(s_n[j]==0) && (j>0); j--); //strip leading zeros
  26351. for (zz=0,w=s_n[j]; w; (w>>=1),zz++);
  26352. zz+=bpe*j; //zz=number of bits in s_n, ignoring leading zeros
  26353. for (;;) { //generate z-bit numbers until one falls in the range [0,s_n-1]
  26354. randBigInt_(s_a,zz,0);
  26355. if (greater(s_n,s_a))
  26356. break;
  26357. } //now s_a is in the range [0,s_n-1]
  26358. addInt_(s_n,3); //now s_a is in the range [0,s_n-4]
  26359. addInt_(s_a,2); //now s_a is in the range [2,s_n-2]
  26360. copy_(s_b,s_a);
  26361. copy_(s_n1,s_n);
  26362. addInt_(s_n1,-1);
  26363. powMod_(s_b,s_n1,s_n); //s_b=s_a^(s_n-1) modulo s_n
  26364. addInt_(s_b,-1);
  26365. if (isZero(s_b)) {
  26366. copy_(s_b,s_a);
  26367. powMod_(s_b,s_r2,s_n);
  26368. addInt_(s_b,-1);
  26369. copy_(s_aa,s_n);
  26370. copy_(s_d,s_b);
  26371. GCD_(s_d,s_n); //if s_b and s_n are relatively prime, then s_n is a prime
  26372. if (equalsInt(s_d,1)) {
  26373. copy_(ans,s_aa);
  26374. return; //if we've made it this far, then s_n is absolutely guaranteed to be prime
  26375. }
  26376. }
  26377. }
  26378. }
  26379. }
  26380. //Return an n-bit random BigInt (n>=1). If s=1, then the most significant of those n bits is set to 1.
  26381. function randBigInt(n,s) {
  26382. var a,b;
  26383. a=Math.floor((n-1)/bpe)+2; //# array elements to hold the BigInt with a leading 0 element
  26384. b=int2bigInt(0,0,a);
  26385. randBigInt_(b,n,s);
  26386. return b;
  26387. }
  26388. //Set b to an n-bit random BigInt. If s=1, then the most significant of those n bits is set to 1.
  26389. //Array b must be big enough to hold the result. Must have n>=1
  26390. function randBigInt_(b,n,s) {
  26391. var i,a;
  26392. for (i=0;i<b.length;i++)
  26393. b[i]=0;
  26394. a=Math.floor((n-1)/bpe)+1; //# array elements to hold the BigInt
  26395. for (i=0;i<a;i++) {
  26396. b[i]=Math.floor(Math.random()*(1<<(bpe-1)));
  26397. }
  26398. b[a-1] &= (2<<((n-1)%bpe))-1;
  26399. if (s==1)
  26400. b[a-1] |= (1<<((n-1)%bpe));
  26401. }
  26402. //Return the greatest common divisor of bigInts x and y (each with same number of elements).
  26403. function GCD(x,y) {
  26404. var xc,yc;
  26405. xc=dup(x);
  26406. yc=dup(y);
  26407. GCD_(xc,yc);
  26408. return xc;
  26409. }
  26410. //set x to the greatest common divisor of bigInts x and y (each with same number of elements).
  26411. //y is destroyed.
  26412. function GCD_(x,y) {
  26413. var i,xp,yp,A,B,C,D,q,sing;
  26414. if (T.length!=x.length)
  26415. T=dup(x);
  26416. sing=1;
  26417. while (sing) { //while y has nonzero elements other than y[0]
  26418. sing=0;
  26419. for (i=1;i<y.length;i++) //check if y has nonzero elements other than 0
  26420. if (y[i]) {
  26421. sing=1;
  26422. break;
  26423. }
  26424. if (!sing) break; //quit when y all zero elements except possibly y[0]
  26425. for (i=x.length;!x[i] && i>=0;i--); //find most significant element of x
  26426. xp=x[i];
  26427. yp=y[i];
  26428. A=1; B=0; C=0; D=1;
  26429. while ((yp+C) && (yp+D)) {
  26430. q =Math.floor((xp+A)/(yp+C));
  26431. qp=Math.floor((xp+B)/(yp+D));
  26432. if (q!=qp)
  26433. break;
  26434. t= A-q*C; A=C; C=t; // do (A,B,xp, C,D,yp) = (C,D,yp, A,B,xp) - q*(0,0,0, C,D,yp)
  26435. t= B-q*D; B=D; D=t;
  26436. t=xp-q*yp; xp=yp; yp=t;
  26437. }
  26438. if (B) {
  26439. copy_(T,x);
  26440. linComb_(x,y,A,B); //x=A*x+B*y
  26441. linComb_(y,T,D,C); //y=D*y+C*T
  26442. } else {
  26443. mod_(x,y);
  26444. copy_(T,x);
  26445. copy_(x,y);
  26446. copy_(y,T);
  26447. }
  26448. }
  26449. if (y[0]==0)
  26450. return;
  26451. t=modInt(x,y[0]);
  26452. copyInt_(x,y[0]);
  26453. y[0]=t;
  26454. while (y[0]) {
  26455. x[0]%=y[0];
  26456. t=x[0]; x[0]=y[0]; y[0]=t;
  26457. }
  26458. }
  26459. //do x=x**(-1) mod n, for bigInts x and n.
  26460. //If no inverse exists, it sets x to zero and returns 0, else it returns 1.
  26461. //The x array must be at least as large as the n array.
  26462. function inverseMod_(x,n) {
  26463. var k=1+2*Math.max(x.length,n.length);
  26464. if(!(x[0]&1) && !(n[0]&1)) { //if both inputs are even, then inverse doesn't exist
  26465. copyInt_(x,0);
  26466. return 0;
  26467. }
  26468. if (eg_u.length!=k) {
  26469. eg_u=new Array(k);
  26470. eg_v=new Array(k);
  26471. eg_A=new Array(k);
  26472. eg_B=new Array(k);
  26473. eg_C=new Array(k);
  26474. eg_D=new Array(k);
  26475. }
  26476. copy_(eg_u,x);
  26477. copy_(eg_v,n);
  26478. copyInt_(eg_A,1);
  26479. copyInt_(eg_B,0);
  26480. copyInt_(eg_C,0);
  26481. copyInt_(eg_D,1);
  26482. for (;;) {
  26483. while(!(eg_u[0]&1)) { //while eg_u is even
  26484. halve_(eg_u);
  26485. if (!(eg_A[0]&1) && !(eg_B[0]&1)) { //if eg_A==eg_B==0 mod 2
  26486. halve_(eg_A);
  26487. halve_(eg_B);
  26488. } else {
  26489. add_(eg_A,n); halve_(eg_A);
  26490. sub_(eg_B,x); halve_(eg_B);
  26491. }
  26492. }
  26493. while (!(eg_v[0]&1)) { //while eg_v is even
  26494. halve_(eg_v);
  26495. if (!(eg_C[0]&1) && !(eg_D[0]&1)) { //if eg_C==eg_D==0 mod 2
  26496. halve_(eg_C);
  26497. halve_(eg_D);
  26498. } else {
  26499. add_(eg_C,n); halve_(eg_C);
  26500. sub_(eg_D,x); halve_(eg_D);
  26501. }
  26502. }
  26503. if (!greater(eg_v,eg_u)) { //eg_v <= eg_u
  26504. sub_(eg_u,eg_v);
  26505. sub_(eg_A,eg_C);
  26506. sub_(eg_B,eg_D);
  26507. } else { //eg_v > eg_u
  26508. sub_(eg_v,eg_u);
  26509. sub_(eg_C,eg_A);
  26510. sub_(eg_D,eg_B);
  26511. }
  26512. if (equalsInt(eg_u,0)) {
  26513. while (negative(eg_C)) //make sure answer is nonnegative
  26514. add_(eg_C,n);
  26515. copy_(x,eg_C);
  26516. if (!equalsInt(eg_v,1)) { //if GCD_(x,n)!=1, then there is no inverse
  26517. copyInt_(x,0);
  26518. return 0;
  26519. }
  26520. return 1;
  26521. }
  26522. }
  26523. }
  26524. //return x**(-1) mod n, for integers x and n. Return 0 if there is no inverse
  26525. function inverseModInt(x,n) {
  26526. var a=1,b=0,t;
  26527. for (;;) {
  26528. if (x==1) return a;
  26529. if (x==0) return 0;
  26530. b-=a*Math.floor(n/x);
  26531. n%=x;
  26532. if (n==1) return b; //to avoid negatives, change this b to n-b, and each -= to +=
  26533. if (n==0) return 0;
  26534. a-=b*Math.floor(x/n);
  26535. x%=n;
  26536. }
  26537. }
  26538. //this deprecated function is for backward compatibility only.
  26539. function inverseModInt_(x,n) {
  26540. return inverseModInt(x,n);
  26541. }
  26542. //Given positive bigInts x and y, change the bigints v, a, and b to positive bigInts such that:
  26543. // v = GCD_(x,y) = a*x-b*y
  26544. //The bigInts v, a, b, must have exactly as many elements as the larger of x and y.
  26545. function eGCD_(x,y,v,a,b) {
  26546. var g=0;
  26547. var k=Math.max(x.length,y.length);
  26548. if (eg_u.length!=k) {
  26549. eg_u=new Array(k);
  26550. eg_A=new Array(k);
  26551. eg_B=new Array(k);
  26552. eg_C=new Array(k);
  26553. eg_D=new Array(k);
  26554. }
  26555. while(!(x[0]&1) && !(y[0]&1)) { //while x and y both even
  26556. halve_(x);
  26557. halve_(y);
  26558. g++;
  26559. }
  26560. copy_(eg_u,x);
  26561. copy_(v,y);
  26562. copyInt_(eg_A,1);
  26563. copyInt_(eg_B,0);
  26564. copyInt_(eg_C,0);
  26565. copyInt_(eg_D,1);
  26566. for (;;) {
  26567. while(!(eg_u[0]&1)) { //while u is even
  26568. halve_(eg_u);
  26569. if (!(eg_A[0]&1) && !(eg_B[0]&1)) { //if A==B==0 mod 2
  26570. halve_(eg_A);
  26571. halve_(eg_B);
  26572. } else {
  26573. add_(eg_A,y); halve_(eg_A);
  26574. sub_(eg_B,x); halve_(eg_B);
  26575. }
  26576. }
  26577. while (!(v[0]&1)) { //while v is even
  26578. halve_(v);
  26579. if (!(eg_C[0]&1) && !(eg_D[0]&1)) { //if C==D==0 mod 2
  26580. halve_(eg_C);
  26581. halve_(eg_D);
  26582. } else {
  26583. add_(eg_C,y); halve_(eg_C);
  26584. sub_(eg_D,x); halve_(eg_D);
  26585. }
  26586. }
  26587. if (!greater(v,eg_u)) { //v<=u
  26588. sub_(eg_u,v);
  26589. sub_(eg_A,eg_C);
  26590. sub_(eg_B,eg_D);
  26591. } else { //v>u
  26592. sub_(v,eg_u);
  26593. sub_(eg_C,eg_A);
  26594. sub_(eg_D,eg_B);
  26595. }
  26596. if (equalsInt(eg_u,0)) {
  26597. while (negative(eg_C)) { //make sure a (C) is nonnegative
  26598. add_(eg_C,y);
  26599. sub_(eg_D,x);
  26600. }
  26601. multInt_(eg_D,-1); ///make sure b (D) is nonnegative
  26602. copy_(a,eg_C);
  26603. copy_(b,eg_D);
  26604. leftShift_(v,g);
  26605. return;
  26606. }
  26607. }
  26608. }
  26609. //is bigInt x negative?
  26610. function negative(x) {
  26611. return ((x[x.length-1]>>(bpe-1))&1);
  26612. }
  26613. //is (x << (shift*bpe)) > y?
  26614. //x and y are nonnegative bigInts
  26615. //shift is a nonnegative integer
  26616. function greaterShift(x,y,shift) {
  26617. var i, kx=x.length, ky=y.length;
  26618. k=((kx+shift)<ky) ? (kx+shift) : ky;
  26619. for (i=ky-1-shift; i<kx && i>=0; i++) {
  26620. if (x[i]>0)
  26621. return 1; //if there are nonzeros in x to the left of the first column of y, then x is bigger
  26622. }
  26623. for (i=kx-1+shift; i<ky; i++){
  26624. if (y[i]>0)
  26625. return 0; //if there are nonzeros in y to the left of the first column of x, then x is not bigger
  26626. }
  26627. for (i=k-1; i>=shift; i--){
  26628. if (x[i-shift]>y[i]) {
  26629. return 1;
  26630. } else if(x[i-shift]<y[i]) {
  26631. return 0 ;
  26632. }
  26633. }
  26634. return 0;
  26635. }
  26636. //is x > y? (x and y both nonnegative)
  26637. function greater(x,y) {
  26638. var i;
  26639. var k=(x.length<y.length) ? x.length : y.length;
  26640. for (i=x.length;i<y.length;i++)
  26641. if (y[i])
  26642. return 0; //y has more digits
  26643. for (i=y.length;i<x.length;i++){
  26644. if (x[i])
  26645. return 1; //x has more digits
  26646. }
  26647. for (i=k-1;i>=0;i--){
  26648. if (x[i]>y[i]){
  26649. return 1;
  26650. } else if (x[i]<y[i]){
  26651. return 0;
  26652. }
  26653. }
  26654. return 0;
  26655. }
  26656. //divide x by y giving quotient q and remainder r. (q=floor(x/y), r=x mod y). All 4 are bigints.
  26657. //x must have at least one leading zero element.
  26658. //y must be nonzero.
  26659. //q and r must be arrays that are exactly the same length as x. (Or q can have more).
  26660. //Must have x.length >= y.length >= 2.
  26661. function divide_(x,y,q,r) {
  26662. var kx, ky;
  26663. var i,j,y1,y2,c,a,b;
  26664. copy_(r,x);
  26665. for (ky=y.length;y[ky-1]==0;ky--); //ky is number of elements in y, not including leading zeros
  26666. //normalize: ensure the most significant element of y has its highest bit set
  26667. b=y[ky-1];
  26668. for (a=0; b; a++)
  26669. b>>=1;
  26670. a=bpe-a; //a is how many bits to shift so that the high order bit of y is leftmost in its array element
  26671. leftShift_(y,a); //multiply both by 1<<a now, then divide both by that at the end
  26672. leftShift_(r,a);
  26673. //Rob Visser discovered a bug: the following line was originally just before the normalization.
  26674. for (kx=r.length;r[kx-1]==0 && kx>ky;kx--); //kx is number of elements in normalized x, not including leading zeros
  26675. copyInt_(q,0); // q=0
  26676. while (!greaterShift(y,r,kx-ky)) { // while (leftShift_(y,kx-ky) <= r) {
  26677. subShift_(r,y,kx-ky); // r=r-leftShift_(y,kx-ky)
  26678. q[kx-ky]++; // q[kx-ky]++;
  26679. } // }
  26680. for (i=kx-1; i>=ky; i--) {
  26681. if (r[i]==y[ky-1]){
  26682. q[i-ky]=mask;
  26683. }
  26684. else{
  26685. q[i-ky]=Math.floor((r[i]*radix+r[i-1])/y[ky-1]);
  26686. }
  26687. //The following for(;;) loop is equivalent to the commented while loop,
  26688. //except that the uncommented version avoids overflow.
  26689. //The commented loop comes from HAC, which assumes r[-1]==y[-1]==0
  26690. // while (q[i-ky]*(y[ky-1]*radix+y[ky-2]) > r[i]*radix*radix+r[i-1]*radix+r[i-2])
  26691. // q[i-ky]--;
  26692. for (;;) {
  26693. y2=(ky>1 ? y[ky-2] : 0)*q[i-ky];
  26694. c=y2>>bpe;
  26695. y2=y2 & mask;
  26696. y1=c+q[i-ky]*y[ky-1];
  26697. c=y1>>bpe;
  26698. y1=y1 & mask;
  26699. if (c==r[i] ? y1==r[i-1] ? y2>(i>1 ? r[i-2] : 0) : y1>r[i-1] : c>r[i]){
  26700. q[i-ky]--;
  26701. }
  26702. else{
  26703. break;
  26704. }
  26705. }
  26706. linCombShift_(r,y,-q[i-ky],i-ky); //r=r-q[i-ky]*leftShift_(y,i-ky)
  26707. if (negative(r)) {
  26708. addShift_(r,y,i-ky); //r=r+leftShift_(y,i-ky)
  26709. q[i-ky]--;
  26710. }
  26711. }
  26712. rightShift_(y,a); //undo the normalization step
  26713. rightShift_(r,a); //undo the normalization step
  26714. }
  26715. //do carries and borrows so each element of the bigInt x fits in bpe bits.
  26716. function carry_(x) {
  26717. var i,k,c,b;
  26718. k=x.length;
  26719. c=0;
  26720. for (i=0;i<k;i++) {
  26721. c+=x[i];
  26722. b=0;
  26723. if (c<0) {
  26724. b=-(c>>bpe);
  26725. c+=b*radix;
  26726. }
  26727. x[i]=c & mask;
  26728. c=(c>>bpe)-b;
  26729. }
  26730. }
  26731. //return x mod n for bigInt x and integer n.
  26732. function modInt(x,n) {
  26733. var i,c=0;
  26734. for (i=x.length-1; i>=0; i--)
  26735. c=(c*radix+x[i])%n;
  26736. return c;
  26737. }
  26738. //convert the integer t into a bigInt with at least the given number of bits.
  26739. //the returned array stores the bigInt in bpe-bit chunks, little endian (buff[0] is least significant word)
  26740. //Pad the array with leading zeros so that it has at least minSize elements.
  26741. //There will always be at least one leading 0 element.
  26742. function int2bigInt(t,bits,minSize) {
  26743. var i,k;
  26744. k=Math.ceil(bits/bpe)+1;
  26745. k=minSize>k ? minSize : k;
  26746. buff=new Array(k);
  26747. copyInt_(buff,t);
  26748. return buff;
  26749. }
  26750. //return the bigInt given a string representation in a given base.
  26751. //Pad the array with leading zeros so that it has at least minSize elements.
  26752. //If base=-1, then it reads in a space-separated list of array elements in decimal.
  26753. //The array will always have at least one leading zero, unless base=-1.
  26754. function str2bigInt(s,base,minSize) {
  26755. var d, i, j, x, y, kk;
  26756. var k=s.length;
  26757. if (base==-1) { //comma-separated list of array elements in decimal
  26758. x=new Array(0);
  26759. for (;;) {
  26760. y=new Array(x.length+1);
  26761. for (i=0;i<x.length;i++)
  26762. y[i+1]=x[i];
  26763. y[0]=parseInt(s,10);
  26764. x=y;
  26765. d=s.indexOf(',',0);
  26766. if (d<1)
  26767. break;
  26768. s=s.substring(d+1);
  26769. if (s.length==0)
  26770. break;
  26771. }
  26772. if (x.length<minSize) {
  26773. y=new Array(minSize);
  26774. copy_(y,x);
  26775. return y;
  26776. }
  26777. return x;
  26778. }
  26779. x=int2bigInt(0,base*k,0);
  26780. for (i=0;i<k;i++) {
  26781. d=digitsStr.indexOf(s.substring(i,i+1),0);
  26782. if (base<=36 && d>=36) //convert lowercase to uppercase if base<=36
  26783. d-=26;
  26784. if (d>=base || d<0) { //stop at first illegal character
  26785. break;
  26786. }
  26787. multInt_(x,base);
  26788. addInt_(x,d);
  26789. }
  26790. for (k=x.length;k>0 && !x[k-1];k--); //strip off leading zeros
  26791. k=minSize>k+1 ? minSize : k+1;
  26792. y=new Array(k);
  26793. kk=k<x.length ? k : x.length;
  26794. for (i=0;i<kk;i++)
  26795. y[i]=x[i];
  26796. for (;i<k;i++)
  26797. y[i]=0;
  26798. return y;
  26799. }
  26800. //is bigint x equal to integer y?
  26801. //y must have less than bpe bits
  26802. function equalsInt(x,y) {
  26803. var i;
  26804. if (x[0]!=y)
  26805. return 0;
  26806. for (i=1;i<x.length;i++)
  26807. if (x[i])
  26808. return 0;
  26809. return 1;
  26810. }
  26811. //are bigints x and y equal?
  26812. //this works even if x and y are different lengths and have arbitrarily many leading zeros
  26813. function equals(x,y) {
  26814. var i;
  26815. var k=x.length<y.length ? x.length : y.length;
  26816. for (i=0;i<k;i++)
  26817. if (x[i]!=y[i])
  26818. return 0;
  26819. if (x.length>y.length) {
  26820. for (;i<x.length;i++)
  26821. if (x[i])
  26822. return 0;
  26823. } else {
  26824. for (;i<y.length;i++)
  26825. if (y[i])
  26826. return 0;
  26827. }
  26828. return 1;
  26829. }
  26830. //is the bigInt x equal to zero?
  26831. function isZero(x) {
  26832. var i;
  26833. for (i=0;i<x.length;i++)
  26834. if (x[i])
  26835. return 0;
  26836. return 1;
  26837. }
  26838. //convert a bigInt into a string in a given base, from base 2 up to base 95.
  26839. //Base -1 prints the contents of the array representing the number.
  26840. function bigInt2str(x,base) {
  26841. if(digitsStr.length-1 < base) {
  26842. var str = "base "+(digitsStr.length-1)+" is max";
  26843. throw new Error(str);
  26844. }
  26845. var i,t,s="";
  26846. if (s6.length!=x.length) {
  26847. s6=dup(x);
  26848. }
  26849. else{
  26850. copy_(s6,x);
  26851. }
  26852. if (base==-1) { //return the list of array contents
  26853. for (i=x.length-1;i>0;i--){
  26854. s+=x[i]+',';
  26855. }
  26856. s+=x[0];
  26857. }
  26858. else { //return it in the given base
  26859. while (!isZero(s6)) {
  26860. t=divInt_(s6,base); //t=s6 % base; s6=floor(s6/base);
  26861. s=digitsStr.substring(t,t+1)+s;
  26862. }
  26863. }
  26864. if (s.length==0){
  26865. s="0";
  26866. }
  26867. return s;
  26868. }
  26869. //returns a duplicate of bigInt x
  26870. function dup(x) {
  26871. var i;
  26872. buff=new Array(x.length);
  26873. copy_(buff,x);
  26874. return buff;
  26875. }
  26876. //do x=y on bigInts x and y. x must be an array at least as big as y (not counting the leading zeros in y).
  26877. function copy_(x,y) {
  26878. var i;
  26879. var k=x.length<y.length ? x.length : y.length;
  26880. for (i=0;i<k;i++)
  26881. x[i]=y[i];
  26882. for (i=k;i<x.length;i++)
  26883. x[i]=0;
  26884. }
  26885. //do x=y on bigInt x and integer y.
  26886. function copyInt_(x,n) {
  26887. var i,c;
  26888. for (c=n,i=0;i<x.length;i++) {
  26889. x[i]=c & mask;
  26890. c>>=bpe;
  26891. }
  26892. }
  26893. //do x=x+n where x is a bigInt and n is an integer.
  26894. //x must be large enough to hold the result.
  26895. function addInt_(x,n) {
  26896. var i,k,c,b;
  26897. x[0]+=n;
  26898. k=x.length;
  26899. c=0;
  26900. for (i=0;i<k;i++) {
  26901. c+=x[i];
  26902. b=0;
  26903. if (c<0) {
  26904. b=-(c>>bpe);
  26905. c+=b*radix;
  26906. }
  26907. x[i]=c & mask;
  26908. c=(c>>bpe)-b;
  26909. if (!c) return; //stop carrying as soon as the carry is zero
  26910. }
  26911. }
  26912. //right shift bigInt x by n bits. 0 <= n < bpe.
  26913. function rightShift_(x,n) {
  26914. var i;
  26915. var k=Math.floor(n/bpe);
  26916. if (k) {
  26917. for (i=0;i<x.length-k;i++) //right shift x by k elements
  26918. x[i]=x[i+k];
  26919. for (;i<x.length;i++)
  26920. x[i]=0;
  26921. n%=bpe;
  26922. }
  26923. for (i=0;i<x.length-1;i++) {
  26924. x[i]=mask & ((x[i+1]<<(bpe-n)) | (x[i]>>n));
  26925. }
  26926. x[i]>>=n;
  26927. }
  26928. //do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement
  26929. function halve_(x) {
  26930. var i;
  26931. for (i=0;i<x.length-1;i++) {
  26932. x[i]=mask & ((x[i+1]<<(bpe-1)) | (x[i]>>1));
  26933. }
  26934. x[i]=(x[i]>>1) | (x[i] & (radix>>1)); //most significant bit stays the same
  26935. }
  26936. //left shift bigInt x by n bits.
  26937. function leftShift_(x,n) {
  26938. var i;
  26939. var k=Math.floor(n/bpe);
  26940. if (k) {
  26941. for (i=x.length; i>=k; i--) //left shift x by k elements
  26942. x[i]=x[i-k];
  26943. for (;i>=0;i--)
  26944. x[i]=0;
  26945. n%=bpe;
  26946. }
  26947. if (!n)
  26948. return;
  26949. for (i=x.length-1;i>0;i--) {
  26950. x[i]=mask & ((x[i]<<n) | (x[i-1]>>(bpe-n)));
  26951. }
  26952. x[i]=mask & (x[i]<<n);
  26953. }
  26954. //do x=x*n where x is a bigInt and n is an integer.
  26955. //x must be large enough to hold the result.
  26956. function multInt_(x,n) {
  26957. var i,k,c,b;
  26958. if (!n)
  26959. return;
  26960. k=x.length;
  26961. c=0;
  26962. for (i=0;i<k;i++) {
  26963. c+=x[i]*n;
  26964. b=0;
  26965. if (c<0) {
  26966. b=-(c>>bpe);
  26967. c+=b*radix;
  26968. }
  26969. x[i]=c & mask;
  26970. c=(c>>bpe)-b;
  26971. }
  26972. }
  26973. //do x=floor(x/n) for bigInt x and integer n, and return the remainder
  26974. function divInt_(x,n) {
  26975. var i,r=0,s;
  26976. for (i=x.length-1;i>=0;i--) {
  26977. s=r*radix+x[i];
  26978. x[i]=Math.floor(s/n);
  26979. r=s%n;
  26980. }
  26981. return r;
  26982. }
  26983. //do the linear combination x=a*x+b*y for bigInts x and y, and integers a and b.
  26984. //x must be large enough to hold the answer.
  26985. function linComb_(x,y,a,b) {
  26986. var i,c,k,kk;
  26987. k=x.length<y.length ? x.length : y.length;
  26988. kk=x.length;
  26989. for (c=0,i=0;i<k;i++) {
  26990. c+=a*x[i]+b*y[i];
  26991. x[i]=c & mask;
  26992. c>>=bpe;
  26993. }
  26994. for (i=k;i<kk;i++) {
  26995. c+=a*x[i];
  26996. x[i]=c & mask;
  26997. c>>=bpe;
  26998. }
  26999. }
  27000. //do the linear combination x=a*x+b*(y<<(ys*bpe)) for bigInts x and y, and integers a, b and ys.
  27001. //x must be large enough to hold the answer.
  27002. function linCombShift_(x,y,b,ys) {
  27003. var i,c,k,kk;
  27004. k=x.length<ys+y.length ? x.length : ys+y.length;
  27005. kk=x.length;
  27006. for (c=0,i=ys;i<k;i++) {
  27007. c+=x[i]+b*y[i-ys];
  27008. x[i]=c & mask;
  27009. c>>=bpe;
  27010. }
  27011. for (i=k;c && i<kk;i++) {
  27012. c+=x[i];
  27013. x[i]=c & mask;
  27014. c>>=bpe;
  27015. }
  27016. }
  27017. //do x=x+(y<<(ys*bpe)) for bigInts x and y, and integers a,b and ys.
  27018. //x must be large enough to hold the answer.
  27019. function addShift_(x,y,ys) {
  27020. var i,c,k,kk;
  27021. k=x.length<ys+y.length ? x.length : ys+y.length;
  27022. kk=x.length;
  27023. for (c=0,i=ys;i<k;i++) {
  27024. c+=x[i]+y[i-ys];
  27025. x[i]=c & mask;
  27026. c>>=bpe;
  27027. }
  27028. for (i=k;c && i<kk;i++) {
  27029. c+=x[i];
  27030. x[i]=c & mask;
  27031. c>>=bpe;
  27032. }
  27033. }
  27034. //do x=x-(y<<(ys*bpe)) for bigInts x and y, and integers a,b and ys.
  27035. //x must be large enough to hold the answer.
  27036. function subShift_(x,y,ys) {
  27037. var i,c,k,kk;
  27038. k=x.length<ys+y.length ? x.length : ys+y.length;
  27039. kk=x.length;
  27040. for (c=0,i=ys;i<k;i++) {
  27041. c+=x[i]-y[i-ys];
  27042. x[i]=c & mask;
  27043. c>>=bpe;
  27044. }
  27045. for (i=k;c && i<kk;i++) {
  27046. c+=x[i];
  27047. x[i]=c & mask;
  27048. c>>=bpe;
  27049. }
  27050. }
  27051. //do x=x-y for bigInts x and y.
  27052. //x must be large enough to hold the answer.
  27053. //negative answers will be 2s complement
  27054. function sub_(x,y) {
  27055. var i,c,k,kk;
  27056. k=x.length<y.length ? x.length : y.length;
  27057. for (c=0,i=0;i<k;i++) {
  27058. c+=x[i]-y[i];
  27059. x[i]=c & mask;
  27060. c>>=bpe;
  27061. }
  27062. for (i=k;c && i<x.length;i++) {
  27063. c+=x[i];
  27064. x[i]=c & mask;
  27065. c>>=bpe;
  27066. }
  27067. }
  27068. //do x=x+y for bigInts x and y.
  27069. //x must be large enough to hold the answer.
  27070. function add_(x,y) {
  27071. var i,c,k,kk;
  27072. k=x.length<y.length ? x.length : y.length;
  27073. for (c=0,i=0;i<k;i++) {
  27074. c+=x[i]+y[i];
  27075. x[i]=c & mask;
  27076. c>>=bpe;
  27077. }
  27078. for (i=k;c && i<x.length;i++) {
  27079. c+=x[i];
  27080. x[i]=c & mask;
  27081. c>>=bpe;
  27082. }
  27083. }
  27084. //do x=x*y for bigInts x and y. This is faster when y<x.
  27085. function mult_(x,y) {
  27086. var i;
  27087. if (ss.length!=2*x.length)
  27088. ss=new Array(2*x.length);
  27089. copyInt_(ss,0);
  27090. for (i=0;i<y.length;i++)
  27091. if (y[i])
  27092. linCombShift_(ss,x,y[i],i); //ss=1*ss+y[i]*(x<<(i*bpe))
  27093. copy_(x,ss);
  27094. }
  27095. //do x=x mod n for bigInts x and n.
  27096. function mod_(x,n) {
  27097. if (s4.length!=x.length){
  27098. s4=dup(x);
  27099. }
  27100. else{
  27101. copy_(s4,x);
  27102. }
  27103. if (s5.length!=x.length){
  27104. s5=dup(x);
  27105. }
  27106. divide_(s4,n,s5,x); //x = remainder of s4 / n
  27107. }
  27108. //do x=x*y mod n for bigInts x,y,n.
  27109. //for greater speed, let y<x.
  27110. function multMod_(x,y,n) {
  27111. var i;
  27112. if (s0.length!=2*x.length)
  27113. s0=new Array(2*x.length);
  27114. copyInt_(s0,0);
  27115. for (i=0;i<y.length;i++)
  27116. if (y[i])
  27117. linCombShift_(s0,x,y[i],i); //s0=1*s0+y[i]*(x<<(i*bpe))
  27118. mod_(s0,n);
  27119. copy_(x,s0);
  27120. }
  27121. //do x=x*x mod n for bigInts x,n.
  27122. function squareMod_(x,n) {
  27123. var i,j,d,c,kx,kn,k;
  27124. for (kx=x.length; kx>0 && !x[kx-1]; kx--); //ignore leading zeros in x
  27125. k=kx>n.length ? 2*kx : 2*n.length; //k=# elements in the product, which is twice the elements in the larger of x and n
  27126. if (s0.length!=k)
  27127. s0=new Array(k);
  27128. copyInt_(s0,0);
  27129. for (i=0;i<kx;i++) {
  27130. c=s0[2*i]+x[i]*x[i];
  27131. s0[2*i]=c & mask;
  27132. c>>=bpe;
  27133. for (j=i+1;j<kx;j++) {
  27134. c=s0[i+j]+2*x[i]*x[j]+c;
  27135. s0[i+j]=(c & mask);
  27136. c>>=bpe;
  27137. }
  27138. s0[i+kx]=c;
  27139. }
  27140. mod_(s0,n);
  27141. copy_(x,s0);
  27142. }
  27143. //return x with exactly k leading zero elements
  27144. function trim(x,k) {
  27145. var i,y;
  27146. for (i=x.length; i>0 && !x[i-1]; i--);
  27147. y=new Array(i+k);
  27148. copy_(y,x);
  27149. return y;
  27150. }
  27151. //do x=x**y mod n, where x,y,n are bigInts and ** is exponentiation. 0**0=1.
  27152. //this is faster when n is odd. x usually needs to have as many elements as n.
  27153. function powMod_(x,y,n) {
  27154. var k1,k2,kn,np;
  27155. if(s7.length!=n.length)
  27156. s7=dup(n);
  27157. //for even modulus, use a simple square-and-multiply algorithm,
  27158. //rather than using the more complex Montgomery algorithm.
  27159. if ((n[0]&1)==0) {
  27160. copy_(s7,x);
  27161. copyInt_(x,1);
  27162. while(!equalsInt(y,0)) {
  27163. if (y[0]&1)
  27164. multMod_(x,s7,n);
  27165. divInt_(y,2);
  27166. squareMod_(s7,n);
  27167. }
  27168. return;
  27169. }
  27170. //calculate np from n for the Montgomery multiplications
  27171. copyInt_(s7,0);
  27172. for (kn=n.length;kn>0 && !n[kn-1];kn--);
  27173. np=radix-inverseModInt(modInt(n,radix),radix);
  27174. s7[kn]=1;
  27175. multMod_(x ,s7,n); // x = x * 2**(kn*bp) mod n
  27176. if (s3.length!=x.length){
  27177. s3=dup(x);
  27178. }
  27179. else{
  27180. copy_(s3,x);
  27181. }
  27182. for (k1=y.length-1;k1>0 & !y[k1]; k1--); //k1=first nonzero element of y
  27183. if (y[k1]==0) { //anything to the 0th power is 1
  27184. copyInt_(x,1);
  27185. return;
  27186. }
  27187. for (k2=1<<(bpe-1);k2 && !(y[k1] & k2); k2>>=1); //k2=position of first 1 bit in y[k1]
  27188. for (;;) {
  27189. if (!(k2>>=1)) { //look at next bit of y
  27190. k1--;
  27191. if (k1<0) {
  27192. mont_(x,one,n,np);
  27193. return;
  27194. }
  27195. k2=1<<(bpe-1);
  27196. }
  27197. mont_(x,x,n,np);
  27198. if (k2 & y[k1]) //if next bit is a 1
  27199. mont_(x,s3,n,np);
  27200. }
  27201. }
  27202. //do x=x*y*Ri mod n for bigInts x,y,n,
  27203. // where Ri = 2**(-kn*bpe) mod n, and kn is the
  27204. // number of elements in the n array, not
  27205. // counting leading zeros.
  27206. //x array must have at least as many elemnts as the n array
  27207. //It's OK if x and y are the same variable.
  27208. //must have:
  27209. // x,y < n
  27210. // n is odd
  27211. // np = -(n^(-1)) mod radix
  27212. function mont_(x,y,n,np) {
  27213. var i,j,c,ui,t,ks;
  27214. var kn=n.length;
  27215. var ky=y.length;
  27216. if (sa.length!=kn)
  27217. sa=new Array(kn);
  27218. copyInt_(sa,0);
  27219. for (;kn>0 && n[kn-1]==0;kn--); //ignore leading zeros of n
  27220. for (;ky>0 && y[ky-1]==0;ky--); //ignore leading zeros of y
  27221. ks=sa.length-1; //sa will never have more than this many nonzero elements.
  27222. //the following loop consumes 95% of the runtime for randTruePrime_() and powMod_() for large numbers
  27223. for (i=0; i<kn; i++) {
  27224. t=sa[0]+x[i]*y[0];
  27225. ui=((t & mask) * np) & mask; //the inner "& mask" was needed on Safari (but not MSIE) at one time
  27226. c=(t+ui*n[0]) >> bpe;
  27227. t=x[i];
  27228. //do sa=(sa+x[i]*y+ui*n)/b where b=2**bpe. Loop is unrolled 5-fold for speed
  27229. j=1;
  27230. for (;j<ky-4;) { c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++;
  27231. c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++;
  27232. c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++;
  27233. c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++;
  27234. c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++; }
  27235. for (;j<ky;) { c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++; }
  27236. for (;j<kn-4;) { c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++;
  27237. c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++;
  27238. c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++;
  27239. c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++;
  27240. c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++; }
  27241. for (;j<kn;) { c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++; }
  27242. for (;j<ks;) { c+=sa[j]; sa[j-1]=c & mask; c>>=bpe; j++; }
  27243. sa[j-1]=c & mask;
  27244. }
  27245. if (!greater(n,sa))
  27246. sub_(sa,n);
  27247. copy_(x,sa);
  27248. }
  27249. BigInt = module.exports = {
  27250. 'add': add,
  27251. 'addInt': addInt,
  27252. 'bigInt2str': bigInt2str,
  27253. 'bitSize': bitSize,
  27254. 'copy': copy_,
  27255. 'copyInt': copyInt_,
  27256. 'dup': dup,
  27257. 'div': divide_,
  27258. 'equals': equals,
  27259. 'equalsInt': equalsInt,
  27260. 'expand': expand,
  27261. 'findPrimes': findPrimes,
  27262. 'GCD': GCD,
  27263. 'greater': greater,
  27264. 'greaterShift': greaterShift,
  27265. 'int2bigInt': int2bigInt,
  27266. 'inverseMod': inverseMod,
  27267. 'inverseModInt': inverseModInt,
  27268. 'isZero': isZero,
  27269. 'millerRabin': millerRabin,
  27270. 'millerRabinInt': millerRabinInt,
  27271. 'mod': mod,
  27272. 'modInt': modInt,
  27273. 'mult': mult_,
  27274. 'multMod': multMod,
  27275. 'negative': negative,
  27276. 'powMod': powMod,
  27277. 'randBigInt': randBigInt,
  27278. 'randTruePrime': randTruePrime,
  27279. 'randProbPrime': randProbPrime,
  27280. 'leftShift': leftShift_,
  27281. 'rightShift': rightShift_,
  27282. 'str2bigInt': str2bigInt,
  27283. 'sub': sub,
  27284. 'trim': trim
  27285. };
  27286. },{}],175:[function(require,module,exports){
  27287. var basex = require('base-x')
  27288. var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
  27289. module.exports = basex(ALPHABET)
  27290. },{"base-x":177}],176:[function(require,module,exports){
  27291. var Buffer = require("buffer").Buffer;
  27292. var crypto = require("crypto");
  27293. var BP = {};
  27294. BP.bitSize = function() {
  27295. return (this.length * 8);
  27296. }
  27297. BP.add = function(buf) {
  27298. var n1 = bigi.str2bigInt(this.toString("hex"), 16, (this.length * 8));
  27299. var n2 = bigi.str2bigInt(buf.toString("hex"), 16, (buf.length * 8));
  27300. var res = bigi.add(n1, n2);
  27301. var tt = bigi.bigInt2str(res, 16);
  27302. var n = nb(tt.length % 2 === 0 ? tt : "0" + tt, 'hex');
  27303. return n
  27304. }
  27305. BP.sub = function(buf) {
  27306. var n1 = bigi.str2bigInt(this.toString("hex"), 16, (this.length * 8));
  27307. var n2 = bigi.str2bigInt(buf.toString("hex"), 16, (buf.length * 8));
  27308. var res = bigi.sub(n1, n2);
  27309. var tt = bigi.bigInt2str(res, 16);
  27310. var n = nb(tt.length % 2 === 0 ? tt : "0" + tt, 'hex');
  27311. return n
  27312. }
  27313. var bii = require("big-integer");
  27314. BP.nextPrime = function(buf) {
  27315. var as = buf.add(nb("1",10));
  27316. var aa = as.toBase(10);
  27317. var res = bii(aa).isPrime()
  27318. var ff= ["0","2","4","5","6","8"];
  27319. while(!res){
  27320. as = as.add(nb("1",10));
  27321. aa = as.toBase(10);
  27322. var las = aa.substring(aa.length-1);
  27323. if(ff.indexOf(las+"") === -1 ){
  27324. res = bii(aa).isPrime()
  27325. }
  27326. }
  27327. return as
  27328. }
  27329. BP.mult = function(buf) {
  27330. var string = this.toString('hex');
  27331. var asa = bigi.str2bigInt(string, 16, (this.length * 8));
  27332. var asa2;
  27333. if (typeof(buf) === "number") {
  27334. asa2 = bigi.str2bigInt("" + buf, 10);
  27335. } else {
  27336. var string2 = buf.toString('hex');
  27337. asa2 = bigi.str2bigInt(string2, 16, (buf.length * 8));
  27338. }
  27339. bigi.mult(asa, asa2);
  27340. var ss = bigi.bigInt2str(asa, 16);
  27341. var re = nb(ss.length % 2 === 0 ? ss : "0" + ss, 'hex');
  27342. return re;
  27343. }
  27344. BP.div = function(buf) {
  27345. var n1 = bigi.str2bigInt(this.toString("hex"), 16, (this.length * 8));
  27346. var n2 = bigi.str2bigInt(buf.toString("hex"), 16, (buf.length * 8));
  27347. var q = bigi.str2bigInt("0", 16, n1.length * 8);
  27348. var r = bigi.str2bigInt("0", 16, n2.length * 8);
  27349. bigi.div(n1, n2, q, r);
  27350. var qq = bigi.bigInt2str(q, 16);
  27351. var rr = bigi.bigInt2str(r, 16);
  27352. var ret = [nb(qq.length % 2 === 0 ? qq : "0" + qq, 'hex'), nb(rr.length % 2 === 0 ? rr : "0" + rr, 'hex')];
  27353. return ret;
  27354. }
  27355. BP.gcd = function(buf) {
  27356. var n1 = bigi.str2bigInt(this.toString("hex"), 16, (this.length * 8));
  27357. var n2 = bigi.str2bigInt(buf.toString("hex"), 16, (buf.length * 8));
  27358. var gg = bigi.GCD(n1, n2);
  27359. var qq = bigi.bigInt2str(gg, 16);
  27360. return nb(qq.length % 2 === 0 ? qq : "0" + qq, 'hex');
  27361. }
  27362. BP.mod = function(buf) {
  27363. var n1 = bigi.str2bigInt(this.toString("hex"), 16, (this.length * 8));
  27364. var n2 = bigi.str2bigInt(buf.toString("hex"), 16, (buf.length * 8));
  27365. var gg = bigi.mod(n1, n2);
  27366. var qq = bigi.bigInt2str(gg, 16);
  27367. return nb(qq.length % 2 === 0 ? qq : "0" + qq, 'hex');
  27368. }
  27369. BP.powMod = function(buf, bufn) {
  27370. var n1 = bigi.str2bigInt(this.toString("hex"), 16, (this.length * 8));
  27371. var n2 = bigi.str2bigInt(buf.toString("hex"), 16, (buf.length * 8));
  27372. var n3 = bigi.str2bigInt(bufn.toString("hex"), 16, (bufn.length * 8));
  27373. var gg = bigi.powMod(n1, n2, n3);
  27374. var qq = bigi.bigInt2str(gg, 16);
  27375. return nb(qq.length % 2 === 0 ? qq : "0" + qq, 'hex');
  27376. }
  27377. BP.leftShift = function(n) {
  27378. var n1 = bigi.str2bigInt(this.toString("hex"), 16, (this.length * 8));
  27379. var gg = bigi.leftShift(n1, n);
  27380. var qq = bigi.bigInt2str(n1, 16);
  27381. return nb(qq.length % 2 === 0 ? qq : "0" + qq, 'hex');
  27382. }
  27383. BP.rightShift = function(n) {
  27384. var n1 = bigi.str2bigInt(this.toString("hex"), 16, (this.length * 8));
  27385. var gg = bigi.rightShift(n1, n);
  27386. var qq = bigi.bigInt2str(n1, 16);
  27387. return nb(qq.length % 2 === 0 ? qq : "0" + qq, 'hex');
  27388. }
  27389. BP.SHA256 = function(encoding) {
  27390. var encoding = encoding || null;
  27391. var h = crypto.createHash('sha256');
  27392. h.update(new Buffer(this));
  27393. return nb(h.digest(encoding));
  27394. }
  27395. BP.SHA1 = function(encoding) {
  27396. var encoding = encoding || null;
  27397. var h = crypto.createHash('sha1');
  27398. h.update(this);
  27399. return nb(h.digest(encoding));
  27400. }
  27401. BP.SHA224 = function(encoding) {
  27402. var encoding = encoding || null;
  27403. var h = crypto.createHash('sha224');
  27404. h.update(this);
  27405. return nb(h.digest(encoding));
  27406. }
  27407. BP.SHA256 = function(encoding) {
  27408. var encoding = encoding || null;
  27409. var h = crypto.createHash('sha256');
  27410. h.update(this);
  27411. return nb(h.digest(encoding));
  27412. }
  27413. BP.SHA384 = function(encoding) {
  27414. var encoding = encoding || null;
  27415. var h = crypto.createHash('sha384');
  27416. h.update(this);
  27417. return nb(h.digest(encoding));
  27418. }
  27419. BP.SHA512 = function(encoding) {
  27420. var encoding = encoding || null;
  27421. var h = crypto.createHash('sha512');
  27422. h.update(this);
  27423. return nb(h.digest(encoding));
  27424. }
  27425. BP.MD5 = function(encoding) {
  27426. var encoding = encoding || null;
  27427. var h = crypto.createHash('md5');
  27428. h.update(this);
  27429. return h.digest(encoding);
  27430. }
  27431. BP.RIPE = function(encoding) {
  27432. var encoding = encoding || null;
  27433. var h = crypto.createHash('ripemd');
  27434. h.update(this);
  27435. return nb(h.digest(encoding));
  27436. }
  27437. BP.RIPE160 = function(encoding) {
  27438. var encoding = encoding || null;
  27439. var h = crypto.createHash('ripemd160');
  27440. h.update(this);
  27441. return nb(h.digest(encoding));
  27442. }
  27443. BP.WHIRLPOOL = function(encoding) {
  27444. var encoding = encoding || null;
  27445. var h = crypto.createHash('whirlpool');
  27446. h.update(this);
  27447. return nb(h.digest(encoding));
  27448. }
  27449. BP.prepend = function(buf) {
  27450. var tmp = nb(this.length + buf.length);
  27451. for (var i = 0; i < buf.length; i++) {
  27452. tmp[i] = buf[i];
  27453. }
  27454. for (var i = 0; i < this.length; i++) {
  27455. tmp[buf.length + i] = this[i];
  27456. }
  27457. return tmp;
  27458. }
  27459. BP.append = function(buf, baselength) {
  27460. var nlen = this.length + buf.length;
  27461. if (baselength) {
  27462. nlen = Math.ceil((nlen) / baselength) * baselength;
  27463. }
  27464. var tmp = nb(nlen);
  27465. tmp.fill(0);
  27466. for (var i = 0; i < this.length; i++) {
  27467. tmp[i] = this[i];
  27468. }
  27469. for (var i = 0; i < buf.length; i++) {
  27470. tmp[this.length + i] = buf[i];
  27471. }
  27472. return tmp;
  27473. }
  27474. BP.XOR = function(buf) {
  27475. var nn = nb(this.length);
  27476. var mi = buf.length;
  27477. var fi = 0;
  27478. var n = this.length;
  27479. for (var i = 0; i < n; i++) {
  27480. if (i > mi) {
  27481. fi = 0;
  27482. }
  27483. nn[i] = this[i] ^ (buf[fi]);
  27484. fi++;
  27485. }
  27486. return nn;
  27487. }
  27488. BP.AND = function(buf) {
  27489. var nn = nb(this.length);
  27490. var mi = buf.length;
  27491. var fi = 0;
  27492. var n = this.length;
  27493. for (var i = 0; i < n; i++) {
  27494. if (i > mi) {
  27495. fi = 0;
  27496. }
  27497. nn[i] = this[i] & (buf[fi]);
  27498. fi++;
  27499. }
  27500. return nn;
  27501. }
  27502. BP.OR = function(buf) {
  27503. var nn = nb(this.length);
  27504. var mi = buf.length;
  27505. var fi = 0;
  27506. var n = this.length;
  27507. for (var i = 0; i < n; i++) {
  27508. if (i > mi) {
  27509. fi = 0;
  27510. }
  27511. nn[i] = this[i] | (buf[fi]);
  27512. fi++;
  27513. }
  27514. return nn;
  27515. }
  27516. BP.clone = function() {
  27517. var n = nb(this.length);
  27518. for (var i = 0; i < this.length; i++) {
  27519. n[i] = this[i];
  27520. }
  27521. return n;
  27522. }
  27523. var bigi = require("./bigint");
  27524. BP.toBase = function(base) {
  27525. var ss = this.toString("hex");
  27526. var asa = bigi.str2bigInt(ss, 16);
  27527. var s = bigi.bigInt2str(asa, base);
  27528. return s;
  27529. }
  27530. BP.fromBase = function(string, base) {
  27531. var asa = bigi.str2bigInt(string, base);
  27532. var ss = bigi.bigInt2str(asa, 16);
  27533. var re = nb(ss.length % 2 === 0 ? ss : "0" + ss, 'hex');
  27534. return re;
  27535. }
  27536. BP.fromBase2 = function(base) {
  27537. var string = this.toString();
  27538. var asa = bigi.str2bigInt(string, base);
  27539. var ss = bigi.bigInt2str(asa, 16);
  27540. var re = nb(ss.length % 2 === 0 ? ss : "0" + ss, 'hex');
  27541. return re;
  27542. }
  27543. var zlib = require('zlib');
  27544. BP.zip = function(callback) {
  27545. zlib.deflate(this, function(err, buffer) {
  27546. callback(err, nb(buffer));
  27547. });
  27548. }
  27549. BP.unzip = function(callback) {
  27550. zlib.unzip(this, function(err, buffer) {
  27551. callback(err, nb(buffer));
  27552. });
  27553. }
  27554. BP.hexdump = function() {
  27555. return hexdump.apply(this, arguments);
  27556. }
  27557. function hexdump(buf, showascii, perline, space, padit, linenums, showtype, html) {
  27558. var showtype = showtype || false;
  27559. var html = html || false;
  27560. var s = "";
  27561. if (showtype) {
  27562. s += "type: " + typeof(buf) + " " + ((buf instanceof Buffer)) + "\n";
  27563. }
  27564. if (typeof(buf) !== "object") {
  27565. buf = new Buffer(buf);
  27566. }
  27567. var usebuf;
  27568. var perline = (perline === 0 || perline) ? perline : 32;
  27569. var space = (space === 0 || space) ? space : 8;
  27570. var showascii = showascii || false;
  27571. var linenums = linenums || false;
  27572. if (perline === 0) {
  27573. perline = buf.length;
  27574. }
  27575. usebuf = buf;
  27576. if (padit) {
  27577. var shouldbelength = Math.ceil(buf.length / perline) * perline;
  27578. var nbuf = new Buffer(shouldbelength);
  27579. nbuf.fill(0);
  27580. buf.copy(nbuf, 0, 0, buf.length);
  27581. usebuf = nbuf;
  27582. }
  27583. var tl = Math.ceil(buf.length / perline);
  27584. var mask = [127, 129, 141, 143, 144, 157, 160, 173, 184, 185, 186];
  27585. var allow = [];
  27586. for (var i = 0; i < tl; i++) {
  27587. var mx = (i * perline) + perline;
  27588. if (mx > usebuf.length) {
  27589. mx = usebuf.length;
  27590. }
  27591. if (linenums) {
  27592. s += intToHex(i * perline, 3) + " ";
  27593. }
  27594. var a = "";
  27595. var t = usebuf.slice(i * perline, mx);
  27596. for (var y = 0; y < t.length; y++) {
  27597. s += int2hex(t[y]);
  27598. if (html) {
  27599. if (((t[y] > 31) && (mask.indexOf(t[y]) === -1))) {
  27600. a += "&#" + t[y] + ";";
  27601. } else {
  27602. a += ".";
  27603. }
  27604. } else {
  27605. if (((t[y] > 31) && (t[y] < 127))) {
  27606. a += String.fromCharCode(t[y]);
  27607. } else {
  27608. a += ".";
  27609. }
  27610. }
  27611. if (y % space === (space - 1)) {
  27612. s += " ";
  27613. a += " ";
  27614. }
  27615. }
  27616. if (showascii) {
  27617. s += " | " + a;
  27618. }
  27619. if (tl > 1) {
  27620. s += "\n";
  27621. }
  27622. }
  27623. return s;
  27624. }
  27625. function intToHex(integera, bytes) {
  27626. var bytes = bytes || 1;
  27627. integera = integera.toString(16);
  27628. if (integera.length % (bytes * 2) !== 0) {
  27629. while (integera.length < bytes * 2) {
  27630. integera = '0' + integera;
  27631. }
  27632. }
  27633. return integera;
  27634. };
  27635. function int2hex(integer) {
  27636. integer = integer.toString(16);
  27637. if (integer.length % 2 !== 0) {
  27638. integer = '0' + integer;
  27639. }
  27640. return integer;
  27641. };
  27642. function int2word(integer) {
  27643. integer = integer.toString(16);
  27644. if (integer.length % 8 !== 0) {
  27645. while (integer.length < 8) {
  27646. integer = '0' + integer;
  27647. }
  27648. }
  27649. return integer;
  27650. };
  27651. function int2longword(integer) {
  27652. integer = integer.toString(16);
  27653. if (integer.length % 16 !== 0) {
  27654. while (integer.length < 16) {
  27655. integer = '0' + integer;
  27656. }
  27657. }
  27658. return integer;
  27659. };
  27660. var bs58 = require("./bs58");
  27661. var decoders = {
  27662. "base58": function(input) {
  27663. return bs58.decode(input);
  27664. }
  27665. }
  27666. var encoders = {
  27667. "base58": function(input) {
  27668. return bs58.encode(input);
  27669. }
  27670. }
  27671. BP.toBase58 = function() {
  27672. return encoders.base58(this);
  27673. }
  27674. BP.toBase64 = function() {
  27675. return this.toString('base64');
  27676. }
  27677. for (var p in BP) {
  27678. Buffer.prototype[p] = BP[p];
  27679. }
  27680. var encodings = ["ascii", "utf8", "utf16le", "ucs2", "base64", "binary", "hex"];
  27681. var specialencodings = ["base58"];
  27682. function nb(a, encoding, minsize) {
  27683. if (typeof(a) === "object") {
  27684. if (typeof(a.bitSize) === "function") {
  27685. return a;
  27686. }
  27687. }
  27688. var holder;
  27689. if (!encoding && !minsize && typeof(a) === "number") {
  27690. holder = new Buffer(a);
  27691. } else {
  27692. if (!encoding) {
  27693. encoding = 'utf8';
  27694. }
  27695. if (encodings.indexOf(encoding) > -1) {
  27696. holder = new Buffer(a + "", encoding);
  27697. if (typeof(a) === "number") {
  27698. holder.fill(0);
  27699. }
  27700. if (minsize) {
  27701. var hholder = new Buffer(minsize);
  27702. hholder.fill(0)
  27703. holder.copy(hholder, hholder.length - holder.length);
  27704. holder = hholder;
  27705. }
  27706. } else {
  27707. if (specialencodings.indexOf(encoding) > -1 && decoders[encoding]) {
  27708. var tt = decoders[encoding](a);
  27709. holder = new Buffer(tt);
  27710. } else {
  27711. var base = parseInt(encoding);
  27712. var bb = bigi.str2bigInt(a, base);
  27713. var ss = bigi.bigInt2str(bb, 16);
  27714. holder = new Buffer(ss.length % 2 === 0 ? ss : "0" + ss, 'hex');
  27715. if (minsize) {
  27716. var hholder = new Buffer(minsize);
  27717. hholder.fill(0)
  27718. holder.copy(hholder, hholder.length - holder.length);
  27719. holder = hholder;
  27720. }
  27721. }
  27722. }
  27723. }
  27724. if (Buffer._useTypedArrays) {
  27725. for (var p in BP) {
  27726. holder[p] = BP[p];
  27727. }
  27728. }
  27729. return holder;
  27730. }
  27731. module.exports = nb;
  27732. /*
  27733. 'ascii' - for 7 bit ASCII data only. This encoding method is very fast, and will strip the high bit if set.
  27734. Note that when converting from string to buffer, this encoding converts a null character ('\0' or '\u0000') into 0x20 (character code of a space). If you want to convert a null character into 0x00, you should use 'utf8'.
  27735. 'utf8' - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.
  27736. 'utf16le' - 2 or 4 bytes, little endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported.
  27737. 'ucs2' - Alias of 'utf16le'.
  27738. 'base64' - Base64 string encoding.
  27739. 'binary' - A way of encoding raw binary data into strings by using only the first 8 bits of each character. This encoding method is deprecated and should be avoided in favor of Buffer objects where possible. This encoding will be removed in future versions of Node.
  27740. 'hex' - Encode each byte as two hexadecimal characters.
  27741. */
  27742. },{"./bigint":174,"./bs58":175,"big-integer":178,"buffer":50,"crypto":59,"zlib":48}],177:[function(require,module,exports){
  27743. // base-x encoding
  27744. // Forked from https://github.com/cryptocoinjs/bs58
  27745. // Originally written by Mike Hearn for BitcoinJ
  27746. // Copyright (c) 2011 Google Inc
  27747. // Ported to JavaScript by Stefan Thomas
  27748. // Merged Buffer refactorings from base58-native by Stephen Pair
  27749. // Copyright (c) 2013 BitPay Inc
  27750. var Buffer = require('safe-buffer').Buffer
  27751. module.exports = function base (ALPHABET) {
  27752. var ALPHABET_MAP = {}
  27753. var BASE = ALPHABET.length
  27754. var LEADER = ALPHABET.charAt(0)
  27755. // pre-compute lookup table
  27756. for (var z = 0; z < ALPHABET.length; z++) {
  27757. var x = ALPHABET.charAt(z)
  27758. if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous')
  27759. ALPHABET_MAP[x] = z
  27760. }
  27761. function encode (source) {
  27762. if (source.length === 0) return ''
  27763. var digits = [0]
  27764. for (var i = 0; i < source.length; ++i) {
  27765. for (var j = 0, carry = source[i]; j < digits.length; ++j) {
  27766. carry += digits[j] << 8
  27767. digits[j] = carry % BASE
  27768. carry = (carry / BASE) | 0
  27769. }
  27770. while (carry > 0) {
  27771. digits.push(carry % BASE)
  27772. carry = (carry / BASE) | 0
  27773. }
  27774. }
  27775. var string = ''
  27776. // deal with leading zeros
  27777. for (var k = 0; source[k] === 0 && k < source.length - 1; ++k) string += LEADER
  27778. // convert digits to a string
  27779. for (var q = digits.length - 1; q >= 0; --q) string += ALPHABET[digits[q]]
  27780. return string
  27781. }
  27782. function decodeUnsafe (string) {
  27783. if (typeof string !== 'string') throw new TypeError('Expected String')
  27784. if (string.length === 0) return Buffer.allocUnsafe(0)
  27785. var bytes = [0]
  27786. for (var i = 0; i < string.length; i++) {
  27787. var value = ALPHABET_MAP[string[i]]
  27788. if (value === undefined) return
  27789. for (var j = 0, carry = value; j < bytes.length; ++j) {
  27790. carry += bytes[j] * BASE
  27791. bytes[j] = carry & 0xff
  27792. carry >>= 8
  27793. }
  27794. while (carry > 0) {
  27795. bytes.push(carry & 0xff)
  27796. carry >>= 8
  27797. }
  27798. }
  27799. // deal with leading zeros
  27800. for (var k = 0; string[k] === LEADER && k < string.length - 1; ++k) {
  27801. bytes.push(0)
  27802. }
  27803. return Buffer.from(bytes.reverse())
  27804. }
  27805. function decode (string) {
  27806. var buffer = decodeUnsafe(string)
  27807. if (buffer) return buffer
  27808. throw new Error('Non-base' + BASE + ' character')
  27809. }
  27810. return {
  27811. encode: encode,
  27812. decodeUnsafe: decodeUnsafe,
  27813. decode: decode
  27814. }
  27815. }
  27816. },{"safe-buffer":179}],178:[function(require,module,exports){
  27817. var bigInt = (function (undefined) {
  27818. "use strict";
  27819. var BASE = 1e7,
  27820. LOG_BASE = 7,
  27821. MAX_INT = 9007199254740992,
  27822. MAX_INT_ARR = smallToArray(MAX_INT),
  27823. LOG_MAX_INT = Math.log(MAX_INT);
  27824. function Integer(v, radix) {
  27825. if (typeof v === "undefined") return Integer[0];
  27826. if (typeof radix !== "undefined") return +radix === 10 ? parseValue(v) : parseBase(v, radix);
  27827. return parseValue(v);
  27828. }
  27829. function BigInteger(value, sign) {
  27830. this.value = value;
  27831. this.sign = sign;
  27832. this.isSmall = false;
  27833. }
  27834. BigInteger.prototype = Object.create(Integer.prototype);
  27835. function SmallInteger(value) {
  27836. this.value = value;
  27837. this.sign = value < 0;
  27838. this.isSmall = true;
  27839. }
  27840. SmallInteger.prototype = Object.create(Integer.prototype);
  27841. function isPrecise(n) {
  27842. return -MAX_INT < n && n < MAX_INT;
  27843. }
  27844. function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes
  27845. if (n < 1e7)
  27846. return [n];
  27847. if (n < 1e14)
  27848. return [n % 1e7, Math.floor(n / 1e7)];
  27849. return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)];
  27850. }
  27851. function arrayToSmall(arr) { // If BASE changes this function may need to change
  27852. trim(arr);
  27853. var length = arr.length;
  27854. if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {
  27855. switch (length) {
  27856. case 0: return 0;
  27857. case 1: return arr[0];
  27858. case 2: return arr[0] + arr[1] * BASE;
  27859. default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE;
  27860. }
  27861. }
  27862. return arr;
  27863. }
  27864. function trim(v) {
  27865. var i = v.length;
  27866. while (v[--i] === 0);
  27867. v.length = i + 1;
  27868. }
  27869. function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger
  27870. var x = new Array(length);
  27871. var i = -1;
  27872. while (++i < length) {
  27873. x[i] = 0;
  27874. }
  27875. return x;
  27876. }
  27877. function truncate(n) {
  27878. if (n > 0) return Math.floor(n);
  27879. return Math.ceil(n);
  27880. }
  27881. function add(a, b) { // assumes a and b are arrays with a.length >= b.length
  27882. var l_a = a.length,
  27883. l_b = b.length,
  27884. r = new Array(l_a),
  27885. carry = 0,
  27886. base = BASE,
  27887. sum, i;
  27888. for (i = 0; i < l_b; i++) {
  27889. sum = a[i] + b[i] + carry;
  27890. carry = sum >= base ? 1 : 0;
  27891. r[i] = sum - carry * base;
  27892. }
  27893. while (i < l_a) {
  27894. sum = a[i] + carry;
  27895. carry = sum === base ? 1 : 0;
  27896. r[i++] = sum - carry * base;
  27897. }
  27898. if (carry > 0) r.push(carry);
  27899. return r;
  27900. }
  27901. function addAny(a, b) {
  27902. if (a.length >= b.length) return add(a, b);
  27903. return add(b, a);
  27904. }
  27905. function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT
  27906. var l = a.length,
  27907. r = new Array(l),
  27908. base = BASE,
  27909. sum, i;
  27910. for (i = 0; i < l; i++) {
  27911. sum = a[i] - base + carry;
  27912. carry = Math.floor(sum / base);
  27913. r[i] = sum - carry * base;
  27914. carry += 1;
  27915. }
  27916. while (carry > 0) {
  27917. r[i++] = carry % base;
  27918. carry = Math.floor(carry / base);
  27919. }
  27920. return r;
  27921. }
  27922. BigInteger.prototype.add = function (v) {
  27923. var n = parseValue(v);
  27924. if (this.sign !== n.sign) {
  27925. return this.subtract(n.negate());
  27926. }
  27927. var a = this.value, b = n.value;
  27928. if (n.isSmall) {
  27929. return new BigInteger(addSmall(a, Math.abs(b)), this.sign);
  27930. }
  27931. return new BigInteger(addAny(a, b), this.sign);
  27932. };
  27933. BigInteger.prototype.plus = BigInteger.prototype.add;
  27934. SmallInteger.prototype.add = function (v) {
  27935. var n = parseValue(v);
  27936. var a = this.value;
  27937. if (a < 0 !== n.sign) {
  27938. return this.subtract(n.negate());
  27939. }
  27940. var b = n.value;
  27941. if (n.isSmall) {
  27942. if (isPrecise(a + b)) return new SmallInteger(a + b);
  27943. b = smallToArray(Math.abs(b));
  27944. }
  27945. return new BigInteger(addSmall(b, Math.abs(a)), a < 0);
  27946. };
  27947. SmallInteger.prototype.plus = SmallInteger.prototype.add;
  27948. function subtract(a, b) { // assumes a and b are arrays with a >= b
  27949. var a_l = a.length,
  27950. b_l = b.length,
  27951. r = new Array(a_l),
  27952. borrow = 0,
  27953. base = BASE,
  27954. i, difference;
  27955. for (i = 0; i < b_l; i++) {
  27956. difference = a[i] - borrow - b[i];
  27957. if (difference < 0) {
  27958. difference += base;
  27959. borrow = 1;
  27960. } else borrow = 0;
  27961. r[i] = difference;
  27962. }
  27963. for (i = b_l; i < a_l; i++) {
  27964. difference = a[i] - borrow;
  27965. if (difference < 0) difference += base;
  27966. else {
  27967. r[i++] = difference;
  27968. break;
  27969. }
  27970. r[i] = difference;
  27971. }
  27972. for (; i < a_l; i++) {
  27973. r[i] = a[i];
  27974. }
  27975. trim(r);
  27976. return r;
  27977. }
  27978. function subtractAny(a, b, sign) {
  27979. var value;
  27980. if (compareAbs(a, b) >= 0) {
  27981. value = subtract(a,b);
  27982. } else {
  27983. value = subtract(b, a);
  27984. sign = !sign;
  27985. }
  27986. value = arrayToSmall(value);
  27987. if (typeof value === "number") {
  27988. if (sign) value = -value;
  27989. return new SmallInteger(value);
  27990. }
  27991. return new BigInteger(value, sign);
  27992. }
  27993. function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT
  27994. var l = a.length,
  27995. r = new Array(l),
  27996. carry = -b,
  27997. base = BASE,
  27998. i, difference;
  27999. for (i = 0; i < l; i++) {
  28000. difference = a[i] + carry;
  28001. carry = Math.floor(difference / base);
  28002. difference %= base;
  28003. r[i] = difference < 0 ? difference + base : difference;
  28004. }
  28005. r = arrayToSmall(r);
  28006. if (typeof r === "number") {
  28007. if (sign) r = -r;
  28008. return new SmallInteger(r);
  28009. } return new BigInteger(r, sign);
  28010. }
  28011. BigInteger.prototype.subtract = function (v) {
  28012. var n = parseValue(v);
  28013. if (this.sign !== n.sign) {
  28014. return this.add(n.negate());
  28015. }
  28016. var a = this.value, b = n.value;
  28017. if (n.isSmall)
  28018. return subtractSmall(a, Math.abs(b), this.sign);
  28019. return subtractAny(a, b, this.sign);
  28020. };
  28021. BigInteger.prototype.minus = BigInteger.prototype.subtract;
  28022. SmallInteger.prototype.subtract = function (v) {
  28023. var n = parseValue(v);
  28024. var a = this.value;
  28025. if (a < 0 !== n.sign) {
  28026. return this.add(n.negate());
  28027. }
  28028. var b = n.value;
  28029. if (n.isSmall) {
  28030. return new SmallInteger(a - b);
  28031. }
  28032. return subtractSmall(b, Math.abs(a), a >= 0);
  28033. };
  28034. SmallInteger.prototype.minus = SmallInteger.prototype.subtract;
  28035. BigInteger.prototype.negate = function () {
  28036. return new BigInteger(this.value, !this.sign);
  28037. };
  28038. SmallInteger.prototype.negate = function () {
  28039. var sign = this.sign;
  28040. var small = new SmallInteger(-this.value);
  28041. small.sign = !sign;
  28042. return small;
  28043. };
  28044. BigInteger.prototype.abs = function () {
  28045. return new BigInteger(this.value, false);
  28046. };
  28047. SmallInteger.prototype.abs = function () {
  28048. return new SmallInteger(Math.abs(this.value));
  28049. };
  28050. function multiplyLong(a, b) {
  28051. var a_l = a.length,
  28052. b_l = b.length,
  28053. l = a_l + b_l,
  28054. r = createArray(l),
  28055. base = BASE,
  28056. product, carry, i, a_i, b_j;
  28057. for (i = 0; i < a_l; ++i) {
  28058. a_i = a[i];
  28059. for (var j = 0; j < b_l; ++j) {
  28060. b_j = b[j];
  28061. product = a_i * b_j + r[i + j];
  28062. carry = Math.floor(product / base);
  28063. r[i + j] = product - carry * base;
  28064. r[i + j + 1] += carry;
  28065. }
  28066. }
  28067. trim(r);
  28068. return r;
  28069. }
  28070. function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE
  28071. var l = a.length,
  28072. r = new Array(l),
  28073. base = BASE,
  28074. carry = 0,
  28075. product, i;
  28076. for (i = 0; i < l; i++) {
  28077. product = a[i] * b + carry;
  28078. carry = Math.floor(product / base);
  28079. r[i] = product - carry * base;
  28080. }
  28081. while (carry > 0) {
  28082. r[i++] = carry % base;
  28083. carry = Math.floor(carry / base);
  28084. }
  28085. return r;
  28086. }
  28087. function shiftLeft(x, n) {
  28088. var r = [];
  28089. while (n-- > 0) r.push(0);
  28090. return r.concat(x);
  28091. }
  28092. function multiplyKaratsuba(x, y) {
  28093. var n = Math.max(x.length, y.length);
  28094. if (n <= 30) return multiplyLong(x, y);
  28095. n = Math.ceil(n / 2);
  28096. var b = x.slice(n),
  28097. a = x.slice(0, n),
  28098. d = y.slice(n),
  28099. c = y.slice(0, n);
  28100. var ac = multiplyKaratsuba(a, c),
  28101. bd = multiplyKaratsuba(b, d),
  28102. abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d));
  28103. var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n));
  28104. trim(product);
  28105. return product;
  28106. }
  28107. // The following function is derived from a surface fit of a graph plotting the performance difference
  28108. // between long multiplication and karatsuba multiplication versus the lengths of the two arrays.
  28109. function useKaratsuba(l1, l2) {
  28110. return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0;
  28111. }
  28112. BigInteger.prototype.multiply = function (v) {
  28113. var n = parseValue(v),
  28114. a = this.value, b = n.value,
  28115. sign = this.sign !== n.sign,
  28116. abs;
  28117. if (n.isSmall) {
  28118. if (b === 0) return Integer[0];
  28119. if (b === 1) return this;
  28120. if (b === -1) return this.negate();
  28121. abs = Math.abs(b);
  28122. if (abs < BASE) {
  28123. return new BigInteger(multiplySmall(a, abs), sign);
  28124. }
  28125. b = smallToArray(abs);
  28126. }
  28127. if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes
  28128. return new BigInteger(multiplyKaratsuba(a, b), sign);
  28129. return new BigInteger(multiplyLong(a, b), sign);
  28130. };
  28131. BigInteger.prototype.times = BigInteger.prototype.multiply;
  28132. function multiplySmallAndArray(a, b, sign) { // a >= 0
  28133. if (a < BASE) {
  28134. return new BigInteger(multiplySmall(b, a), sign);
  28135. }
  28136. return new BigInteger(multiplyLong(b, smallToArray(a)), sign);
  28137. }
  28138. SmallInteger.prototype._multiplyBySmall = function (a) {
  28139. if (isPrecise(a.value * this.value)) {
  28140. return new SmallInteger(a.value * this.value);
  28141. }
  28142. return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign);
  28143. };
  28144. BigInteger.prototype._multiplyBySmall = function (a) {
  28145. if (a.value === 0) return Integer[0];
  28146. if (a.value === 1) return this;
  28147. if (a.value === -1) return this.negate();
  28148. return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign);
  28149. };
  28150. SmallInteger.prototype.multiply = function (v) {
  28151. return parseValue(v)._multiplyBySmall(this);
  28152. };
  28153. SmallInteger.prototype.times = SmallInteger.prototype.multiply;
  28154. function square(a) {
  28155. var l = a.length,
  28156. r = createArray(l + l),
  28157. base = BASE,
  28158. product, carry, i, a_i, a_j;
  28159. for (i = 0; i < l; i++) {
  28160. a_i = a[i];
  28161. for (var j = 0; j < l; j++) {
  28162. a_j = a[j];
  28163. product = a_i * a_j + r[i + j];
  28164. carry = Math.floor(product / base);
  28165. r[i + j] = product - carry * base;
  28166. r[i + j + 1] += carry;
  28167. }
  28168. }
  28169. trim(r);
  28170. return r;
  28171. }
  28172. BigInteger.prototype.square = function () {
  28173. return new BigInteger(square(this.value), false);
  28174. };
  28175. SmallInteger.prototype.square = function () {
  28176. var value = this.value * this.value;
  28177. if (isPrecise(value)) return new SmallInteger(value);
  28178. return new BigInteger(square(smallToArray(Math.abs(this.value))), false);
  28179. };
  28180. function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes.
  28181. var a_l = a.length,
  28182. b_l = b.length,
  28183. base = BASE,
  28184. result = createArray(b.length),
  28185. divisorMostSignificantDigit = b[b_l - 1],
  28186. // normalization
  28187. lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)),
  28188. remainder = multiplySmall(a, lambda),
  28189. divisor = multiplySmall(b, lambda),
  28190. quotientDigit, shift, carry, borrow, i, l, q;
  28191. if (remainder.length <= a_l) remainder.push(0);
  28192. divisor.push(0);
  28193. divisorMostSignificantDigit = divisor[b_l - 1];
  28194. for (shift = a_l - b_l; shift >= 0; shift--) {
  28195. quotientDigit = base - 1;
  28196. if (remainder[shift + b_l] !== divisorMostSignificantDigit) {
  28197. quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit);
  28198. }
  28199. // quotientDigit <= base - 1
  28200. carry = 0;
  28201. borrow = 0;
  28202. l = divisor.length;
  28203. for (i = 0; i < l; i++) {
  28204. carry += quotientDigit * divisor[i];
  28205. q = Math.floor(carry / base);
  28206. borrow += remainder[shift + i] - (carry - q * base);
  28207. carry = q;
  28208. if (borrow < 0) {
  28209. remainder[shift + i] = borrow + base;
  28210. borrow = -1;
  28211. } else {
  28212. remainder[shift + i] = borrow;
  28213. borrow = 0;
  28214. }
  28215. }
  28216. while (borrow !== 0) {
  28217. quotientDigit -= 1;
  28218. carry = 0;
  28219. for (i = 0; i < l; i++) {
  28220. carry += remainder[shift + i] - base + divisor[i];
  28221. if (carry < 0) {
  28222. remainder[shift + i] = carry + base;
  28223. carry = 0;
  28224. } else {
  28225. remainder[shift + i] = carry;
  28226. carry = 1;
  28227. }
  28228. }
  28229. borrow += carry;
  28230. }
  28231. result[shift] = quotientDigit;
  28232. }
  28233. // denormalization
  28234. remainder = divModSmall(remainder, lambda)[0];
  28235. return [arrayToSmall(result), arrayToSmall(remainder)];
  28236. }
  28237. function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/
  28238. // Performs faster than divMod1 on larger input sizes.
  28239. var a_l = a.length,
  28240. b_l = b.length,
  28241. result = [],
  28242. part = [],
  28243. base = BASE,
  28244. guess, xlen, highx, highy, check;
  28245. while (a_l) {
  28246. part.unshift(a[--a_l]);
  28247. trim(part);
  28248. if (compareAbs(part, b) < 0) {
  28249. result.push(0);
  28250. continue;
  28251. }
  28252. xlen = part.length;
  28253. highx = part[xlen - 1] * base + part[xlen - 2];
  28254. highy = b[b_l - 1] * base + b[b_l - 2];
  28255. if (xlen > b_l) {
  28256. highx = (highx + 1) * base;
  28257. }
  28258. guess = Math.ceil(highx / highy);
  28259. do {
  28260. check = multiplySmall(b, guess);
  28261. if (compareAbs(check, part) <= 0) break;
  28262. guess--;
  28263. } while (guess);
  28264. result.push(guess);
  28265. part = subtract(part, check);
  28266. }
  28267. result.reverse();
  28268. return [arrayToSmall(result), arrayToSmall(part)];
  28269. }
  28270. function divModSmall(value, lambda) {
  28271. var length = value.length,
  28272. quotient = createArray(length),
  28273. base = BASE,
  28274. i, q, remainder, divisor;
  28275. remainder = 0;
  28276. for (i = length - 1; i >= 0; --i) {
  28277. divisor = remainder * base + value[i];
  28278. q = truncate(divisor / lambda);
  28279. remainder = divisor - q * lambda;
  28280. quotient[i] = q | 0;
  28281. }
  28282. return [quotient, remainder | 0];
  28283. }
  28284. function divModAny(self, v) {
  28285. var value, n = parseValue(v);
  28286. var a = self.value, b = n.value;
  28287. var quotient;
  28288. if (b === 0) throw new Error("Cannot divide by zero");
  28289. if (self.isSmall) {
  28290. if (n.isSmall) {
  28291. return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)];
  28292. }
  28293. return [Integer[0], self];
  28294. }
  28295. if (n.isSmall) {
  28296. if (b === 1) return [self, Integer[0]];
  28297. if (b == -1) return [self.negate(), Integer[0]];
  28298. var abs = Math.abs(b);
  28299. if (abs < BASE) {
  28300. value = divModSmall(a, abs);
  28301. quotient = arrayToSmall(value[0]);
  28302. var remainder = value[1];
  28303. if (self.sign) remainder = -remainder;
  28304. if (typeof quotient === "number") {
  28305. if (self.sign !== n.sign) quotient = -quotient;
  28306. return [new SmallInteger(quotient), new SmallInteger(remainder)];
  28307. }
  28308. return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)];
  28309. }
  28310. b = smallToArray(abs);
  28311. }
  28312. var comparison = compareAbs(a, b);
  28313. if (comparison === -1) return [Integer[0], self];
  28314. if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]];
  28315. // divMod1 is faster on smaller input sizes
  28316. if (a.length + b.length <= 200)
  28317. value = divMod1(a, b);
  28318. else value = divMod2(a, b);
  28319. quotient = value[0];
  28320. var qSign = self.sign !== n.sign,
  28321. mod = value[1],
  28322. mSign = self.sign;
  28323. if (typeof quotient === "number") {
  28324. if (qSign) quotient = -quotient;
  28325. quotient = new SmallInteger(quotient);
  28326. } else quotient = new BigInteger(quotient, qSign);
  28327. if (typeof mod === "number") {
  28328. if (mSign) mod = -mod;
  28329. mod = new SmallInteger(mod);
  28330. } else mod = new BigInteger(mod, mSign);
  28331. return [quotient, mod];
  28332. }
  28333. BigInteger.prototype.divmod = function (v) {
  28334. var result = divModAny(this, v);
  28335. return {
  28336. quotient: result[0],
  28337. remainder: result[1]
  28338. };
  28339. };
  28340. SmallInteger.prototype.divmod = BigInteger.prototype.divmod;
  28341. BigInteger.prototype.divide = function (v) {
  28342. return divModAny(this, v)[0];
  28343. };
  28344. SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide;
  28345. BigInteger.prototype.mod = function (v) {
  28346. return divModAny(this, v)[1];
  28347. };
  28348. SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod;
  28349. BigInteger.prototype.pow = function (v) {
  28350. var n = parseValue(v),
  28351. a = this.value,
  28352. b = n.value,
  28353. value, x, y;
  28354. if (b === 0) return Integer[1];
  28355. if (a === 0) return Integer[0];
  28356. if (a === 1) return Integer[1];
  28357. if (a === -1) return n.isEven() ? Integer[1] : Integer[-1];
  28358. if (n.sign) {
  28359. return Integer[0];
  28360. }
  28361. if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large.");
  28362. if (this.isSmall) {
  28363. if (isPrecise(value = Math.pow(a, b)))
  28364. return new SmallInteger(truncate(value));
  28365. }
  28366. x = this;
  28367. y = Integer[1];
  28368. while (true) {
  28369. if (b & 1 === 1) {
  28370. y = y.times(x);
  28371. --b;
  28372. }
  28373. if (b === 0) break;
  28374. b /= 2;
  28375. x = x.square();
  28376. }
  28377. return y;
  28378. };
  28379. SmallInteger.prototype.pow = BigInteger.prototype.pow;
  28380. BigInteger.prototype.modPow = function (exp, mod) {
  28381. exp = parseValue(exp);
  28382. mod = parseValue(mod);
  28383. if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0");
  28384. var r = Integer[1],
  28385. base = this.mod(mod);
  28386. while (exp.isPositive()) {
  28387. if (base.isZero()) return Integer[0];
  28388. if (exp.isOdd()) r = r.multiply(base).mod(mod);
  28389. exp = exp.divide(2);
  28390. base = base.square().mod(mod);
  28391. }
  28392. return r;
  28393. };
  28394. SmallInteger.prototype.modPow = BigInteger.prototype.modPow;
  28395. function compareAbs(a, b) {
  28396. if (a.length !== b.length) {
  28397. return a.length > b.length ? 1 : -1;
  28398. }
  28399. for (var i = a.length - 1; i >= 0; i--) {
  28400. if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;
  28401. }
  28402. return 0;
  28403. }
  28404. BigInteger.prototype.compareAbs = function (v) {
  28405. var n = parseValue(v),
  28406. a = this.value,
  28407. b = n.value;
  28408. if (n.isSmall) return 1;
  28409. return compareAbs(a, b);
  28410. };
  28411. SmallInteger.prototype.compareAbs = function (v) {
  28412. var n = parseValue(v),
  28413. a = Math.abs(this.value),
  28414. b = n.value;
  28415. if (n.isSmall) {
  28416. b = Math.abs(b);
  28417. return a === b ? 0 : a > b ? 1 : -1;
  28418. }
  28419. return -1;
  28420. };
  28421. BigInteger.prototype.compare = function (v) {
  28422. // See discussion about comparison with Infinity:
  28423. // https://github.com/peterolson/BigInteger.js/issues/61
  28424. if (v === Infinity) {
  28425. return -1;
  28426. }
  28427. if (v === -Infinity) {
  28428. return 1;
  28429. }
  28430. var n = parseValue(v),
  28431. a = this.value,
  28432. b = n.value;
  28433. if (this.sign !== n.sign) {
  28434. return n.sign ? 1 : -1;
  28435. }
  28436. if (n.isSmall) {
  28437. return this.sign ? -1 : 1;
  28438. }
  28439. return compareAbs(a, b) * (this.sign ? -1 : 1);
  28440. };
  28441. BigInteger.prototype.compareTo = BigInteger.prototype.compare;
  28442. SmallInteger.prototype.compare = function (v) {
  28443. if (v === Infinity) {
  28444. return -1;
  28445. }
  28446. if (v === -Infinity) {
  28447. return 1;
  28448. }
  28449. var n = parseValue(v),
  28450. a = this.value,
  28451. b = n.value;
  28452. if (n.isSmall) {
  28453. return a == b ? 0 : a > b ? 1 : -1;
  28454. }
  28455. if (a < 0 !== n.sign) {
  28456. return a < 0 ? -1 : 1;
  28457. }
  28458. return a < 0 ? 1 : -1;
  28459. };
  28460. SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;
  28461. BigInteger.prototype.equals = function (v) {
  28462. return this.compare(v) === 0;
  28463. };
  28464. SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals;
  28465. BigInteger.prototype.notEquals = function (v) {
  28466. return this.compare(v) !== 0;
  28467. };
  28468. SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals;
  28469. BigInteger.prototype.greater = function (v) {
  28470. return this.compare(v) > 0;
  28471. };
  28472. SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater;
  28473. BigInteger.prototype.lesser = function (v) {
  28474. return this.compare(v) < 0;
  28475. };
  28476. SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser;
  28477. BigInteger.prototype.greaterOrEquals = function (v) {
  28478. return this.compare(v) >= 0;
  28479. };
  28480. SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals;
  28481. BigInteger.prototype.lesserOrEquals = function (v) {
  28482. return this.compare(v) <= 0;
  28483. };
  28484. SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals;
  28485. BigInteger.prototype.isEven = function () {
  28486. return (this.value[0] & 1) === 0;
  28487. };
  28488. SmallInteger.prototype.isEven = function () {
  28489. return (this.value & 1) === 0;
  28490. };
  28491. BigInteger.prototype.isOdd = function () {
  28492. return (this.value[0] & 1) === 1;
  28493. };
  28494. SmallInteger.prototype.isOdd = function () {
  28495. return (this.value & 1) === 1;
  28496. };
  28497. BigInteger.prototype.isPositive = function () {
  28498. return !this.sign;
  28499. };
  28500. SmallInteger.prototype.isPositive = function () {
  28501. return this.value > 0;
  28502. };
  28503. BigInteger.prototype.isNegative = function () {
  28504. return this.sign;
  28505. };
  28506. SmallInteger.prototype.isNegative = function () {
  28507. return this.value < 0;
  28508. };
  28509. BigInteger.prototype.isUnit = function () {
  28510. return false;
  28511. };
  28512. SmallInteger.prototype.isUnit = function () {
  28513. return Math.abs(this.value) === 1;
  28514. };
  28515. BigInteger.prototype.isZero = function () {
  28516. return false;
  28517. };
  28518. SmallInteger.prototype.isZero = function () {
  28519. return this.value === 0;
  28520. };
  28521. BigInteger.prototype.isDivisibleBy = function (v) {
  28522. var n = parseValue(v);
  28523. var value = n.value;
  28524. if (value === 0) return false;
  28525. if (value === 1) return true;
  28526. if (value === 2) return this.isEven();
  28527. return this.mod(n).equals(Integer[0]);
  28528. };
  28529. SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy;
  28530. function isBasicPrime(v) {
  28531. var n = v.abs();
  28532. if (n.isUnit()) return false;
  28533. if (n.equals(2) || n.equals(3) || n.equals(5)) return true;
  28534. if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false;
  28535. if (n.lesser(25)) return true;
  28536. // we don't know if it's prime: let the other functions figure it out
  28537. }
  28538. BigInteger.prototype.isPrime = function () {
  28539. var isPrime = isBasicPrime(this);
  28540. if (isPrime !== undefined) return isPrime;
  28541. var n = this.abs(),
  28542. nPrev = n.prev();
  28543. var a = [2, 3, 5, 7, 11, 13, 17, 19],
  28544. b = nPrev,
  28545. d, t, i, x;
  28546. while (b.isEven()) b = b.divide(2);
  28547. for (i = 0; i < a.length; i++) {
  28548. x = bigInt(a[i]).modPow(b, n);
  28549. if (x.equals(Integer[1]) || x.equals(nPrev)) continue;
  28550. for (t = true, d = b; t && d.lesser(nPrev) ; d = d.multiply(2)) {
  28551. x = x.square().mod(n);
  28552. if (x.equals(nPrev)) t = false;
  28553. }
  28554. if (t) return false;
  28555. }
  28556. return true;
  28557. };
  28558. SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime;
  28559. BigInteger.prototype.isProbablePrime = function (iterations) {
  28560. var isPrime = isBasicPrime(this);
  28561. if (isPrime !== undefined) return isPrime;
  28562. var n = this.abs();
  28563. var t = iterations === undefined ? 5 : iterations;
  28564. // use the Fermat primality test
  28565. for (var i = 0; i < t; i++) {
  28566. var a = bigInt.randBetween(2, n.minus(2));
  28567. if (!a.modPow(n.prev(), n).isUnit()) return false; // definitely composite
  28568. }
  28569. return true; // large chance of being prime
  28570. };
  28571. SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime;
  28572. BigInteger.prototype.modInv = function (n) {
  28573. var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR;
  28574. while (!newR.equals(bigInt.zero)) {
  28575. q = r.divide(newR);
  28576. lastT = t;
  28577. lastR = r;
  28578. t = newT;
  28579. r = newR;
  28580. newT = lastT.subtract(q.multiply(newT));
  28581. newR = lastR.subtract(q.multiply(newR));
  28582. }
  28583. if (!r.equals(1)) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime");
  28584. if (t.compare(0) === -1) {
  28585. t = t.add(n);
  28586. }
  28587. if (this.isNegative()) {
  28588. return t.negate();
  28589. }
  28590. return t;
  28591. };
  28592. SmallInteger.prototype.modInv = BigInteger.prototype.modInv;
  28593. BigInteger.prototype.next = function () {
  28594. var value = this.value;
  28595. if (this.sign) {
  28596. return subtractSmall(value, 1, this.sign);
  28597. }
  28598. return new BigInteger(addSmall(value, 1), this.sign);
  28599. };
  28600. SmallInteger.prototype.next = function () {
  28601. var value = this.value;
  28602. if (value + 1 < MAX_INT) return new SmallInteger(value + 1);
  28603. return new BigInteger(MAX_INT_ARR, false);
  28604. };
  28605. BigInteger.prototype.prev = function () {
  28606. var value = this.value;
  28607. if (this.sign) {
  28608. return new BigInteger(addSmall(value, 1), true);
  28609. }
  28610. return subtractSmall(value, 1, this.sign);
  28611. };
  28612. SmallInteger.prototype.prev = function () {
  28613. var value = this.value;
  28614. if (value - 1 > -MAX_INT) return new SmallInteger(value - 1);
  28615. return new BigInteger(MAX_INT_ARR, true);
  28616. };
  28617. var powersOfTwo = [1];
  28618. while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);
  28619. var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1];
  28620. function shift_isSmall(n) {
  28621. return ((typeof n === "number" || typeof n === "string") && +Math.abs(n) <= BASE) ||
  28622. (n instanceof BigInteger && n.value.length <= 1);
  28623. }
  28624. BigInteger.prototype.shiftLeft = function (n) {
  28625. if (!shift_isSmall(n)) {
  28626. throw new Error(String(n) + " is too large for shifting.");
  28627. }
  28628. n = +n;
  28629. if (n < 0) return this.shiftRight(-n);
  28630. var result = this;
  28631. while (n >= powers2Length) {
  28632. result = result.multiply(highestPower2);
  28633. n -= powers2Length - 1;
  28634. }
  28635. return result.multiply(powersOfTwo[n]);
  28636. };
  28637. SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft;
  28638. BigInteger.prototype.shiftRight = function (n) {
  28639. var remQuo;
  28640. if (!shift_isSmall(n)) {
  28641. throw new Error(String(n) + " is too large for shifting.");
  28642. }
  28643. n = +n;
  28644. if (n < 0) return this.shiftLeft(-n);
  28645. var result = this;
  28646. while (n >= powers2Length) {
  28647. if (result.isZero()) return result;
  28648. remQuo = divModAny(result, highestPower2);
  28649. result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
  28650. n -= powers2Length - 1;
  28651. }
  28652. remQuo = divModAny(result, powersOfTwo[n]);
  28653. return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
  28654. };
  28655. SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight;
  28656. function bitwise(x, y, fn) {
  28657. y = parseValue(y);
  28658. var xSign = x.isNegative(), ySign = y.isNegative();
  28659. var xRem = xSign ? x.not() : x,
  28660. yRem = ySign ? y.not() : y;
  28661. var xDigit = 0, yDigit = 0;
  28662. var xDivMod = null, yDivMod = null;
  28663. var result = [];
  28664. while (!xRem.isZero() || !yRem.isZero()) {
  28665. xDivMod = divModAny(xRem, highestPower2);
  28666. xDigit = xDivMod[1].toJSNumber();
  28667. if (xSign) {
  28668. xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers
  28669. }
  28670. yDivMod = divModAny(yRem, highestPower2);
  28671. yDigit = yDivMod[1].toJSNumber();
  28672. if (ySign) {
  28673. yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers
  28674. }
  28675. xRem = xDivMod[0];
  28676. yRem = yDivMod[0];
  28677. result.push(fn(xDigit, yDigit));
  28678. }
  28679. var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0);
  28680. for (var i = result.length - 1; i >= 0; i -= 1) {
  28681. sum = sum.multiply(highestPower2).add(bigInt(result[i]));
  28682. }
  28683. return sum;
  28684. }
  28685. BigInteger.prototype.not = function () {
  28686. return this.negate().prev();
  28687. };
  28688. SmallInteger.prototype.not = BigInteger.prototype.not;
  28689. BigInteger.prototype.and = function (n) {
  28690. return bitwise(this, n, function (a, b) { return a & b; });
  28691. };
  28692. SmallInteger.prototype.and = BigInteger.prototype.and;
  28693. BigInteger.prototype.or = function (n) {
  28694. return bitwise(this, n, function (a, b) { return a | b; });
  28695. };
  28696. SmallInteger.prototype.or = BigInteger.prototype.or;
  28697. BigInteger.prototype.xor = function (n) {
  28698. return bitwise(this, n, function (a, b) { return a ^ b; });
  28699. };
  28700. SmallInteger.prototype.xor = BigInteger.prototype.xor;
  28701. var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I;
  28702. function roughLOB(n) { // get lowestOneBit (rough)
  28703. // SmallInteger: return Min(lowestOneBit(n), 1 << 30)
  28704. // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7]
  28705. var v = n.value, x = typeof v === "number" ? v | LOBMASK_I : v[0] + v[1] * BASE | LOBMASK_BI;
  28706. return x & -x;
  28707. }
  28708. function max(a, b) {
  28709. a = parseValue(a);
  28710. b = parseValue(b);
  28711. return a.greater(b) ? a : b;
  28712. }
  28713. function min(a, b) {
  28714. a = parseValue(a);
  28715. b = parseValue(b);
  28716. return a.lesser(b) ? a : b;
  28717. }
  28718. function gcd(a, b) {
  28719. a = parseValue(a).abs();
  28720. b = parseValue(b).abs();
  28721. if (a.equals(b)) return a;
  28722. if (a.isZero()) return b;
  28723. if (b.isZero()) return a;
  28724. var c = Integer[1], d, t;
  28725. while (a.isEven() && b.isEven()) {
  28726. d = Math.min(roughLOB(a), roughLOB(b));
  28727. a = a.divide(d);
  28728. b = b.divide(d);
  28729. c = c.multiply(d);
  28730. }
  28731. while (a.isEven()) {
  28732. a = a.divide(roughLOB(a));
  28733. }
  28734. do {
  28735. while (b.isEven()) {
  28736. b = b.divide(roughLOB(b));
  28737. }
  28738. if (a.greater(b)) {
  28739. t = b; b = a; a = t;
  28740. }
  28741. b = b.subtract(a);
  28742. } while (!b.isZero());
  28743. return c.isUnit() ? a : a.multiply(c);
  28744. }
  28745. function lcm(a, b) {
  28746. a = parseValue(a).abs();
  28747. b = parseValue(b).abs();
  28748. return a.divide(gcd(a, b)).multiply(b);
  28749. }
  28750. function randBetween(a, b) {
  28751. a = parseValue(a);
  28752. b = parseValue(b);
  28753. var low = min(a, b), high = max(a, b);
  28754. var range = high.subtract(low).add(1);
  28755. if (range.isSmall) return low.add(Math.floor(Math.random() * range));
  28756. var length = range.value.length - 1;
  28757. var result = [], restricted = true;
  28758. for (var i = length; i >= 0; i--) {
  28759. var top = restricted ? range.value[i] : BASE;
  28760. var digit = truncate(Math.random() * top);
  28761. result.unshift(digit);
  28762. if (digit < top) restricted = false;
  28763. }
  28764. result = arrayToSmall(result);
  28765. return low.add(typeof result === "number" ? new SmallInteger(result) : new BigInteger(result, false));
  28766. }
  28767. var parseBase = function (text, base) {
  28768. var length = text.length;
  28769. var i;
  28770. var absBase = Math.abs(base);
  28771. for(var i = 0; i < length; i++) {
  28772. var c = text[i].toLowerCase();
  28773. if(c === "-") continue;
  28774. if(/[a-z0-9]/.test(c)) {
  28775. if(/[0-9]/.test(c) && +c >= absBase) {
  28776. if(c === "1" && absBase === 1) continue;
  28777. throw new Error(c + " is not a valid digit in base " + base + ".");
  28778. } else if(c.charCodeAt(0) - 87 >= absBase) {
  28779. throw new Error(c + " is not a valid digit in base " + base + ".");
  28780. }
  28781. }
  28782. }
  28783. if (2 <= base && base <= 36) {
  28784. if (length <= LOG_MAX_INT / Math.log(base)) {
  28785. var result = parseInt(text, base);
  28786. if(isNaN(result)) {
  28787. throw new Error(c + " is not a valid digit in base " + base + ".");
  28788. }
  28789. return new SmallInteger(parseInt(text, base));
  28790. }
  28791. }
  28792. base = parseValue(base);
  28793. var digits = [];
  28794. var isNegative = text[0] === "-";
  28795. for (i = isNegative ? 1 : 0; i < text.length; i++) {
  28796. var c = text[i].toLowerCase(),
  28797. charCode = c.charCodeAt(0);
  28798. if (48 <= charCode && charCode <= 57) digits.push(parseValue(c));
  28799. else if (97 <= charCode && charCode <= 122) digits.push(parseValue(c.charCodeAt(0) - 87));
  28800. else if (c === "<") {
  28801. var start = i;
  28802. do { i++; } while (text[i] !== ">");
  28803. digits.push(parseValue(text.slice(start + 1, i)));
  28804. }
  28805. else throw new Error(c + " is not a valid character");
  28806. }
  28807. return parseBaseFromArray(digits, base, isNegative);
  28808. };
  28809. function parseBaseFromArray(digits, base, isNegative) {
  28810. var val = Integer[0], pow = Integer[1], i;
  28811. for (i = digits.length - 1; i >= 0; i--) {
  28812. val = val.add(digits[i].times(pow));
  28813. pow = pow.times(base);
  28814. }
  28815. return isNegative ? val.negate() : val;
  28816. }
  28817. function stringify(digit) {
  28818. var v = digit.value;
  28819. if (typeof v === "number") v = [v];
  28820. if (v.length === 1 && v[0] <= 35) {
  28821. return "0123456789abcdefghijklmnopqrstuvwxyz".charAt(v[0]);
  28822. }
  28823. return "<" + v + ">";
  28824. }
  28825. function toBase(n, base) {
  28826. base = bigInt(base);
  28827. if (base.isZero()) {
  28828. if (n.isZero()) return "0";
  28829. throw new Error("Cannot convert nonzero numbers to base 0.");
  28830. }
  28831. if (base.equals(-1)) {
  28832. if (n.isZero()) return "0";
  28833. if (n.isNegative()) return new Array(1 - n).join("10");
  28834. return "1" + new Array(+n).join("01");
  28835. }
  28836. var minusSign = "";
  28837. if (n.isNegative() && base.isPositive()) {
  28838. minusSign = "-";
  28839. n = n.abs();
  28840. }
  28841. if (base.equals(1)) {
  28842. if (n.isZero()) return "0";
  28843. return minusSign + new Array(+n + 1).join(1);
  28844. }
  28845. var out = [];
  28846. var left = n, divmod;
  28847. while (left.isNegative() || left.compareAbs(base) >= 0) {
  28848. divmod = left.divmod(base);
  28849. left = divmod.quotient;
  28850. var digit = divmod.remainder;
  28851. if (digit.isNegative()) {
  28852. digit = base.minus(digit).abs();
  28853. left = left.next();
  28854. }
  28855. out.push(stringify(digit));
  28856. }
  28857. out.push(stringify(left));
  28858. return minusSign + out.reverse().join("");
  28859. }
  28860. BigInteger.prototype.toString = function (radix) {
  28861. if (radix === undefined) radix = 10;
  28862. if (radix !== 10) return toBase(this, radix);
  28863. var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit;
  28864. while (--l >= 0) {
  28865. digit = String(v[l]);
  28866. str += zeros.slice(digit.length) + digit;
  28867. }
  28868. var sign = this.sign ? "-" : "";
  28869. return sign + str;
  28870. };
  28871. SmallInteger.prototype.toString = function (radix) {
  28872. if (radix === undefined) radix = 10;
  28873. if (radix != 10) return toBase(this, radix);
  28874. return String(this.value);
  28875. };
  28876. BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function() { return this.toString(); }
  28877. BigInteger.prototype.valueOf = function () {
  28878. return +this.toString();
  28879. };
  28880. BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;
  28881. SmallInteger.prototype.valueOf = function () {
  28882. return this.value;
  28883. };
  28884. SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;
  28885. function parseStringValue(v) {
  28886. if (isPrecise(+v)) {
  28887. var x = +v;
  28888. if (x === truncate(x))
  28889. return new SmallInteger(x);
  28890. throw "Invalid integer: " + v;
  28891. }
  28892. var sign = v[0] === "-";
  28893. if (sign) v = v.slice(1);
  28894. var split = v.split(/e/i);
  28895. if (split.length > 2) throw new Error("Invalid integer: " + split.join("e"));
  28896. if (split.length === 2) {
  28897. var exp = split[1];
  28898. if (exp[0] === "+") exp = exp.slice(1);
  28899. exp = +exp;
  28900. if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent.");
  28901. var text = split[0];
  28902. var decimalPlace = text.indexOf(".");
  28903. if (decimalPlace >= 0) {
  28904. exp -= text.length - decimalPlace - 1;
  28905. text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);
  28906. }
  28907. if (exp < 0) throw new Error("Cannot include negative exponent part for integers");
  28908. text += (new Array(exp + 1)).join("0");
  28909. v = text;
  28910. }
  28911. var isValid = /^([0-9][0-9]*)$/.test(v);
  28912. if (!isValid) throw new Error("Invalid integer: " + v);
  28913. var r = [], max = v.length, l = LOG_BASE, min = max - l;
  28914. while (max > 0) {
  28915. r.push(+v.slice(min, max));
  28916. min -= l;
  28917. if (min < 0) min = 0;
  28918. max -= l;
  28919. }
  28920. trim(r);
  28921. return new BigInteger(r, sign);
  28922. }
  28923. function parseNumberValue(v) {
  28924. if (isPrecise(v)) {
  28925. if (v !== truncate(v)) throw new Error(v + " is not an integer.");
  28926. return new SmallInteger(v);
  28927. }
  28928. return parseStringValue(v.toString());
  28929. }
  28930. function parseValue(v) {
  28931. if (typeof v === "number") {
  28932. return parseNumberValue(v);
  28933. }
  28934. if (typeof v === "string") {
  28935. return parseStringValue(v);
  28936. }
  28937. return v;
  28938. }
  28939. // Pre-define numbers in range [-999,999]
  28940. for (var i = 0; i < 1000; i++) {
  28941. Integer[i] = new SmallInteger(i);
  28942. if (i > 0) Integer[-i] = new SmallInteger(-i);
  28943. }
  28944. // Backwards compatibility
  28945. Integer.one = Integer[1];
  28946. Integer.zero = Integer[0];
  28947. Integer.minusOne = Integer[-1];
  28948. Integer.max = max;
  28949. Integer.min = min;
  28950. Integer.gcd = gcd;
  28951. Integer.lcm = lcm;
  28952. Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger; };
  28953. Integer.randBetween = randBetween;
  28954. Integer.fromArray = function (digits, base, isNegative) {
  28955. return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative);
  28956. };
  28957. return Integer;
  28958. })();
  28959. // Node.js check
  28960. if (typeof module !== "undefined" && module.hasOwnProperty("exports")) {
  28961. module.exports = bigInt;
  28962. }
  28963. //amd check
  28964. if ( typeof define === "function" && define.amd ) {
  28965. define( "big-integer", [], function() {
  28966. return bigInt;
  28967. });
  28968. }
  28969. },{}],179:[function(require,module,exports){
  28970. arguments[4][157][0].apply(exports,arguments)
  28971. },{"buffer":50,"dup":157}],180:[function(require,module,exports){
  28972. function getpath(obj, path) {
  28973. path = path || "";
  28974. var arr = path.split(".");
  28975. var t = obj;
  28976. var done = false;
  28977. if (arr.length) {
  28978. while (arr.length && !done) {
  28979. var check = arr.shift();
  28980. if (check !== "") {
  28981. t = t[check];
  28982. }
  28983. if (typeof t !== "object") {
  28984. done = true;
  28985. }
  28986. }
  28987. }
  28988. return t;
  28989. }
  28990. function setpath(obj, path, value) {
  28991. if (typeof obj !== "object" || !obj) {
  28992. throw new Error("obj is not Object");
  28993. }
  28994. if (typeof path !== "string" || path === "") {
  28995. throw new Error("path must be string with length > 0");
  28996. }
  28997. var arr = path.split(".");
  28998. var done = false;
  28999. var t = obj;
  29000. if (arr.length > 1) {
  29001. while (arr.length && t && !done) {
  29002. var check = arr.shift();
  29003. if (typeof t[check] === "object" && arr.length > 0) {
  29004. t = t[check];
  29005. } else {
  29006. done = true;
  29007. arr.unshift(check);
  29008. }
  29009. }
  29010. var xt = t;
  29011. while (arr.length) {
  29012. var tt = arr.shift();
  29013. if (arr.length) { //go deeper
  29014. xt = xt[tt] = {};
  29015. } else {
  29016. //last
  29017. xt[tt] = value;
  29018. }
  29019. }
  29020. } else {
  29021. if (arr.length === 1 && arr[0] !== "") {
  29022. t[arr[0]] = value;
  29023. }
  29024. }
  29025. }
  29026. function sort_by_1_col(a, b) {
  29027. return a[0] > b[0] ? -1 : a[0] < b[0] ? 1 : 0;
  29028. }
  29029. function sort_by_1_col_alpha(a, b) {
  29030. var x = a[0].toLowerCase(),
  29031. y = b[0].toLowerCase();
  29032. return x < y ? -1 : x > y ? 1 : 0;
  29033. }
  29034. function query(obj, str) {
  29035. console.log(obj);
  29036. console.log(str);
  29037. }
  29038. function flatten(obj, pre) {
  29039. var pre = pre || "";
  29040. var r = [];
  29041. for (var i in obj) {
  29042. if (typeof(obj[i]) === "object") {
  29043. r = r.concat(flatten(obj[i], (pre.length > 0 ? pre + "." : "") + i));
  29044. } else {
  29045. r.push([(pre.length > 0 ? pre + "." : "") + i, "" + obj[i]]);
  29046. }
  29047. }
  29048. r.sort(sort_by_1_col_alpha)
  29049. return r;
  29050. }
  29051. module.exports = {
  29052. get: getpath,
  29053. set: setpath,
  29054. flatten: flatten,
  29055. query: query
  29056. }
  29057. },{}],181:[function(require,module,exports){
  29058. function stringify(obj, replacer, spaces, cycleReplacer) {
  29059. return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces)
  29060. }
  29061. function serializer(replacer, cycleReplacer) {
  29062. var stack = [],
  29063. keys = []
  29064. if (cycleReplacer == null) cycleReplacer = function(key, value) {
  29065. if (stack[0] === value) return "[Circular ~]"
  29066. return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]"
  29067. }
  29068. return function(key, value) {
  29069. if (stack.length > 0) {
  29070. var thisPos = stack.indexOf(this);
  29071. (~thisPos) ? stack.splice(thisPos + 1) : stack.push(this);
  29072. (~thisPos) ? keys.splice(thisPos, Infinity, key) : keys.push(key);
  29073. if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value)
  29074. } else stack.push(value)
  29075. return replacer == null ? value : replacer.call(this, key, value)
  29076. }
  29077. }
  29078. var Mash = function() {
  29079. // var n = 0xefc8249d;
  29080. var n = 0xbadebabe;
  29081. var mash = function(data) {
  29082. if (data) {
  29083. data = data.toString();
  29084. for (var i = 0; i < data.length; i++) {
  29085. n += data.charCodeAt(i);
  29086. var h = 0.02519603282416938 * n;
  29087. n = h >>> 0;
  29088. h -= n;
  29089. h *= n;
  29090. n = h >>> 0;
  29091. h -= n;
  29092. n += h * 0x100000000; // 2^32
  29093. }
  29094. return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
  29095. } else {
  29096. n = 0xbadebabe;
  29097. }
  29098. };
  29099. return mash;
  29100. };
  29101. var uheprng = function(seed) {
  29102. return (function() {
  29103. var o = 48; // set the 'order' number of ENTROPY-holding 32-bit values
  29104. var c = 1; // init the 'carry' used by the multiply-with-carry (MWC) algorithm
  29105. var p = o; // init the 'phase' (max-1) of the intermediate variable pointer
  29106. var s = new Array(o); // declare our intermediate variables array
  29107. var i; // general purpose local
  29108. var j; // general purpose local
  29109. var k = 0; // general purpose local
  29110. // when our "uheprng" is initially invoked our PRNG state is initialized from the
  29111. // browser's own local PRNG. This is okay since although its generator might not
  29112. // be wonderful, it's useful for establishing large startup entropy for our usage.
  29113. var mash = new Mash(); // get a pointer to our high-performance "Mash" hash
  29114. // fill the array with initial mash hash values
  29115. for (i = 0; i < o; i++) {
  29116. s[i] = mash(Math.random());
  29117. }
  29118. // this PRIVATE (internal access only) function is the heart of the multiply-with-carry
  29119. // (MWC) PRNG algorithm. When called it returns a pseudo-random number in the form of a
  29120. // 32-bit JavaScript fraction (0.0 to <1.0) it is a PRIVATE function used by the default
  29121. // [0-1] return function, and by the random 'string(n)' function which returns 'n'
  29122. // characters from 33 to 126.
  29123. var rawprng = function() {
  29124. if (++p >= o) {
  29125. p = 0;
  29126. }
  29127. var t = 1768863 * s[p] + c * 2.3283064365386963e-10; // 2^-32
  29128. return s[p] = t - (c = t | 0);
  29129. };
  29130. // this EXPORTED function is the default function returned by this library.
  29131. // The values returned are integers in the range from 0 to range-1. We first
  29132. // obtain two 32-bit fractions (from rawprng) to synthesize a single high
  29133. // resolution 53-bit prng (0 to <1), then we multiply this by the caller's
  29134. // "range" param and take the "floor" to return a equally probable integer.
  29135. var random = function(range) {
  29136. return Math.floor(range * (rawprng() + (rawprng() * 0x200000 | 0) * 1.1102230246251565e-16)); // 2^-53
  29137. };
  29138. // this EXPORTED function 'string(n)' returns a pseudo-random string of
  29139. // 'n' printable characters ranging from chr(33) to chr(126) inclusive.
  29140. random.string = function(count) {
  29141. var i;
  29142. var s = '';
  29143. for (i = 0; i < count; i++) {
  29144. s += String.fromCharCode(33 + random(94));
  29145. }
  29146. return s;
  29147. };
  29148. // this PRIVATE "hash" function is used to evolve the generator's internal
  29149. // entropy state. It is also called by the EXPORTED addEntropy() function
  29150. // which is used to pour entropy into the PRNG.
  29151. var hash = function() {
  29152. var args = Array.prototype.slice.call(arguments);
  29153. for (i = 0; i < args.length; i++) {
  29154. for (j = 0; j < o; j++) {
  29155. s[j] -= mash(args[i]);
  29156. if (s[j] < 0) {
  29157. s[j] += 1;
  29158. }
  29159. }
  29160. }
  29161. };
  29162. // this EXPORTED "clean string" function removes leading and trailing spaces and non-printing
  29163. // control characters, including any embedded carriage-return (CR) and line-feed (LF) characters,
  29164. // from any string it is handed. this is also used by the 'hashstring' function (below) to help
  29165. // users always obtain the same EFFECTIVE uheprng seeding key.
  29166. random.cleanString = function(inStr) {
  29167. inStr = inStr.replace(/(^\s*)|(\s*$)/gi, ''); // remove any/all leading spaces
  29168. inStr = inStr.replace(/[\x00-\x1F]/gi, ''); // remove any/all control characters
  29169. inStr = inStr.replace(/\n /, '\n'); // remove any/all trailing spaces
  29170. return inStr; // return the cleaned up result
  29171. };
  29172. // this EXPORTED "hash string" function hashes the provided character string after first removing
  29173. // any leading or trailing spaces and ignoring any embedded carriage returns (CR) or Line Feeds (LF)
  29174. random.hashString = function(inStr) {
  29175. inStr = random.cleanString(inStr);
  29176. mash(inStr); // use the string to evolve the 'mash' state
  29177. for (i = 0; i < inStr.length; i++) { // scan through the characters in our string
  29178. k = inStr.charCodeAt(i); // get the character code at the location
  29179. for (j = 0; j < o; j++) { // "mash" it into the UHEPRNG state
  29180. s[j] -= mash(k);
  29181. if (s[j] < 0) {
  29182. s[j] += 1;
  29183. }
  29184. }
  29185. }
  29186. };
  29187. // this EXPORTED function allows you to seed the random generator.
  29188. random.seed = function(seed) {
  29189. if (typeof seed === 'undefined' || seed === null) {
  29190. seed = Math.random();
  29191. }
  29192. if (typeof seed !== 'string') {
  29193. seed = stringify(seed, function(key, value) {
  29194. if (typeof value === 'function') {
  29195. return (value).toString();
  29196. }
  29197. return value;
  29198. });
  29199. }
  29200. random.initState();
  29201. random.hashString(seed);
  29202. };
  29203. // this handy exported function is used to add entropy to our uheprng at any time
  29204. random.addEntropy = function( /* accept zero or more arguments */ ) {
  29205. var args = [];
  29206. for (i = 0; i < arguments.length; i++) {
  29207. args.push(arguments[i]);
  29208. }
  29209. hash(args.join(''));
  29210. };
  29211. // if we want to provide a deterministic startup context for our PRNG,
  29212. // but without directly setting the internal state variables, this allows
  29213. // us to initialize the mash hash and PRNG's internal state before providing
  29214. // some hashing input
  29215. random.initState = function() {
  29216. mash(); // pass a null arg to force mash hash to init
  29217. for (i = 0; i < o; i++) {
  29218. s[i] = mash(' '); // fill the array with initial mash hash values
  29219. }
  29220. c = 1; // init our multiply-with-carry carry
  29221. p = o; // init our phase
  29222. };
  29223. // we use this (optional) exported function to signal the JavaScript interpreter
  29224. // that we're finished using the "Mash" hash function so that it can free up the
  29225. // local "instance variables" is will have been maintaining. It's not strictly
  29226. // necessary, of course, but it's good JavaScript citizenship.
  29227. random.done = function() {
  29228. mash = null;
  29229. };
  29230. // if we called "uheprng" with a seed value, then execute random.seed() before returning
  29231. if (typeof seed !== 'undefined') {
  29232. random.seed(seed);
  29233. }
  29234. // Returns a random integer between 0 (inclusive) and range (exclusive)
  29235. random.range = function(range) {
  29236. return random(range);
  29237. };
  29238. // Returns a random float between 0 (inclusive) and 1 (exclusive)
  29239. random.random = function() {
  29240. return random(Number.MAX_VALUE - 1) / Number.MAX_VALUE;
  29241. };
  29242. // Returns a random float between min (inclusive) and max (exclusive)
  29243. random.floatBetween = function(min, max) {
  29244. return random.random() * (max - min) + min;
  29245. };
  29246. // Returns a random integer between min (inclusive) and max (inclusive)
  29247. random.intBetween = function(min, max) {
  29248. return Math.floor(random.random() * (max - min + 1)) + min;
  29249. };
  29250. // when our main outer "uheprng" function is called, after setting up our
  29251. // initial variables and entropic state, we return an "instance pointer"
  29252. // to the internal anonymous function which can then be used to access
  29253. // the uheprng's various exported functions. As with the ".done" function
  29254. // above, we should set the returned value to 'null' once we're finished
  29255. // using any of these functions.
  29256. return random;
  29257. }());
  29258. };
  29259. // Modification for use in node:
  29260. uheprng.create = function(seed) {
  29261. return new uheprng(seed);
  29262. };
  29263. module.exports = uheprng;
  29264. },{}]},{},[173])(173)
  29265. });